178
\$\begingroup\$

A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

  • Gets a number (either 0 or 1) from STDIN.

  • If that number is 0, print out 0 and terminate.

  • If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

  • take input from STDIN or an acceptable alternative
    • If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program
  • must output to STDOUT or an acceptable alternative
    • If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.
  • when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory
  • the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

  • if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes 

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes 

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes 

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes 

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 320px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = 62732; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; 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,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\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, }); else console.log(body); }); 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; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), 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_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) 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); } }</script>

\$\endgroup\$
19
  • 3
    \$\begingroup\$ Assuming any behaviour is fine for all invalid inputs? \$\endgroup\$ Commented Nov 3, 2015 at 17:33
  • 3
    \$\begingroup\$ @Cruncher Yes, the only inputs you should expect to get are 0 and 1. \$\endgroup\$ Commented Nov 3, 2015 at 17:38
  • 5
    \$\begingroup\$ Catalog is borked. \$\endgroup\$ Commented Nov 6, 2015 at 15:18
  • 2
    \$\begingroup\$ Catalog appears to consider Bf and bf to be different languages. \$\endgroup\$ Commented Nov 10, 2015 at 1:13
  • 1
    \$\begingroup\$ Is one allowed to print an infinite number of 1s? That is, not print out 1s forever, but print out an infinite list of 1s all at once? This would be theoretically demonstrated, but the language has no notion of printing more than once. It just generates an output. So is it okay if it runs indefinitely, but would print infinite 1s given infinite time (to finish executing)? \$\endgroup\$ Commented Apr 26, 2020 at 1:42

509 Answers 509

1
4 5
6
7 8
17
2
\$\begingroup\$

Java, 87 bytes

interface A{static void main(String[]a){System.out.print(a[0]);main(a[0].split("0"));}} 

(has output to STDERR, but that should not matter)

\$\endgroup\$
10
  • \$\begingroup\$ I'm not entirely sure if this is valid. The rules state that the program must infinitely run unless killed or out of memory. This will cause a stack overflow, since Java doesn't have tail call recursion optimization. \$\endgroup\$ Commented Jan 25, 2016 at 13:31
  • \$\begingroup\$ Yes, for the standard JVM; but there the size of the stack depends on the memory allocated. If the memory allocated by -Xss is large enough, it will run arbitrarily long (see also stackoverflow.com/questions/4734108/…). The stack overflow therefore is just the visible result of the program being out of memory. \$\endgroup\$ Commented Jan 25, 2016 at 13:36
  • 1
    \$\begingroup\$ @SeanBean "take input from STDIN or an acceptable alternative" - command-line arguments are an acceptable input method. \$\endgroup\$ Commented Sep 1, 2016 at 9:27
  • 1
    \$\begingroup\$ maybe downvote the challenge if you don't like it, instead of this particular Java answer? Not that I mind but you could reach a larger audience there... downvoting because you believe an answer is the shortest kind of defeats the purpose of codegolf?? \$\endgroup\$ Commented Sep 7, 2016 at 18:28
  • 1
    \$\begingroup\$ A stack overflow is a form of memory outage: there is no more place in the stack memory for another stack frame. \$\endgroup\$ Commented Jan 10, 2019 at 9:55
2
\$\begingroup\$

HALT, 49 bytes

1 IF '0' 2 ELSE 3 2 TYPE '0';HALT 3 TYPE '1';SET 1 

Pretty simple. If input is one go to 3, output 1, set the pointer to 1 so the program never ends. If input is output 0, print, then halt.

Online interpreter (Firefox only)

\$\endgroup\$
3
  • \$\begingroup\$ such amazing much wow where's rightgoat \$\endgroup\$ Commented Feb 23, 2016 at 3:12
  • 1
    \$\begingroup\$ @Seadrus ---I ate him---. I mean, he'll be coming soon \$\endgroup\$ Commented Feb 23, 2016 at 3:12
  • \$\begingroup\$ No he won't, you're the only goat left ;) \$\endgroup\$ Commented Feb 24, 2016 at 3:12
2
\$\begingroup\$

Shtriped, 33 bytes

e : t : . d : i : p : . . p : 

This prints the 0 or the infinite stream of 1's without any trailing newlines or spaces.

