32
\$\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\$
12
  • 5
    \$\begingroup\$ Wait, why did you post it so fast from the Sandbox? \$\endgroup\$
    – user85052
    Commented Jan 21, 2020 at 14:01
  • 7
    \$\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
    Commented Jan 21, 2020 at 14:02
  • 6
    \$\begingroup\$ Quasi-duplicate of Implement a Truth-Machine. The added restriction on input doesn't make it distinct in an interesting way. \$\endgroup\$
    – Grimmy
    Commented Jan 21, 2020 at 15:39
  • 7
    \$\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
    Commented Jan 21, 2020 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\$ Commented Jan 21, 2020 at 16:34

57 Answers 57

35
\$\begingroup\$

Python 3, 29 bytes

 or~print(0)
while 1:print(1)

A full program, which if prefixed with 0 will print 0 then halt, exiting with an error, or if prefixed with 1 will print 1 forever.

Try 0 online!
Try 1 online!

The right of a logical or is only executed if the left is falsey (which 0 is, while 1 is not).

If the prefix is 0 the argument, print(0), of bitwise-not, ~, is evaluated - this has a side-effect of printing 0 and returns None which is an invalid argument for ~ causing an error which halts the program.

If the prefix is 1 the code ~print(0) is not evaluated and the infinite loop of while 1:print(1) is reached.

\$\endgroup\$
3
  • 8
    \$\begingroup\$ That's really clever. Have an upvote. \$\endgroup\$ Commented Jan 21, 2020 at 19:12
  • \$\begingroup\$ It's just as long, but exit('0') instead of ~print(0) would work without the error... \$\endgroup\$
    – AVee
    Commented Jan 23, 2020 at 14:07
  • \$\begingroup\$ @AVee True, although exit prints to stderr which would mean different output streams for the two programs - I'd want to check that was acceptable. \$\endgroup\$ Commented Jan 23, 2020 at 18:50
19
\$\begingroup\$

W, 2 bytes

You know, duplicate the first character and apply while. Simple enough.

:w

Explanation, applied the bits

1:  % The condition and the body is both 1
  w % While the condition 1 is true, output 1

Explanation 2

0:  % The condition and the body is both 0
  w % This while does not get executed
    % The condition 0 gets returned & printed
\$\endgroup\$
1
  • 2
    \$\begingroup\$ I really like this solution. Short and to the point. +1 \$\endgroup\$
    – GipsyD
    Commented Jan 22, 2020 at 13:26
9
\$\begingroup\$

R, 20 bytes

->a
while(print(a))0

0Try it online!

1Try it online!

Uses rightwards assignment ->, which I now seem to use about once a month on this site (and never anywhere else).

\$\endgroup\$
4
  • 4
    \$\begingroup\$ I knew this would be here. The only use I've ever thought of for -> outside of the site is at the end of a long pipe expression, but that's actually more confusing for future readers than it's worth. \$\endgroup\$
    – Giuseppe
    Commented Jan 21, 2020 at 20:15
  • 2
    \$\begingroup\$ @Giuseppe maybe you paste some data into console, and then realized that you need assign it to some variable... \$\endgroup\$
    – tsh
    Commented Jan 22, 2020 at 3:50
  • \$\begingroup\$ @tsh that's pretty much where I use it, when I'm skunkworksing some big pipe expression and need to use it as a vector mask or something \$\endgroup\$ Commented Jan 23, 2020 at 8:39
  • \$\begingroup\$ I use it in setClass statements (you certainly don't have to, it just looks nicer to me to do setClass("myClass",...) -> myClass though I can't put my finger on why) \$\endgroup\$
    – JDL
    Commented Jan 24, 2020 at 14:25
9
\$\begingroup\$

x86-16 machine code, IBM PC DOS, 11 bytes

Binary:

(0 example)

00000000: 3002 ad8a d03c 30cd 2175 fcc3            0....<0.!u..

(1 example)

00000000: 3102 ad8a d03c 30cd 2175 fcc3            1....<0.!u..

Unassembled listing:

?? 02       DB  ?, 2        ; first byte is '1' or '0', second byte is DOS write char fnc
AD          LODSW           ; load input from [SI] into AL, INT 21H function 2 in AH
8A D0       MOV  DL, AL     ; output to DL
3C 30       CMP  AL, '0'    ; is input 0?
        OUTPUT: 
CD 21       INT  21H        ; write to console
75 FC       JNZ  OUTPUT     ; if not a '0', keep looping forever
C3          RET             ; return to DOS (only if it was a 0)

