Internal Truth Machine

25

1

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>

Want

Posted 2020-01-21T13:59:50.567

Reputation: 407

3Wait, why did you post it so fast from the Sandbox? – None – 2020-01-21T14:01:01.407

5So, 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? – histocrat – 2020-01-21T14:02:57.483

Yes, and it acts like an input to the normal truth machine. – Want – 2020-01-21T14:05:18.137

Does the input bit count as part of the program? – None – 2020-01-21T14:06:40.163

Well, when I had it in mind, I thought of including it, but now, I guess not. – Want – 2020-01-21T14:08:55.790

Must output be STDOUT or is STDERR or exit code also fine? – Jitse – 2020-01-21T14:36:26.230

5

Quasi-duplicate of Implement a Truth-Machine. The added restriction on input doesn't make it distinct in an interesting way.

– Grimmy – 2020-01-21T15:39:57.953

I agree with the suggested dupe. Let's dupe-hammer this if Grimmy's comment reaches 4 votes (assuming it's not closed as dupe first by standard votes) – Luis Mendo – 2020-01-21T16:09:21.173

1

@Grimy, My code would change quite a bit though, shaving ten bytes off, and my answer here wouldn't work.

– ouflak – 2020-01-21T16:13:06.190

6

@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.

– ouflak – 2020-01-21T16:33:01.400

2Although 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.. – Kevin Cruijssen – 2020-01-21T16:34:50.470

@ouflak, Kevin: Ok, not a dupe then – Luis Mendo – 2020-01-21T17:11:10.807

2Could those who VTC as unclear please state what they require? I have voted to re-open, since the post is clear. – Jonathan Allan – 2020-01-21T17:16:44.297

Does this first byte need to literally be 0x00 (ASCII NUL) or 0x01 (ASCII SOH), or the ASCII character 0 or 1 (0x30 / 0x31)? (I assume the latter since the former would invalidate some of the existing answers) – 640KB – 2020-01-21T17:20:39.027

@640KB "it uses the first character of the program."; "The 0 or 1 at the start does not count to the bytes" – Jonathan Allan – 2020-01-21T17:22:54.223

@JonathanAllan I'm just trying to clarify that the spec doesn't require that the first byte of the program be an actual0x0 value (null byte)when (representing the 0 input) vs. a human-readable representation of a "0" char. For example, if you were to hexdump a Python source file would the first byte be 0x0 (non-printable) or 0x30. character would seem to imply that it is indeed the ASCII value. Again, just clarifying rules. – 640KB – 2020-01-21T17:25:22.280

10@JonathanAllan The challenge is only clear to me when taking into account the comments. If the challenge is edited with most of those changes added in I will gladly reopen. – FryAmTheEggman – 2020-01-21T17:36:21.050

This would have been a bit more interesting if there was a third thing the program had to do when not prefixed with a 0/1 – Jo King – 2020-01-23T06:32:35.850

Oh that would be interesting, but what should it do? Print 1 only once? – Want – 2020-01-23T13:19:20.323

Answers

31

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.

Jonathan Allan

Posted 2020-01-21T13:59:50.567

Reputation: 67 804

7That's really clever. Have an upvote. – AdmBorkBork – 2020-01-21T19:12:38.203

It's just as long, but exit('0') instead of ~print(0) would work without the error... – AVee – 2020-01-23T14:07:18.957

@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. – Jonathan Allan – 2020-01-23T18:50:10.883

18

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

user85052

Posted 2020-01-21T13:59:50.567

Reputation:

1I really like this solution. Short and to the point. +1 – GipsyD – 2020-01-22T13:26:17.507

9

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).

Robin Ryder

Posted 2020-01-21T13:59:50.567

Reputation: 6 625

4I 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. – Giuseppe – 2020-01-21T20:15:37.390

2@Giuseppe maybe you paste some data into console, and then realized that you need assign it to some variable... – tsh – 2020-01-22T03:50:07.363

@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 – CriminallyVulgar – 2020-01-23T08:39:15.637

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) – JDL – 2020-01-24T14:25:19.190

9

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

640KB

Posted 2020-01-21T13:59:50.567

Reputation: 7 149

6

Grimmy

Posted 2020-01-21T13:59:50.567

Reputation: 12 521

6

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)

Jonathan Allan

Posted 2020-01-21T13:59:50.567

Reputation: 67 804

6

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!

Lyxal

Posted 2020-01-21T13:59:50.567

Reputation: 5 253

6

><>,  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

Jonathan Allan

Posted 2020-01-21T13:59:50.567

Reputation: 67 804

4

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.

Jonathan Allan

Posted 2020-01-21T13:59:50.567

Reputation: 67 804

4

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!

Joseph Sible-Reinstate Monica