Explanation:

e : \ initialize a variable named ":" t : \ prompt for integer input, storing the result in : . \ define a function named "." that will only return if : is 0 (the next 4 indented lines are part the function) d : \ decrement : if : is positive, else return immediately i : \ : must have been 1 to reach here and was just decremented, so increment back to 1 p : \ print :, which we know is 1 . \ recursively call ., endlessly looping . \ call . initially p : \ if . terminated this line will finally be run, printing : which we know is 0 
\$\endgroup\$
2
\$\begingroup\$

BASTARD, 83 bytes

{{fi in 0{!b {= {t 0} ‘1’} {(o <> {{fi out ‘1’}{o}}){o}}{fi out ‘0’}}}} 

Note: This language is not qualified. Mostly because I'm still designing it. I just wanted to test drive it against some puzzles.

Explanation:

fi in copies the input into the 0 place on the Variable Stack.

!b is a basic if statement to check if its a "1" or not.

If it is, we just use fi out to print our "0".

Otherwise, we define a new function called o that prints a "1", and then calls itself again.

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Programming Puzzles and Code Golf Stack Exchange. This is a great first answer, +1. Your language looks interesting; once you've got enough reputation you could get help developing it on Chat. \$\endgroup\$ Commented Feb 19, 2016 at 15:05
2
\$\begingroup\$

NTFJ, 27 bytes

:*:##~~~~~#@|########@|($~^ 

An online interpreter can be found here.

NTFJ is an esoteric programming language, made by user @ConorO'Brien, that is intended to be a Turing tarpit. It is stack-based, and pushes bits to the stack, which can be later coalesced to an 8-bit number.

  • The only pushable values are 0 with ~ and 1 with #.
  • The only manipulations possible to the actual values of the stack are to wrap eight bits into a byte with @, and to NAND with |.
  • The only logic command is IF with (), but combined with JUMP ^, it can be used to create loops.

Thus, it's quite difficult to manipulate values to do your bidding.

How it works

 Implicit input: byte 48 for 0 or 49 for 1. :*: Duplicate the top item, pop/output, and duplicate again. ##~~~~~#@| Push 193 and perform NAND. ########@| Push 255 and perform NAND. These two operations change 48 to 0 and 49 to 1. ( If the top item is not 0: $ Pop the top item. ~^ Push 0 and jump to that instruction. This effectively creates a while loop that loops the entire program. 
\$\endgroup\$
2
  • \$\begingroup\$ I believe removing the last paren should still work. \$\endgroup\$ Commented Mar 2, 2016 at 19:42
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ Thanks, it does! \$\endgroup\$ Commented Mar 15, 2016 at 20:08
2
\$\begingroup\$

Beatnik, 26 bytes

J ZD ZD JA K ZZZZJ Z JJ MF 

Try it online

An explanation

Words Scores Action J 8 Get character value from input ZD 12 Duplicate TOS ZD 12 Duplicate TOS JA 9 Output TOS character K ZZZZJ 5 48 Push 48 (char 0) onto stack z 10 Pop 2 from stack and subtract JJ MF 16 (7) If not zero skip back 7 words 

Of course something like the following, while still not making sense, looks more like what you would expect for a Beatnik program.

Shall falsey determine truths? We **WithoutAWarningAboutMemoryUse** printed infinitely yeas! 
\$\endgroup\$
3
  • \$\begingroup\$ The last one mostly makes sense, except for He quackpizzled? :) \$\endgroup\$ Commented Mar 16, 2016 at 22:50
  • \$\begingroup\$ @ETHproductions Yea, try to find a word that is SORTAWORDLIKEWITHABIGNUMBER and still fits gets difficult :) Will have a play and see what I can come up with. \$\endgroup\$ Commented Mar 16, 2016 at 22:55
  • \$\begingroup\$ @ETHproductions That's a bit better now \$\endgroup\$ Commented Mar 16, 2016 at 23:08
2
\$\begingroup\$

Lua, 56 52 Bytes

I know that this answer in 70 Bytes exists, but its author doesn't look like he's updating it when someone point out an improvement.

if io.read'*n'>0then::a::print"1"goto a end print"0" 

Old 56 bytes solution

if io.read()=="1"then while""do print"1"end end print"0" 