Explanation:

The first byte of the program is either a '0' or a '1', and combined with a second byte of 2 (more on that later) decodes to a benign instruction of either XOR [BP+SI], AL or XOR [BP+SI], AX. In PC DOS, many registers are initialized to known values, so we know that AX is 0, and SI is 100H which is the first byte of the program. Whatever memory address [BP+SI] translates to, it simply XOR's 0 to it, doing nothing.

The LODSW instruction puts the input byte into the AL register and a 2 into the AH register, which is the DOS INT 21H API function number to write an ASCII char in DL to the console.

The input is compared and ZF (zero flag) is set "true" if input is a 0. The char is written to the console and if ZF is not zero, it will loop indefinitely.

Output of both variants:

enter image description here

\$\endgroup\$
7
\$\begingroup\$

Haskell, 32 bytes

!f=f 0
_!f=f 1*>0!f
main=0!print

I think this is the only answer posted so far where the first character (the digit) isn't the entry point.

Anyway, explanation: I'm creating an operator function called !, and defining it by cases. We enter the top case if the left operand matches the program's first digit, and the bottom case otherwise. The right operand is bound to f in both cases (and it happens to always be print). In the top case, we just print a 0. In the bottom case, we print a 1, and then recursively call ourself with the same operands. (We know the left operand will always be 0.) Finally, main, the entry point, calls our operator with 0 and print.

Try it online with 0! Try it online with 1!

\$\endgroup\$
6
\$\begingroup\$

05AB1E, 3 bytes

µ=0

Try 0µ=0 online!

Try 1µ=0 online!

Also 3 bytes:

i[,

Try 0i[, online!

Try 1i[, online!

\$\endgroup\$
6
\$\begingroup\$

Jelly, 3 bytes

Ṅḷ¿

Try 0 online!
Try 1 online!

 Ṅḷ¿ - Main Link: no arguments
.    - set Left to 0 or 1
   ¿ - while...
  ḷ  - ...condition: Left
 Ṅ   - ...do: print and yield (Left)
     - implicit print (Left)
\$\endgroup\$
6
\$\begingroup\$

Scratch 3.0, 10 blocks/80 bytes

Program

As SB Syntax:

//1 or 0
repeat until<(n)=[0
say[1
end
say[0
define 0
set [n v]to[0
define 1
set[n v]to[1

It's more of a snippet than a program, but it works.

Try it online Scratch!

\$\endgroup\$
6
\$\begingroup\$

><>,  6  5 bytes

-1 thanks to Jo King!

:n?!;

Try 0 online!
Try 1 online!

How?

Instruction pointer starts at the top left (i.e. 0 or 1) facing right. If the instruction pointer leaves the code it wraps around to the other side, continuing in the same direction.

X:n?!; -               X=0                X=1
X      - push X          {0}                {1}
 :     - duplicate       {0,0}              {1,1}
  n    - pop & print     {0,} "0"           {1} "1"
   ?   - pop & if...     {}                 {}
    !  - ...truthy:      skip & wrap to X
     ; - ...falsey:                         exit
\$\endgroup\$
0
5
\$\begingroup\$

Labyrinth, 5 bytes

"
!"@

Try 0 online!
Try 1 online!

How?

Instruction pointer starts at the top left (i.e. 0 or 1) facing right, the stack starts as infinite zeros.

0:

0"
!"@

  - stack = {0,0,0,...} (infinite supply of zeros)
0 - multiply top of stack by 10 and add 0 {0,0,0,...}
  - 2 neighbours, 0 -> go forward
" - no-op {0,0,0,...}
  - 2 neighbours -> go forward
" - no-op {0,0,0,...}
  - 3 neighbours T-junction from stem, 0 -> turn around
" - no-op {0,0,0,...}
  - 2 neighbours -> go forward
0 - multiply top of stack by 10 and add 0 {0,0,0,...}
  - 2 neighbours -> go forward
! - pop top of stack, print as decimal "0" {0,0,0,...}
  - 2 neighbours -> go forward
" - no-op {0,0,0,...}
  - 3 neighbours T-junction from side, 0 -> go forward
@ - exit labyrinth

1:

1"
!"@

  - stack = {0,0,0,...} (infinite supply of zeros)
1 - multiply top of stack by 10 and add 1 {1,0,0,...}
  - 2 neighbours -> go forward
" - no-op {1,0,0,...}
  - 2 neighbours -> go forward
" - no-op {1,0,0,...}
  - 3 neighbours T-junction from stem, 1 -> turn right
! - pop top of stack, print as decimal "1" {0,0,0,...}
  - 2 neighbours -> go forward
1 - multiply top of stack by 10 and add 1 {1,0,0,...}
  - ...etc.
\$\endgroup\$
4
\$\begingroup\$

Pyth, 65 63 56 bytes

Pyth's prefix operators don't really suit well to this challenge...

Ws@`$__import__("inspect").stack()[1][0].f_locals$_101
1

Edit 1: Saved 2 bytes by letting Pyth do the dictionary index, and using h instead of @<py_code>0 because I remembered it exists.

Edit 2: Saved 7 bytes because @isaacg found an even sillier trick :)

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ I really like this! I found a even sillier way to shorten it a bit more by removing the need for the "pyth_code" index. 56 bytes: Try it online! \$\endgroup\$
    – isaacg
    Commented Jan 21, 2020 at 19:08
  • \$\begingroup\$ @issacg Clever! also thanks for making such a fun little language to play with, I've sunk more time into it than I'd like to admit >.< \$\endgroup\$
    – Citty
    Commented Jan 21, 2020 at 20:37
  • 1
    \$\begingroup\$ I'm really glad you've enjoyed it! \$\endgroup\$
    – isaacg
    Commented Jan 21, 2020 at 20:43
4
\$\begingroup\$

><>, 12 10 bytes

:?vn;
 n:<

-2 bytes thanks to @JonathanAllan

Answer History

 :?vn;
>:n:<

Try it online!

or

Try it with 1

Try it with 0

Explained

Gif showing execution path with 0

Gif showing execution path with 0

Path visualiser is https://fishlanguage.com/

Gif converter is https://www.onlineconverter.com/video-to-gif

\$\endgroup\$
4
  • \$\begingroup\$ Save two using wrapping. \$\endgroup\$ Commented Jan 21, 2020 at 23:20
  • 1
    \$\begingroup\$ 5 bytes by keeping it 1D. \$\endgroup\$
    – Bubbler
    Commented Jan 22, 2020 at 8:16
  • \$\begingroup\$ But then that would be the same as the other 5 byte ><> answer \$\endgroup\$
    – lyxal
    Commented Jan 22, 2020 at 8:20
  • \$\begingroup\$ Oh, didn't notice that. \$\endgroup\$
    – Bubbler
    Commented Jan 22, 2020 at 8:26
4
\$\begingroup\$

APL (Dyalog Unicode), 8 bytesSBCS

{⍞←⍺}⍣≠1

0Try it online! 1Try it online!

Prints to stderr.

How they work

0{⍞←⍺}⍣≠1
 {⍞←⍺}⍣≠   ⍝ Iterate {⍞←⍺} until (next value)≠(prev value) is true
 {⍞←⍺}     ⍝ First iteration: print and return left arg (0)
       ≠   ⍝ (next value)=0, (prev value)=1, so 0≠1 is true
           ⍝ Function terminates

1{⍞←⍺}⍣≠1
 {⍞←⍺}⍣≠   ⍝ Iterate {⍞←⍺} until (next value)≠(prev value) is true
 {⍞←⍺}     ⍝ First iteration: print and return left arg (1)
       ≠   ⍝ (next value)=1, (prev value)=1, so 1≠1 is false
 {⍞←⍺}     ⍝ Second and subsequent iterations: called with the same arg (1)
           ⍝ Never terminates; prints 1 infinitely
\$\endgroup\$
3
  • \$\begingroup\$ I tried translating this into J to improve my current approach but wasn't able to. Is J's ^:v^:_ just fundamentally different from the APL iterate or am I missing something? \$\endgroup\$
    – Jonah
    Commented Jan 23, 2020 at 5:13
  • \$\begingroup\$ @Jonah I guess it's because J's ^:_ is special-cased to find the fixed point. So it stops not only when v gives 0, but also when the right argument doesn't change. \$\endgroup\$
    – Bubbler
    Commented Jan 23, 2020 at 5:28
  • \$\begingroup\$ Yeah that was the problem. \$\endgroup\$
    – Jonah
    Commented Jan 23, 2020 at 5:36
4
\$\begingroup\$

Befunge-93, 5 bytes

:_.@#

Try 0 online

Try 1 online

First submission, and I only started learning Funge yesterday, so it's very likely there's a shorter solution.

I tried to find a way to remove the need for the ":" but I couldn't.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to CGCC! This is a very nice solution \$\endgroup\$
    – Jo King
    Commented Jan 23, 2020 at 5:21
4
\$\begingroup\$

Raku, 14 11 bytes

,1...&say^1

0Try it online! 1Try it online!

Abuses the range operator to loop infinitely and the XOR Junction (^) to print and to evaluate if the range should stop.

\$\endgroup\$
3
\$\begingroup\$

Python 3, 37 bytes

and exec('while 1:print(1)');print(0)

0: Try it online!
1: Try it online!

\$\endgroup\$
3
\$\begingroup\$

MathGolf, 3 bytes

Äo↑

Try 0Äo↑ online.
Try 1Äo↑ online.

Explanation:

1     # Push 1
   ↑  # While true without popping,
 Ä    # by using a single builtin as inner block:
  o   #  Print with trailing newline without popping

0     # Push 0
   ↑  # While true without popping
      # (output the entire stack joined together implicitly as result)
\$\endgroup\$
3
\$\begingroup\$

PowerShell, 21 bytes

0|?{$_}|%{for(){1}};0

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Keg, 4 bytes

{:|④

Try it online!

It seems I'm a bit late to the party! ¯\_(ツ)_/¯

Anyhow, this is simply a modification of the usual truth machine This is literally the same truth machine as it would be if we didn't have to place the digit at the start. Funny how implicit input works.

By this, I mean it doesn't matter if y'all place the digit at the start or you place it in input.

(⌐■◡■)

\$\endgroup\$
3
\$\begingroup\$

JavaScript, 34 bytes

?(_=>{for(;;)alert(1)})():alert(0)

Try it online!

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Would a recursive function be legal, along the lines of (g=_=>g(alert(1)))()? \$\endgroup\$
    – Neil
    Commented Jan 21, 2020 at 22:43
  • 1
    \$\begingroup\$ ?(a=1):(a=0);do alert(a);while(a) is 33 bytes long \$\endgroup\$
    – tsh
    Commented Jan 22, 2020 at 4:30
  • \$\begingroup\$ ?eval('for(;;)alert(1)'):alert(0) is 33 bytes also. \$\endgroup\$
    – tsh
    Commented Jan 22, 2020 at 4:37
  • 2
    \$\begingroup\$ ?a=1:a=2;for(;a;)alert(a&=1) funny version still based on @tsh suggestion \$\endgroup\$
    – AZTECCO
    Commented Jan 22, 2020 at 6:41
  • 1
    \$\begingroup\$ @AZTECCO I'd post yours as it's own answer, I feel it's a little too novel for me to take... \$\endgroup\$
    – Citty
    Commented Jan 22, 2020 at 13:46
3
\$\begingroup\$

Charcoal, 6 bytes

1WΣ⊟KAD

Try it online! Link is to verbose version of code.

0WΣ⊟KAD

Try it online! Link is to verbose version of code.

Explanation: The leading 1 or 0 simply prints literally to the canvas. There then follows a while loop, the condition of which is the digital sum of the last character on the canvas. Thus if this is zero, the loop never gets off the ground, and the canvas gets implicitly output with the 0 still on it. However, if this is a non-zero digit, such as 1, then the loop will dump a copy of the canvas for ever. (Note that the dump command has a rate limit on it, so that TIO will time out before the output reaches the size limit.)

There are a few variants with the same byte count, such as using Cast rather than Sum, or Maximum or Minimum rather than Pop, or even by using Count or Find instead.

\$\endgroup\$
3
\$\begingroup\$

Alchemist, 27 bytes

a->a+Out_b
_+0a->a+b
a+b->_

Try it online with 0!

Try it online with 1!

This was a bit tricky. Every execution path up to the first application of the first line must be possible in both programs, and the two possible patterns in the first line are mutually exclusive. Hence, in order for the program to work, execution up to that point must be non-deterministic. This program swaps infinitely between two states until the first line is applied.

0a->a+Out_b    # the 0 version: from the initial state, add an a to halt and output 0
1a->a+Out_b    # the 1 version: from the a+b state, output 1 and leave the state unchanged
_+0a->a+b      # From the initial state, move to the a+b state
a+b->_         # From the a+b state, move to the initial state

A deterministic solution is possible by starting the first line with a two-digit number, but this is 14 bytes longer.

\$\endgroup\$
1
  • \$\begingroup\$ The second program can be shortened to 36 bytes \$\endgroup\$
    – Jo King
    Commented Jan 22, 2020 at 4:19
3
\$\begingroup\$

PHP, 24 bytes

?:die(0.);for(;;)echo 1;

Uses ternary condition knowing that in PHP one of the alternatives can be empty and i doesn't need to be assigned to a variable.

0: Try it online!

1: Try it online!

Edit: had to add '0' to properly echo zero

Edit2: Had forgotten that die was synonym of exit (thanks manual)

Edit3: saved 1 byte with for(;;) instead of while(1)

Edit4: saved 1 byte with die(0.) instead of die('0') thanks to @Christoph

\$\endgroup\$
1
  • \$\begingroup\$ You can use die(0.); to save a byte only integers get returned instead of printed. \$\endgroup\$
    – Christoph
    Commented Jan 22, 2020 at 11:58
3
\$\begingroup\$

Cubix, 5 bytes

^O?@u

0 Try it online!

1 Try it online!

Maps onto the cube like

  0
^ O ? @
  u
  • ^ Redirect up onto the top face
  • 0 or 1 pushed to the stack
  • ? test
    • uO?@ if 0 then u-turn onto the integer output pass through the test again and halt
    • O^ if 1 output the integer and redirect up again
\$\endgroup\$
3
\$\begingroup\$

Turing Machine Code, 29 bytes or 28 bytes

With the strange rule that the leading '0' or '1' doesn't count towards the byte count.

0 0 1 * 1
* _ 0 * 1
* 1 1 r 1

Try '0' online!

1 0 1 * 1
* _ 0 * 1
* 1 1 r 1

Try '1' online!

\$\endgroup\$
0
3
\$\begingroup\$

Perl 6, 16 15 bytes

-1 byte thanks to Jo King

&&1 xx*X[&put]$

Try0 it online!
Try1 it online!

\$\endgroup\$
3
  • \$\begingroup\$ Using X with a custom operator is very clever. My thought was to use ..., but that only ties with your old solution. Try it online! \$\endgroup\$
    – Jo King
    Commented Jan 23, 2020 at 21:35
  • 1
    \$\begingroup\$ @JoKing You can replace +* with 1 for -1 byte, so both approaches are tied again. \$\endgroup\$
    – nwellnhof
    Commented Jan 24, 2020 at 14:13
  • \$\begingroup\$ Aha! Figured out how to eliminate another byte from my solution \$\endgroup\$
    – Jo King
    Commented Aug 7, 2020 at 4:15
3
\$\begingroup\$

><>, 15 9 bytes

?\0n;
n1<

Try it online!

  • -6 bytes thanks to JoKing

My first fish program, doesn't beat the other one but I wanted to post it anyway. Beats the other one now!

Explanation:

For 0:
0? skip the next command
0 push 0 to the stack
n output the top of the stack
; terminate
For 1:
1? don't skip the next command (no-op)
\ mirror down
> switch direction to forward
1 push 1 to the stack
n output, then wrap round

\$\endgroup\$
2
  • \$\begingroup\$ @JoKing "d"o can be replaced with dn I tried that but TIO outputs unrecognised characters... am I missing something? \$\endgroup\$
    – Miriam
    Commented Jan 23, 2020 at 16:10
  • \$\begingroup\$ Oh right I used o not n because apparently I can't read. Thanks! \$\endgroup\$
    – Miriam
    Commented Jan 24, 2020 at 19:42
2
\$\begingroup\$

Python 3, 38 bytes

0 or print(0)or exit()
while 1:print(1)

Try it online!

1 or print(0)or exit()
while 1:print(1)

Try it online!


If output to STDERR is allowed (30 bytes):

0 or exit('0')
while 1:print(1)

Try it online!


If output as exit code is allowed (28 bytes):

0 or exit(0)
while 1:print(1)

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ I was not expecting that to be possible \$\endgroup\$
    – PkmnQ
    Commented Jan 21, 2020 at 14:22
2
\$\begingroup\$

Ruby, 17 bytes

>0?loop{p 1}:p(0)

Try it online!

\$\endgroup\$
2
\$\begingroup\$

TI-BASIC, 10 bytes

Repeat not(Ans:Disp Ans:End:"

Add either 0: or 1: to the beginning of the code to get the desired output.
Output is either just 0 or an infinite amount of 1s.

Repeat loops until its condition is true and ignores the condition for the first loop.
Thus, not(Ans will be 1 if 0: is added and 0 if 1: is added.

An empty string is added to the end of the program to prevent it from printing Done.

Examples:

prgmA: 0:Repeat not(Ans:Disp Ans:End:"

prgmB: 1:Repeat not(Ans:Disp Ans:End:"

prgmA
              0

prgmB
              1
              1
              1
              1
              1
              1
              1

Note: TI-BASIC is a tokenized language. Character count does not equal byte count.

\$\endgroup\$

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