Posted 2020-01-21T13:59:50.567

Reputation: 556

3

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!

ouflak

Posted 2020-01-21T13:59:50.567

Reputation: 925

3

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

Kaddath

Posted 2020-01-21T13:59:50.567

Reputation: 449

You can use die(0.); to save a byte only integers get returned instead of printed. – Christoph – 2020-01-22T11:58:53.260

3

Python 3, 37 bytes

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

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

Mukundan

Posted 2020-01-21T13:59:50.567

Reputation: 1 188

3

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)

Kevin Cruijssen

Posted 2020-01-21T13:59:50.567

Reputation: 67 575

3

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!

famous1622

Posted 2020-01-21T13:59:50.567

Reputation: 451

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!

– isaacg – 2020-01-21T19:08:40.473

@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 >.< – famous1622 – 2020-01-21T20:37:59.850

1I'm really glad you've enjoyed it! – isaacg – 2020-01-21T20:43:21.690

3

PowerShell, 21 bytes

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

Try it online!

mazzy

Posted 2020-01-21T13:59:50.567

Reputation: 4 832

3

JavaScript, 34 bytes

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

Try it online!

famous1622

Posted 2020-01-21T13:59:50.567

Reputation: 451

1Would a recursive function be legal, along the lines of (g=_=>g(alert(1)))()? – Neil – 2020-01-21T22:43:01.650

1?(a=1):(a=0);do alert(a);while(a) is 33 bytes long – tsh – 2020-01-22T04:30:37.860

?eval('for(;;)alert(1)'):alert(0) is 33 bytes also. – tsh – 2020-01-22T04:37:14.943

You can also remove brackets from @tsh suggestion ?a=1:a=0;do alert(a);while(a) – AZTECCO – 2020-01-22T06:32:16.597

2?a=1:a=2;for(;a;)alert(a&=1) funny version still based on @tsh suggestion – AZTECCO – 2020-01-22T06:41:04.693

1@AZTECCO I'd post yours as it's own answer, I feel it's a little too novel for me to take... – famous1622 – 2020-01-22T13:46:44.140

3

><>, 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

Lyxal

Posted 2020-01-21T13:59:50.567

Reputation: 5 253

Save two using wrapping.

– Jonathan Allan – 2020-01-21T23:20:06.633

15 bytes by keeping it 1D. – Bubbler – 2020-01-22T08:16:37.060

But then that would be the same as the other 5 byte ><> answer – Lyxal – 2020-01-22T08:20:56.853

Oh, didn't notice that. – Bubbler – 2020-01-22T08:26:00.287

3

><>, 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

Artemis still doesn't trust SE

Posted 2020-01-21T13:59:50.567

Reputation: 525

@JoKing "d"o can be replaced with dn I tried that but TIO outputs unrecognised characters... am I missing something? – Artemis still doesn't trust SE – 2020-01-23T16:10:20.010

Oh right I used o not n because apparently I can't read. Thanks! – Artemis still doesn't trust SE – 2020-01-24T19:42:28.490

3

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.

Neil

Posted 2020-01-21T13:59:50.567

Reputation: 95 035

3

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

Bubbler

Posted 2020-01-21T13:59:50.567

Reputation: 16 616

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? – Jonah – 2020-01-23T05:13:36.107

@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. – Bubbler – 2020-01-23T05:28:51.897

Yeah that was the problem. – Jonah – 2020-01-23T05:36:00.813

3

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.

yeah ok nice

Posted 2020-01-21T13:59:50.567

Reputation: 31

1Welcome to CGCC! This is a very nice solution – Jo King – 2020-01-23T05:21:37.990

2

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!

Jitse

Posted 2020-01-21T13:59:50.567

Reputation: 3 566

I was not expecting that to be possible – Want – 2020-01-21T14:22:36.923

2

Ruby, 17 bytes

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

Try it online!

G B

Posted 2020-01-21T13:59:50.567

Reputation: 11 099

2

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.

Tau

Posted 2020-01-21T13:59:50.567

Reputation: 1 935

2

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.

(⌐■◡■)

Lyxal

Posted 2020-01-21T13:59:50.567

Reputation: 5 253

2

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.

MD XF

Posted 2020-01-21T13:59:50.567

Reputation: 11 605

2

Perl 6, 16 15 bytes

-1 byte thanks to Jo King

&&1 xx*X[&put]$

Try0 it online!
Try1 it online!

nwellnhof

Posted 2020-01-21T13:59:50.567

Reputation: 10 037

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!

– Jo King – 2020-01-23T21:35:52.133

1@JoKing You can replace +* with 1 for -1 byte, so both approaches are tied again. – nwellnhof – 2020-01-24T14:13:06.387

2

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