Nothing special here, just using the fact that "" evaluates to true to save a byte on the infinite loop. Parenthesis for functions parameters aren't mandatory when they only take a single string, which is not stored in a variable.

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

Julia, 51 45 bytes

readline()>"0"?while 2>1 print(1)end:print(0) 

Read a string from STDIN. If it's lexicographically larger than the string "0" then print 1 forever, otherwise print 0 and we're done.

Saved 6 bytes thanks to Sp3000!

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

UGL, 6 bytes

il$o:o 

Try it online!

How it works:

i #stack.push(input) l : #while stack.peek(): $ # stack.dup() o # print(stack.pop()) o #print(stack.pop()) 
\$\endgroup\$
0
2
\$\begingroup\$

PowerShell, 24 bytes

'for(){1}'*"$args"+0|iex 

Generate expression as string and pass it to Invoke-Expression (eval).

It casts $args array to string with "", then multiplication sign casts it to int and string for(){1} is repeated int times (1 or 0 - empty string). Then we add 0 to this string, which will be cast to a string also.

Resulting string expression (for(){1}0 or 0) is then piped to Invoke-Expression, resulting either in endless loop outputting 1 or one-time output of 0.

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

WistfulC, 141 bytes

This C has seen better days.

if only int n were 0... wish for "%d",&n upon a star someday !n... wish "1" upon a star *sigh* wish "0" upon a star if wishes were horses... 

Obviously not competitive, but then neither is this language.

Rough translation to regular C:

int n = 0; scanf("%d", &n); while (n) { puts("1"); } puts("0"); exit(0); 
\$\endgroup\$
2
\$\begingroup\$

T-SQL 23 bytes

No STDIN here so a hard-coded variable.

DECLARE @ INT =1; or DECLARE @ INT =0;

and the truth machine is

l:PRINT @ IF(1=@)GOTO l

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

C, 41, 40 bytes

main(c){for(c=getchar();putchar(c)&1;);} 

Reads a single character from stdin, writes to stdout.

This version is 1 byte longer than feersum's solution, but removes his/her assumptions onstdin.

\$\endgroup\$
2
  • \$\begingroup\$ Would putchar(c)&1 work? \$\endgroup\$ Commented Aug 29, 2016 at 16:41
  • \$\begingroup\$ Yes, you are right! One byte saved, thanks @Dennis. \$\endgroup\$ Commented Aug 29, 2016 at 16:51
2
\$\begingroup\$

PHP, 34 bytes

<?for($f=fgetc(STDIN);$f;?>1<?)?>0 

Wanted to try to get rid of the print but not sure it's worth it since you have to reintroduce the <? tags

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

Java, 143 141 125 88 bytes

interface T {static void main(String[]a){System.out.print(a[0]);main(a[0].split("0"));}} 

Ungolfed Test Code

interface T { static void main(String[] a) { System.out.print(a[0]); main(a[0].split("0")); } } 
\$\endgroup\$
4
  • \$\begingroup\$ That's 143 characters. \$\endgroup\$ Commented Sep 1, 2016 at 8:49
  • \$\begingroup\$ Why did you even check? \$\endgroup\$ Commented Sep 1, 2016 at 8:51
  • \$\begingroup\$ I'm using a userscript for PPCG, and it tells me how many bytes there are. (You should totally use it, it's worth it) \$\endgroup\$ Commented Sep 1, 2016 at 8:54
  • \$\begingroup\$ Ahh ok. It's shorter now anyway :P \$\endgroup\$ Commented Sep 1, 2016 at 8:55
2
\$\begingroup\$

Lua, 34 Bytes

repeat print(arg[2])until arg[2]<1 

arg[2] contains the first command line argument, (arg[1] contains the filename)

Give an input through the command line, and it shall spam it if it's 1, or once if it's not.

Simple enough.

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

Copy, 67 59 bytes

My new esolang :D

getch a add b a add b -48 print a skip b skip 1 copy -4 0 1 

Explanation:

getch a Take input in variable 'a' add b a Set 'b' to 'a' add b -48 Substract 48 from 'b' print a Print 'a' skip b Skip the copy if 'a' is not zero skip 1 ^ copy -4 0 1 Copy the code block from the print to this instruction after this instruction 
\$\endgroup\$
2
  • \$\begingroup\$ protip: *subtract \$\endgroup\$ Commented Sep 25, 2016 at 9:22
  • \$\begingroup\$ @DestructibleWatermelon No \$\endgroup\$ Commented Sep 25, 2016 at 9:26
2
\$\begingroup\$

Crystal, 48 37 36 bytes

y=gets;y=="0\n"&&(p 0;exit);y=="1\n"&&loop{p 1}
y=gets;y=="0\n"&&(p 0;exit);loop{p 1}
y=gets;y=="0\n"&&(p 0;1/0);loop{p 1}

Edit: Shaved off 10 bytes because the post doesn't specify what should happen on invalid input (like 2). If it does and I misunderstood, let me know.

Edit: Shaved off 1 byte by dying with an error instead of normal exit.

Crystal is statically typed, so I couldn't just do gets.chomp (gets can return nil, and nil doesn't have chomp). The alternative was gets.try &.chomp, but that takes much more space than just having the newlines.

In Crystal (and Ruby) you can do something like puts 0 if y=="0\n", however you can also shave off 2 bytes by doing y=="0\n"&&puts 0 as the && operator returns the last object it tests for truthiness.

loop is a method in the standard lib that infinitely runs the block. It's a much shorter way of writing while true;CODE;end.

p prints the result of .inspect on its arguments to the output. Here I abuse it as a shorter puts because for numbers it'll just return the number.

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

Valve scripting language, 38 bytes

alias 0 echo 0 alias 1 "echo 1;wait;1" 

This defines two commands, 0 and 1. Type 0 into the console for the zero case, and 1 for the 1 case.

\$\endgroup\$
2
  • \$\begingroup\$ Could I just try this in half life's console, or do I need the source SDK? \$\endgroup\$ Commented Dec 21, 2016 at 1:56
  • \$\begingroup\$ @Pavel I tested it on the TF2 console, so that should be fine. \$\endgroup\$ Commented Dec 21, 2016 at 2:02
2
\$\begingroup\$

Underload, 16 bytes

((1)S:^)~^:^(0)S 

Underload has no way to take input from standard input. The most natural way to take input is therefore from the initial stack: () for 1, (!()) for 0 (this is the normal way to represent numbers in Underload).

Here are Try It Online links for 0 and for 1 (be prepared to kill this one quickly; the infinite loop runs very quickly and will spam up your browser window).

This program didn't need much effort to golf; the most idiomatic way to do things is almost the shortest (I just had to be careful not to let the input get buried too far on the stack). It's easiest to read if I translate the code to a hypothetical functional language:

 function x(y) print(1) x(x) end x = x^(input) x(x) print(0) 

The only weird thing happening here is being able to exponentiate functions, but it's a fairly easy-to-understand operation; for example, raising a function f to the power 3 would produce f compose f compose f, i.e. lambda x.f(f(f(x))). Raising a function to the power 1 does nothing (just like if you'd raised an integer to the power 1); and raising a function to the power 0 gives you the identity function (just like raising a number to the power 0 gives you 1). Actually, the integers in Underload are defined in terms of their effect exponentiating functions, rather than the other way round; the operation is fundamental enough to Underload that you use it to construct most flow control.

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

Jelly, 3 bytes

Ṅ¹¿ 

If reading from STDIN is absolutely required:

