30
\$\begingroup\$

It's a normal truth machine but instead of taking input, it uses the first character of the program. Thus, internal.

The 0 and 1 are plain characters, i.e. ASCII code 0x30 and 0x31 respectively.

Example: 0abcd prints 0 and halts, and 1abcd prints 1 infinitely. Then your submission is abcd, whose score is 4 bytes. The 0 or 1 (the first character of the program) is not counted towards your score.

Of course, you're not allowed to look inside the file itself. Like a quine.

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 198288; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();
    
    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
  • 4
    \$\begingroup\$ Wait, why did you post it so fast from the Sandbox? \$\endgroup\$ – user85052 Jan 21 at 14:01
  • 6
    \$\begingroup\$ So, to make sure I understand, this requires two programs in the same language that differ only in the first character being either 0 or 1? \$\endgroup\$ – histocrat Jan 21 at 14:02
  • 5
    \$\begingroup\$ Quasi-duplicate of Implement a Truth-Machine. The added restriction on input doesn't make it distinct in an interesting way. \$\endgroup\$ – Grimmy Jan 21 at 15:39
  • 6
    \$\begingroup\$ @LuisMendo, But I think one major qualification for whether a question here is a duplicate is whether the answers here would answer the question for the proposed duplicate (even with trivial changes). But I don't think that is the case. Maybe for a couple of languages. But not for many of these. The Lua answer there would not work here, and in fact, it's impossible to answer this challenge here in Lua. That certainly has to be taken into consideration. \$\endgroup\$ – ouflak Jan 21 at 16:33
  • 2
    \$\begingroup\$ Although I agree with Grimmy and something else could have been chosen as output for 1/0 respectively, I don't really see it as a dupe. Uninteresting since we already have the other challenge: definitely; but dupe: not really. This challenge isn't even possible in Java or Whitespace for example (a.f.a.i.k.), and although the core part is indeed the same, getting around that leading 0/1 will be tricky in some languages. EDIT: Ah, @ouflak already mentioned everything I said I now see.. \$\endgroup\$ – Kevin Cruijssen Jan 21 at 16:34

54 Answers 54

1
2
2
\$\begingroup\$

Triangular, 9 bytes

.%).?/%(<

Try it online!

Formatted, it looks like this, with X being the number:

   X
  . %
 ) . ?