MickyT

Posted 2020-01-21T13:59:50.567

Reputation: 11 735

1

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

AZTECCO

Posted 2020-01-21T13:59:50.567

Reputation: 2 441

1

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.

AdmBorkBork

Posted 2020-01-21T13:59:50.567

Reputation: 41 581

1

? Try it online!

– mazzy – 2020-01-21T19:17:13.630

1@mazzy Haha, now I feel silly. Go ahead and post that as a separate answer, since it's significantly different than this one. – AdmBorkBork – 2020-01-21T19:19:14.473

I thought I didn't understand something in the task. ok. – mazzy – 2020-01-21T19:25:02.070

Thanks for -outvariable. – mazzy – 2020-01-21T19:30:52.277

1

Befunge-93, 9 bytes

0>:#1.:_@

or:

1>:#1.:_@

Try it with 0

Try it with 1

osuka_

Posted 2020-01-21T13:59:50.567

Reputation: 391

1

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

– Jo King – 2020-01-22T00:09:57.803

1

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.

Jo King

Posted 2020-01-21T13:59:50.567

Reputation: 38 234

1

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.

GammaFunction

Posted 2020-01-21T13:59:50.567

Reputation: 2 838

1

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.

Nitrodon

Posted 2020-01-21T13:59:50.567

Reputation: 9 181

The second program can be shortened to 36 bytes

– Jo King – 2020-01-22T04:19:20.033

1

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.

Jonah

Posted 2020-01-21T13:59:50.567

Reputation: 8 729

1

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

tsh

Posted 2020-01-21T13:59:50.567

Reputation: 13 072

1

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

Danko Durbić

Posted 2020-01-21T13:59:50.567

Reputation: 10 241

1

J, 23 bytes

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

Try it online!

False

True

Jonah

Posted 2020-01-21T13:59:50.567

Reputation: 8 729

1

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.

MD XF

Posted 2020-01-21T13:59:50.567

Reputation: 11 605

1

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

Elmusfire

Posted 2020-01-21T13:59:50.567

Reputation: 11

0

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

user85052

Posted 2020-01-21T13:59:50.567

Reputation:

0

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

Bubbler

Posted 2020-01-21T13:59:50.567

Reputation: 16 616

0

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";

user85052

Posted 2020-01-21T13:59:50.567

Reputation:

0

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 

MD XF

Posted 2020-01-21T13:59:50.567

Reputation: 11 605

0

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

user41805

Posted 2020-01-21T13:59:50.567

Reputation: 16 320

0

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.

rootbeersoup

Posted 2020-01-21T13:59:50.567

Reputation: 111

0

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!

Mathgeek

Posted 2020-01-21T13:59:50.567

Reputation: 408

Does this actually output the 1s or just duplicate them in memory? – Jo King – 2020-02-17T21:35:07.617

When programs finish, GS prints the stack. – Mathgeek – 2020-02-17T23:54:05.573

But the program isn't going to finish, by definition – Jo King – 2020-02-17T23:59:41.107

When the program crashes, it still prints the stack (explosively). – Mathgeek – 2020-02-18T00:04:01.120

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 – Jo King – 2020-02-18T00:21:21.043

I disagree with this, since there are several languages that only actually engage in their "output" once they finish the program. Processing, for example, if you lock it in a while loop, will never output anything until the program eventually crashes, since it holds all output prints until either the draw() call is done or the program crashes. Since this problem didn't specify we're doing a theory-question that we "don't actually have the ability to calculate" like some complexity problems do, I'd say there isn't an implicit infinite-memory quota. – Mathgeek – 2020-02-18T00:29:17.557

I don't see any Processing answer on this question. Also, GolfScript has a way to explicitly output. I'm not sure if it is written down on CCCG, but submissions may assume infinite resources at any time unless explicitly restricted from doing so. Regardless, if you're assuming it only outputs on termination, then you can't say that it both outputs and runs forever. – Jo King – 2020-02-18T00:38:03.053

This shows my output is valid. – Mathgeek – 2020-02-26T19:29:13.000

This is not a function, this is a full program – Jo King – 2020-02-26T21:05:56.950

Golfscript executes programs as insular functions. Arguably, since it needs to take input on the stack and by itself is non-functional, it's closer to the definition of "function" than "full program". Takes in a specific input and presents a specific output. Golfscript treats programs and functions pretty much identically. – Mathgeek – 2020-02-27T14:10:37.353

0

Stax, 4 bytes

WQ|c

Run and debug it

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

Nanajnaiojneg

Posted 2020-01-21T13:59:50.567

Reputation: 11

0

Perl 5, 23 bytes

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

True

False

Xcali

Posted 2020-01-21T13:59:50.567

Reputation: 7 671