ƈOḂṄ¹¿` 

I'm not sure which since "Jelly's main input method is via command line arguments, although reading input from STDIN is also possible."

\$\endgroup\$
1
  • \$\begingroup\$ Your second version can also be ƓṄ¹¿, where it reads a line instead of a single character. \$\endgroup\$ Commented Mar 12, 2017 at 15:33
2
\$\begingroup\$

SmileBASIC, 23 22 bytes

INPUT N@L?N?N/N GOTO@L 

Ends the program with a divide by 0 error.

If this isn't allowed, here's a 23 byte solution:

INPUT N@L?N IF N GOTO@L 
\$\endgroup\$
2
\$\begingroup\$

WireWorld (It doesnt have a scoring method yet :\)

 ████ █ <= this pixel will be the input. if it is a electron head (1), █ █ It will loop forever as 1. if its a wire (0), it will do nothing. █ ██ █ ██ █ ██ 
\$\endgroup\$
2
\$\begingroup\$

Common Lisp, 30

(do((x(read)))((=(print x)0))) 

Common Lisp's print function returns the object that was printed. This reads a value from the user, then prints the value until the return value of the call to print returns 0.

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

BitCycle, 7 bytes

Golfed 4 bytes off my example program!

?~< !~+ 

Provide input as 0 or 1 on the command-line. The -s or -p debug options are recommended, especially when dealing with infinite output.

Explanation

BitCycle is a 2D language that works by moving bits around a playfield. Commands used in this program are:

  • ? puts input bit(s) onto the playfield, moving east
  • ~ duplicates and negates a bit, turning the original right and the negated copy left
  • < sends bits westward
  • + turns 1-bits right and 0-bits left
  • ! outputs bits

The input hits the first ~. A negated copy turns left (north) off the playfield and is discarded. The original bit turns right (south).

At the second ~, the original bit turns west into the ! and is output. A negated copy turns east.

If the original bit was 0, the negated copy is 1; it turns south at the +, goes off the playfield, and is discarded.

If the original bit was 1, the negated copy is 0; it turns north at the + and then west at the <. The 0 hits the first ~ again, where it turns right (north) off the playfield and is discarded. The negated copy (1) turns left (south), leading to an infinite loop.

\$\endgroup\$
1
  • \$\begingroup\$ Alternative 7 byter ?v~ newline !~+ \$\endgroup\$ Commented Mar 26, 2019 at 9:38
2
\$\begingroup\$

Aceto, 11 10 bytes

X p|1 rip^ 

reads a string and converts it to an integer. | tests for truthiness (1 is truthy, 0 is not) and mirrors horizontally if truthy (in that case moving to the 1). Otherwise, we'll go to 0, which pushes the 0, we print implicit zero and eXit.

If the number was truthy (e.g. 1), we got mirrored to the 1, which pushes a 1, prints, and goes one cell up (^), going into an infinite loop.

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

MarioLANG, 11 bytes

;>:[< ===== 

Explanation:

; Get numerical input and save in current cell > Move left (Required to make an infinite loop) : Output the current cell [ Skip next command if cell is 0 < Move right 

Basically, it loops infinitely unless input = 0

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

Wise, 3 bytes

[:] 

Try it online!

Wise cannot actually output whenever you want, it only outputs the entire stack when the program terminates. So the solution to infinitely output is to simply infinitely fill the stack. When the program eventually halts (never), it will output the stack that, at that theoretical point in time, will have infinite values in it.

Explanation

[:] Implicit input from command-line arg [ If last value is != 0.. : ..Duplicate last value on stack ] If last value is != 0, jump back to [ 

Given a non-zero number, will infinitely duplicate the input on the stack, after an infinite amount of time, will terminate and output the entire stack.

Given zero, jumps to the end of the program and immediately terminates, outputting the stack, which contains only the input.

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

Ly, 7 bytes

n:u[:u] 

Explanation:

n # take input :u # duplicate it and print it [ # while the top of the stack is not 0... :u # duplicate it and print it ] # end loop 
\$\endgroup\$
1
  • \$\begingroup\$ With the current version on TIO, this works n[:u] since the 0 on the stack prints when it exits. \$\endgroup\$ Commented Apr 16, 2022 at 6:40
2
\$\begingroup\$

6502 machine code (C64), 17 bytes

20 FD AE 20 9E B7 8A 09 30 20 D2 FF C9 30 D0 F9 60 

Online demo

This is position independent code, you can enter it at any position in RAM and call it, so it doesn't need a load address. Assuming you put it at C000 (that's the case in the online demo), call it like sys49152,0 or sys49152,1 -- any other input is undefined.

Explanation:

20 FD AE JSR $AEFD ; consume comma 20 9E B7 JSR $B79E ; evaluate number, result in X 8A TXA ; transfer X to A 09 30 ORA #$30 ; convert to numeric character 20 D2 FF JSR $FFD2 ; output character C9 30 CMP #$30 ; compare with '0' character D0 F9 BNE *-5 ; not equal? Then jump back to output (-7) 60 RTS ; return 
\$\endgroup\$
1
4 5
6
7 8
17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.