/ % ( <

How it works:

  • The instruction pointer begins at the top going southeast. It hits the first byte which is the number and pushes that to the stack.
  • % prints the top of the stack as a number.
  • ? skips the next instruction if the top of the stack is not positive. This effectively ends the program if the first byte was zero.
  • < redirects the IP left.
  • ( creates a jump point, % prints the top of the stack, ) unconditionally jumps to the most recent jump point.
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Bash, 46 bytes

 2>t
f()(echo 1;f)
grep -q '0: c' t&&echo 0||f

False Version

True Version - You may have to stop TIO before you'll see the output of ones.

We redirect the error message for the missing command (0 or 1) to a file named t, and then we use grep to find out which error occured and branch off it.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Octave, 22 bytes

;do disp(ans)until!ans

If additional ans = on each line is allowed, this could be 17 bytes: ;do ans until!ans

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Commodore 64 Basic, 26 bytes

Memory address $0039 (or 57 decimal) contains the low byte of the current line number.

0 PRINT PEEK(57):IF PEEK(57)=1 THEN 1

or

1 PRINT PEEK(57):IF PEEK(57)=1 THEN 1
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

J, 23 bytes

 echo@0`($:[echo@1)@.*1

Try it online!

False

True

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Forked, 15 13 12 bytes

%v
>%|
^-:-&

Try it online!

Forked is a very bad two-dimensional esolang I wrote a while ago. For example, the IP will wrap if you run off the bottom of the screen but the program will terminate if you run off the top.

Control flow begins traveling east at the number inputted, hits % to print it, then hits the v which redirects it south. It enters the fork (for some reason I wanted forks to be entered using three additional bytes apiece) and turns west if 1 was pushed, east if 0. To the east it hits & (terminate). To the west the code goes through a couple redirects that put the code in an infinite loop hitting the print command and nop | forever.

Due to the ridiculous fork-entering rule, I believe this is the shortest possible program in Forked to do this.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

J, 15 bytes

(-[echo@[)^:_]0

Try it online! (includes both 0 and 1 cases.)

Abuses "fixed point" feature to choose between iterating once or infinitely.

How they work

0(-[echo@[)^:_]0  Case 0
 (-[echo@[)^:_    Try to find the fixed point of (-[echo@[), which does...
    echo@[          Print left argument once, and then
  -[                Return (left - right)
                  The input (right arg, which counts as 0th iteration) is 0
                  1st iteration is also 0, so ^:_ terminates

1(-[echo@[)^:_]0  Case 1
                  Tries to do the same, but...
                  0th iteration is 0
                  1st iteration is 1 - 0 = 1
                  2nd iteration is 1 - 1 = 0
                  3rd iteration is 1 - 0 = 1... so it oscillates between 0 and 1
                  Therefore, there's no fixed point and ^:_ runs infinitely
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Thue (40 bytes)

!::=1
1+::=_+
_::=~1
+1::=~0
::=
1!+0!

Explanation:

Start with zero:

0!::=1 : String becomes 1!+1

+1::=~0 : String becomes 1!, and zero is printed

No more possible substitutions

Start with one:

1!::=1 : String becomes 1+0!

1+::=1_+ : String becomes 1_+0!

_::=~1 : String becomes 1+0! and one is printed

last two steps repeat at infimum

Try it online

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 41 bytes

0-ge1|iex -ov a
for(;"$a"-match"True"){1}0

Try it online!

I didn't think this would be possible in PowerShell, but then I remembered -outvariable, which is the key to making this happen. This is the first time I've ever used it, even in my $DayJob.

Checks whether the input digit is -greater-than-orequal to 1. That will yield either False or True for 0 and 1, respectively. We pipe that into iex (short for Invoke-Expression and similar to eval), which barfs out a spectacular error message because neither False nor True are legitimate PowerShell expressions. Thankfully, stderr is ignored by default.

Then we use the handy-dandy -outvariable to put the output of iex into variable $a. Since the -ov captures all output into an arraylist, both stdout and stderr are captured, so we get the error message into $a. We then for loop on the condition whether $a (cast as a string to collapse the arraylist) regex -matches "True". If it does, we output 1 continuously; otherwise we simply exit the for loop without printing anything, output 0, and terminate.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ ? Try it online! \$\endgroup\$ – mazzy Jan 21 at 19:17
  • 1
    \$\begingroup\$ @mazzy Haha, now I feel silly. Go ahead and post that as a separate answer, since it's significantly different than this one. \$\endgroup\$ – AdmBorkBork Jan 21 at 19:19
  • \$\begingroup\$ I thought I didn't understand something in the task. ok. \$\endgroup\$ – mazzy Jan 21 at 19:25
  • \$\begingroup\$ Thanks for -outvariable. \$\endgroup\$ – mazzy Jan 21 at 19:30
1
\$\begingroup\$

Japt, 7 bytes

©@Op1}a

0Test it

0          0 / 1
 ©         AND
  @   }a   return first integer that return a truthy value
           when passed through..
   Op1      return undefined and writes 1 to output

1Try it online

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Befunge-93, 9 bytes

0>:#1.:_@

or:

1>:#1.:_@

Try it with 0

Try it with 1

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Similar to the ><> answer, you don't have to create a loop when you can just use wrapping behaviour. You can do something like this for 7 bytes, though I think there could be a 6 byter out there \$\endgroup\$ – Jo King Jan 22 at 0:09
1
\$\begingroup\$

Cascade, 8 bytes

0/
?@
#| 

Try 0 online! Try 1 online!

Hardcoded input makes this a lot more trivial, since we don't need to store the value of the input or anything.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Zsh, 23 20 bytes

=
<<<${${1+1}:-0}
$0

Try it online! Try it online!

Normally, the parameter $0 holds the program/function name. Running 0= sets the parameter to the empty string, which causes the recursion to break. Without any arguments, $1 is unset, so the ${:-fallback} 0 is used instead.

Otherwise, 1= sets $1 to the empty string, which causes ${1+1} to expand to 1.


If the program 1 is not in the user's path or another function, then for 16 bytes:

=1
<<<${1:-0}
$0

Try it online!

Same principle, but with the parameter in question set to the value 1 instead of empty.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Wren, 53 bytes

That extremely long System.print ... but it doesn't matter.

==0?System.print(0):(0..0/0).each{|i|System.print(1)}

Try it online!

Explanation

If x is the given input bit:

x==0  // If the input bit is 0:
?System.print(0) // Output 0 to the console
:     // Otherwise:
(0..0/0) // Generate range from 0 to 0/0 (which yields nan,
         // a negative infinity constant. No matter how
         // you increment 0, you will never get a negative.)
.each{|i|System.print(1)} // Foreach over this infinite list:
                          // Output the number 1
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

CJam, 6 bytes

You know, the fact that input isn't taken from STDIN helps the CJam code become shorter! (Martin Ender wrote this before)

{_o}h;

Try it online!

Explanation

1       "The input bit";
 {  }h  "A do ... while loop, taking";
        "the non-popped TOS as condition";
  _     "Duplicate the input bit";
   o    "Output to STDOUT, popping";
      ; "If the bit is 0, we discard";
        "the extra copy on the stack";
        "That is printed implicitly to the";
        "output";
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Implicit, 3 bytes

(%)

Try it online!

Explanation:

 X         Push number X (only works at start of program)
(           Create jump point 
%          Print top of stack
)            Jump to most recent jump point if top of stack is truthy 
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

GolfScript, 7 bytes

{..}do;

It sucks that you need to infinitely print 1, and print exactly one 0 otherwise I could take away a few characters!

If the restriction was "term on 0, hang on 1", then {.}do is enough. The extra point is for infinite 1s, and the semicolon is or exactly one zero (otherwise there'd be 2 with this solution).

This takes the header, then duplicates it twice. Pop the top, if it's 0, stop, pop, done. One 0 left. If it's a 1, recur the inside, duplicating 1s until your computer burns out of memory.

EDIT: Note, the Wikipedia article has ~{..p}do; as its solution. This assumes you use the "input" area, whereas SE has slightly more flexible input rules to allow header starts.

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Does this actually output the 1s or just duplicate them in memory? \$\endgroup\$ – Jo King Feb 17 at 21:35
  • \$\begingroup\$ When programs finish, GS prints the stack. \$\endgroup\$ – Mathgeek Feb 17 at 23:54
  • \$\begingroup\$ But the program isn't going to finish, by definition \$\endgroup\$ – Jo King Feb 17 at 23:59
  • \$\begingroup\$ When the program crashes, it still prints the stack (explosively). \$\endgroup\$ – Mathgeek Feb 18 at 0:04
  • \$\begingroup\$ Programs are based on the assumption that they have infinite memory and time. If your program relies on halting in order to output, then it doesn't obey the run forever restriction, and vice versa \$\endgroup\$ – Jo King Feb 18 at 0:21
1
\$\begingroup\$

dc, 11 10 bytes

[p1=m]dsmx

Try it online!

Try with 0.

Try with 1.

Thanks to user41805 for eliminating 1 byte.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ It seems the program works without d, while producing infinite stack emptys to STDERR. \$\endgroup\$ – user41805 Apr 21 at 5:42
  • 1
    \$\begingroup\$ @user41805 Thanks, that's interesting. Conditionals in dc are supposed to pop two items off the stack and compare them. But it seems that if the stack doesn't have two items on it, nothing is popped (even if there is one item), and the test is evaluated as if the two items being compared were equal (so that =, !< and !> are considered true, while !=, <, and > are considered false. (At least that's true for one version of dc that I tested, but there are different versions floating around, and I wouldn't assume that they all behave in the same way in this regard.) \$\endgroup\$ – Mitchell Spector Apr 21 at 6:06
  • \$\begingroup\$ I did not understand why it worked as it did, thanks for the explanation, it is indeed interesting. Perhaps it's worth adding to the dc tips \$\endgroup\$ – user41805 Apr 22 at 7:08
1
\$\begingroup\$

1+, 19 15 bytes

11+/1<"#:[#":1#

A fairly trivial ungolfed solution.

Try it 0nline!

Try it on1ine!

Explanation:

Firstly, in this language, 1 pushes 1 and 0 is a NOP.

The program consists of two parts: 11+/1< which converts the internal input into the corresponding number and 1##":"1+1<1+# which is basically the Truth Machine.

Another nice feature of 1+ is the "rotate" operation / which leave the stack unmodified if there's only one number in the stack and swaps the two numbers if there's two.

11+                  [Pushes 2]
   /                 [Rotate the stack]
    1<               [Converts 2 to 0 and leave 1 as-is]
      "#:[#":1#      [See https://codegolf.stackexchange.com/a/208961/87986]
| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

sed, 9 bytes

1c0
=;G;D

Try it online!

(sed requires at the minimum an empty line as input to run.)

sed cycles the input line-by-line. The first line is read into the pattern space first, on which the program is run, at the end of which the resulting pattern space will be implicitly output allowing the next cycle to commence with the next line. Commands can be line-addressed, meaning that they will run only on the specified lines. For example, 11c0 will change the 11th line of input to 0, whilst 1c0 changes the 1st line of input to 0.

If 0 is inserted as the first character, the first line becomes 01c0, i.e. the first line is changed to 0, which ends up printed. A new cycle is started immediately afterwards, and since there are no more lines, the program exits.

If 1 is inserted as the first character, the first line becomes 11c0, i.e. change the 11th line to 0. This does not happen, because there is only 1 line of input, the empty line. The program proceeds to = which prints the line number, i.e. 1. G appends a newline followed by the hold space (starts with being the empty line) to the pattern space, which now contains just a newline. D deletes the first line of the pattern space until and including the newline, and restarts the cycle with the resulting pattern space without consuming the next line of input. This creates the infinite loop, and since the line number stays at 1, 1 + newline is printed out forever. source

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

AWK, 26 bytes

{while(1)print 1}{print 0}

Try it online! (0) Try it online! (1)

This requires some form of input; an empty string will suffice. Otherwise, I couldn't come up with a valid AWK program that begins with 0 or 1.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Stax, 4 bytes

WQ|c

Run and debug it

prepend with 0 or 1. Bonus: also works as a regular truth machine with input

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

Perl 5, 23 bytes

?$_=1:say 0;say while$_

True

False

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

MAWP, 13 bytes

!~M1A?:?.[!:]

Explanation:

               Stack starts with 1.
!              Duplicates 0 or 1  [1,0,0] or [1,1,1]
 ~             Reverses the stack [0,0,1] or [1,1,1]
  M            Adds top 2 elements[0,1]   or [1,2]
   1A          Subtract 1 from top[0,0]   or [1,1]
     ?:        If top of stack is 0, print it, otherwise do nothing
       ?.      If top of stack is 0, end program
         [!:]  Infinite loop which duplicates top of stack and prints it

Try it!

| improve this answer | |
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.