175
\$\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\$
    – Cruncher
    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\$
    – AviFS
    Commented Apr 26, 2020 at 1:42

502 Answers 502

1
2 3 4 5
17
207
+200
\$\begingroup\$

Hexagony, 6 bytes

This was surprisingly tricky, and I'm not convinced it's optimal...

<.@!$?

After padding and unfolding the code, this represents the following hex grid:

enter image description here

This uses a similar control flow like my recent error-free cat program, moving along anti-diagonals. To achieve that we start by deflecting the instruction pointer (IP) to the left, where the purple path wraps around to the lower left corner.

? reads the input as an integer. ! prints it back. . is just a no-op. Now the corner of the grid acts as a branch:

If the input was 0, the IP will continue along the red path, which simply terminates the program with @.

If the input was 1, the IP will continue on the green path. Again, . is just a no-op, but $ is the equivalent of Befunge's trampoline: it skips the next instruction. After wrapping, the next instruction would be the ?, but due to $ execution actually continues on the blue path, starting with ! to print another copy of the 1. This loop which only contains !..$ is now repeated indefinitely.

A study of control flow in Hexagony...

I believe the above solution is optimal. I've written a brute forcer, which checks all 6-byte Hexagony programs, which contain at least one each of ?!@ (which are necessary; I've also checked : and % in place of @ to terminate with a division-by-zero error, but that didn't help either). The check prints all the programs which a) produce a 0 on input 0 and terminate and b) produce at least two 1s (and nothing else) and don't terminate within the first 60 ticks of the program (200 ticks for 5-byte solutions). I doubt that any valid solution would take more than 200 ticks to correctly print the first 0 or the second 1 on such a small grid, so I don't think I've missed out on any potential solutions.

The search didn't yield any results for 5 bytes, but 57 results for 6 bytes (using @; there's no need to terminate with an error if we can solve this cleanly in the same amount of bytes). Of those 57 only 6 were false positives which actually printed only two 1s and then entered an infinite loop without printing any more. One solution was listed twice because it contained two ! commands. That leaves exactly 50 valid solutions.

There is a certain amount of degeneracy between the solutions where one or two characters are not substantial, e.g. because they're effectively no-ops anyway. The solutions can be grouped into 23 sets of genuinely distinct programs (in some cases, there is only a single character difference between two sets, but it changes the control flow substantially, so I've counted them separately). Two of the groups even make use of multiple instruction pointers in a very unexpected way. As I would never have come up with most of these ways to use the branches and mirrors, they make a very interesting study of what sorts of control flow are possible in Hexagony, and I have definitely learned some new tricks for future golfs.

The overall control flow is almost always the same: read a number, print it. If it's 0 find a way to the @, if not keep looping through the ! while mainting an edge value of 1. There are four notable exceptions:

  • One solution (the one with two !) prints two 1s per iteration through the grid, therefore printing about twice as fast as the majority of programs. I've marked this one with x2 below.
  • A few solutions (those which contain an o) replace the 1 with a 111 (the character code of o), so they print three 1s per iteration, making them print about three times as fast as the majority of programs. I've marked these with x3 below.
  • Two solutions append a 1 to the edge value in each iteration (so 1 --> 11 --> 111 --> ...). Those print very fast, but they'll run out of memory eventually. I've marked these with OoM below.
  • Two solutions enter a very tight loop which merely bounces back and forth over the !, printing on every other tick (instead of of every 5th or so), which makes them slightly faster (and neater). I've marked these with >< below.

So here is the entire zoo:

#1                #5                #12                #19
?!/$.@            ?$!>$@            .?!/$@             |!|?$@  # ><
?!/$1@  # OoM     ?$!|$@            =?!/$@
?!/$=@                                                 #20
?!/$\@            #6                #13                $@.?<!
?!/$o@  # x3      ?/!<|@            .?/!$@             $@1?<!  # OoM
?!/$!@  # x2                        =?/!$@             $@=?<!
                  #7                                   $@o?<!  # x3
#2                ?\!<|@            #14
?!>$)@                              \!?__@             #21
?!>$1@            #8                                   _>_!?@
?!>$o@  # x3      ?<!>$@  # ><      #15
?!|$)@                              \_?!$@             #22
?!|$1@            #9                                   <!@.$?
?!|$o@  # x3      ?\$!@$            #16                <!@/$?
                                    \_?!_@             <!@=$?
#3                #10                                  <$@!$?
?!|)$@            ?~#!@)            #17                <.@!$?
?!|1$@            ?~#!@1            $$?\@!             </@!$?
?!|o$@  # x3                                           <=@!$?
                  #11               #18
#4                ?$)\@!            \$?\@!             #23
?_!<@>            ?$1\@!                               <<@]!?
                  ?$o\@!  # x3

The following is a short walkthrough for a handful of the more representative groups. Especially groups 10 and 23 are worth checking out. There are many other interesting and sometimes convoluted paths in the other groups, but I think I've bored you enough at the end of this. For anyone who really wants to learn Hexagony, these are definitely worth investigating though, as they exhibit even more possible uses of the mirrors and $.

Group 1

This one isn't much more elaborate than my original solution, but the paths go in different directions. It also allows for the largest number of variations in a single cell, as the right-most no-op can be replaced with 5 different commands which still make this valid without changing the structure:

enter image description here

Group 2

This one is quite interesting, because it only moves horizontally. After wrapping to the >, the IP reverses immediately, taking the branch in the corner. It's not entirely well visibly no the diagram, but in the case of the 1 we traverse the first row again, but backwards this time. This also means we run into ? again, which now returns 0 (EOF). This is fixed with ) (increment) to keep printing 1s. This also has 5 variations, as ) could also be 1 or o, and > could also be |:

enter image description here

Group 3

This one looks almost identical to the previous one but it's messy as hell. Up to hitting | and then traversing the bottom or top row it's the same. But in the case of a loop, the $ now skips over the ) onto the mirror. So we follow the turquoise path to the right, now hit the increment, skip over the @ before we wrap around to the | again and then go back to the green path at the top.

enter image description here

Group 4

I thought this one was particularly nifty:

enter image description here

The _ mirror in the top right corner is initially a no-op, so we print with ! and hit the <. The 0 path now hits the horizontal mirror and terminates. The 1 path takes a really interesting trajectory though: it deflects down, wraps to the !, gets redirected towards the horizontal and then wraps back to the ! again. It then keeps moving in this rhombus shape, printing twice per iteration (every third tick).

Group 8

This is one of the two solutions with a really tight printing loop:

enter image description here

The < acts as the branch. After wrapping twice, 0 hits @. 1 on the other hand, first skips the ?, then > sends it onto the the $ again, so that is skips the @. Then the IP wraps into the turquoise path, where it bounces back and forth between the > and < (wrapping around the edge in between).

Group 10

One of two groups which use other instruction pointers, and it's absolutely beautiful. Hexagony has 6 - each one starts from a different corner along the clockwise edge, but only one of them is active at a time.

enter image description here

As usual, we read with ?. Now ~ is unary negation: it turns the 1 into a -1. Next, we hit the #. This is one way to switch between IPs: it takes the current edge value modulo 6 and switches to the corresponding IP (IPs are numbered from 0 in the clockwise direction). So if the input was 0, then the IP simply remains the same, and travels boringly straight ahead into !@. But if the input was 1, then the current value is -1 which is 5 (mod 6). So we switch to the IP which starts on the very same cell (the green path). Now # is a no-op and ? sets the memory edge to 0. ) increments so ! prints a 1. Now we hit ~ again to ensure that # is still a no-op (as opposed to switching us to IP 1 which would terminate the program). It's mindblowing how well everything fits together in this little program.

Group 22

Just to note, this is the group my original solution is in. It also happens to be largest group, because the no-op can be in two different places, and there are several choices for the actual (effective no-op) command.

Group 23

This is the other group using multiple IPs. In fact this one uses 3 different IPs. The top right corner is a bit of a mess, but I'll try to walk you through this:

enter image description here

So, the beginning you've seen before: < deflects North-East, ? reads input. Now ] is another way to change between IPs: it hands control to the next IP in clockwise order. So we switch control to the turquoise path which (I know it's hard to see) starts in the North-East corner going South-East. It is immediately reflected by the < so that it wraps to the South-East corner, going North-West. It also hits the ] so we switch to the next IP. This is the grey path starting in the East corner, going South-West. It prints the input, then wraps to the North-East corner. < deflects the path into the horizontal, where it is reflected by the other <. Now the right-hand < acts as a branch: if the input was 0, the IP moves North-East, and wraps to the @. If the input was 1, the IP moves to the !, wraps to the lef-thand < where it is reflected... now in the corner, it wraps back to the !, gets deflected by the the right <, reflected by the left < and the paths starts over...

Quite a mess, but a beautiful mess. :)


Diagrams generated with Timwi's amazing HexagonyColorer.

\$\endgroup\$
2
  • 63
    \$\begingroup\$ whoa. just whoa. \$\endgroup\$ Commented Nov 4, 2015 at 22:38
  • 8
    \$\begingroup\$ @ThomasOltmann I admit this answer assumes some basic knowledge of the language. If you're actually interested in learning more about it, I've gone through the basics in this answer and in this answer, but I won't blame you if you're not. ;) \$\endgroup\$ Commented Nov 6, 2015 at 19:31
158
\$\begingroup\$

Motorola MC14500B Machine Code, 2 bytes

In hex:

58EC

Explanation:

5  OR the register with input from the data bus
8  Write the register to the data bus
E  Skip next instruction if register is zero
C  Jump

The Motorola MC14500B is a 1-bit microcontroller; it has one 1-bit register and a 1-bit data bus. Since the opcodes are 4 bits each, there are only sixteen; half of them carry out a logical operation between the register and the bit on the data bus.

The jump instruction sets a jump flag; when no address is provided, it is common to set the program counter to 0. If the input bit was zero, the processor will not jump. If the input bit was 1, the processor jumps back to the start; since we're ORing with input, it doesn't matter what the input signal is afterwards—the register will then be 1 forever.

As is conventional, the register is initialized to 0.

A list of the opcodes can be found on the data sheet, or here.

\$\endgroup\$
9
  • 10
    \$\begingroup\$ 2 bytes is definitely the minimum for this challenge. \$\endgroup\$ Commented Nov 4, 2015 at 2:52
  • 30
    \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ I've been looking for several hours through esolangs and lists of 4-bit processors to see if there's a 1 or 1.5, and haven't found one. \$\endgroup\$
    – lirtosiast
    Commented Nov 4, 2015 at 3:07
  • 1
    \$\begingroup\$ Definitely the right tool for the job. \$\endgroup\$
    – user23597
    Commented Nov 9, 2015 at 12:49
  • \$\begingroup\$ Link is borked atm... \$\endgroup\$
    – TheDoctor
    Commented Nov 17, 2015 at 4:19
  • \$\begingroup\$ @TheDoctor Both links work fine for me \$\endgroup\$
    – user45941
    Commented Nov 17, 2015 at 6:00
92
\$\begingroup\$

Arnold C, 296 Bytes

IT'S SHOWTIME
    HEY CHRISTMAS TREE i    
    YOU SET US UP @NO PROBLEMO
    BECAUSE I'M GOING TO SAY PLEASE i
        STICK AROUND i
            TALK TO THE HAND i
        CHILL
    BULLSHIT
        TALK TO THE HAND i
    YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE BEEN TERMINATED

Not really competitive, but for the fun of it. Does not support stdin, replace @NO PROBLEMO with @I LIED for a zero value. @No Problemo is 1.

Run with (assuming file is truthmachine.arnoldc):

wget http://lhartikk.github.io/ArnoldC.jar
java -jar ArnoldC.jar truthmachine.arnoldc
java truthmachine
\$\endgroup\$
7
  • 51
    \$\begingroup\$ Beautiful. I cried 10/10 \$\endgroup\$ Commented Nov 3, 2015 at 17:56
  • 13
    \$\begingroup\$ BECAUSE I'M GOING TO SAY PLEASE LOL \$\endgroup\$ Commented Nov 3, 2015 at 22:14
  • 9
    \$\begingroup\$ It looks like this does if(i){while(i) print(i);} else {print(i);} Surely it would be shorter to do print(i);while(i) print(i);? \$\endgroup\$
    – lirtosiast
    Commented Nov 4, 2015 at 16:21
  • 20
    \$\begingroup\$ Although BULLSHIT has a great contribution to the entertainment value of the program, technically it is unnecessary. You can factor the whole BULLSHIT branch out by moving TALK TO THE HAND i after YOU HAVE NO RESPECT FOR LOGIC. \$\endgroup\$
    – gaborsch
    Commented Nov 6, 2015 at 9:46
  • 6
    \$\begingroup\$ @GaborSch There is only one proper response to that: BULLSHIT ;) \$\endgroup\$ Commented May 16, 2017 at 22:52
74
\$\begingroup\$

Minecraft, 18 Bytes (MC Version 15w45a)

minecraft sketch

As you can see, there is a lever directed into the repeating command block, which has the command say 1 in it. There is an signal inverting torch on top of that, which directs power into the single-run command block with the command say 0 in it.

Whenever the switch is directed towards truthy, the repeater block uses the code say 1 to output infinite 1s. When the lever is redirected to false, it outputs a single 0.

Note that this outputs a [@] by default. If you really want just straight up 1s and zeros, this becomes 34 bytes, where the code in the command blocks are tellraw @a [1] and tellraw @a [0]. This is using @Cᴏɴᴏʀ O'Bʀɪᴇɴ's suggested byte count for MC as can be found in Meta.

\$\endgroup\$
3
  • 37
    \$\begingroup\$ You used a video game for code golf. +1 \$\endgroup\$
    – RK.
    Commented Nov 18, 2015 at 13:57
  • 13
    \$\begingroup\$ @RK. This is actually fairly standard practice for simple challenges. There are at least two other users who use MC as a code golfing language - try the search bar with is:answer Minecraft. c: \$\endgroup\$ Commented Nov 18, 2015 at 14:33
  • 2
    \$\begingroup\$ @FlagAsSpam lol nicely done. Also, thanks for that tip to search MC answers. \$\endgroup\$ Commented Dec 8, 2015 at 4:11
67
\$\begingroup\$

Bash + GNU utils, 13

grep 0||yes 1

Bash, 35

read n;for((;n;));{ echo 1;};echo 0
\$\endgroup\$
2
  • 3
    \$\begingroup\$ You know, I was wondering if a bash solution with yes would be possible... \$\endgroup\$ Commented Nov 3, 2015 at 19:36
  • 2
    \$\begingroup\$ Nice! That's pretty clever \$\endgroup\$ Commented Nov 3, 2015 at 19:52
43
\$\begingroup\$

Microscript, 3 bytes

i{p

The shortest one I know.

Explanation:

i  Takes numeric input and puts it in register 1
{  while register 1 is truthy
  p  Print the contents of register 1

Microscript has implicit printing of register 1 upon termination, which is the reason why an input of 0 gets printed once.

\$\endgroup\$
4
  • \$\begingroup\$ @quartata I matched you :D \$\endgroup\$ Commented Nov 3, 2015 at 17:17
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ :O \$\endgroup\$ Commented Nov 3, 2015 at 17:18
  • 2
    \$\begingroup\$ I'm seriously wondering if you wrote the question first, or the answer... \$\endgroup\$ Commented Nov 8, 2015 at 14:56
  • 1
    \$\begingroup\$ The question. I just wanted to post this since it was the shortest one I came up with while writing the question. It is a catalog so there aren't any real winners. \$\endgroup\$ Commented Nov 8, 2015 at 15:07
41
\$\begingroup\$

Ruby, 20

print while/1/||gets

Run from the command line to avoid warnings, as

ruby -e "print while/1/||gets" <<< 0
ruby -e "print while/1/||gets" <<< 1

Explanation:

Less golfed, this is

while /1/ || gets
  print
end

When a Regexp is used in a conditional, it evaluates as falsey unless the variable $_ is populated and matches the pattern. On the first time through the loop, $_ is empty so we fall through to gets, which sets the value of $_ to a line read from STDIN. print with no arguments prints $_. Now we evaluate the conditional again. If we read in 1, we short-circuit and just print 1 again, and so on forever. Otherwise, we fall through to gets, but since there's no second line of input, gets returns nil, so the loop ends.

\$\endgroup\$
3
  • 19
    \$\begingroup\$ It's nice when trivial tasks still allow mindblowing solutions even in "normal" languages. :) \$\endgroup\$ Commented Nov 3, 2015 at 17:20
  • \$\begingroup\$ The ||gets part is cool and all, but can't you just do gets;print while/1/ and save a byte? \$\endgroup\$
    – daniero
    Commented Aug 27, 2016 at 20:54
  • \$\begingroup\$ No, then it doesn't print the 0 at all. \$\endgroup\$
    – histocrat
    Commented Aug 28, 2016 at 1:41
39
\$\begingroup\$

Turing Machine Code, 32 22 bytes

Using the rule table syntax found here.

0 0 0 * halt
0 * 1 r 0
\$\endgroup\$
2
  • \$\begingroup\$ I really like this. +1 \$\endgroup\$ Commented Nov 3, 2015 at 17:28
  • \$\begingroup\$ I knew someone would've already posted this! \$\endgroup\$
    – yyny
    Commented Feb 1, 2016 at 0:55
32
\$\begingroup\$

Python 2, 29 bytes

a=input()
while 1:print a;1/a

This terminates with a division error on 0, which is allowed by default.

\$\endgroup\$
6
  • \$\begingroup\$ STDERR output is fine. The ><> answer uses it as well. \$\endgroup\$ Commented Nov 3, 2015 at 20:09
  • \$\begingroup\$ This is brilliant ^_^ \$\endgroup\$
    – ABcDexter
    Commented Sep 1, 2016 at 9:36
  • \$\begingroup\$ Would while a print a work? Sorry, I dont know python. \$\endgroup\$ Commented Sep 14, 2016 at 0:42
  • 2
    \$\begingroup\$ @RohanJhunjhunwala For 0, it wouldn't print anything, but it should print it once. \$\endgroup\$
    – xnor
    Commented Sep 14, 2016 at 1:30
  • 1
    \$\begingroup\$ @xnor oh, my bad. \$\endgroup\$ Commented Sep 14, 2016 at 20:27
30
\$\begingroup\$

JavaScript, 28 bytes

For loops are often shorter than while loops.

alert(x) returns undefined, which is falsy, so the bitwise or operator, |, casts it to 0. Thus, if x is "0", alert once, otherwise keep looping. Uses alert for STDOUT like this answer.

for(x=prompt();alert(x)|x;);
\$\endgroup\$
8
  • \$\begingroup\$ Shoot, you beat me to it. I was about to post exactly this! :) GG \$\endgroup\$
    – Domino
    Commented Nov 3, 2015 at 21:35
  • \$\begingroup\$ Wow, that's a good bit more clever than mine :) Have a +1! \$\endgroup\$ Commented Nov 3, 2015 at 22:01
  • \$\begingroup\$ You don't need the trailing semicolon. \$\endgroup\$ Commented Nov 6, 2015 at 21:36
  • 1
    \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ What browser did you use? I tested it on Firefox and Chrome and I get a SyntaxError without it. \$\endgroup\$ Commented Nov 6, 2015 at 22:25
  • 2
    \$\begingroup\$ Yeah, you need one because it's a for loop. :) \$\endgroup\$
    – Domino
    Commented Nov 7, 2015 at 21:22
22
\$\begingroup\$

Brainfuck, 41 36 31 30 bytes

Shortened by printing once right after input and with help from Ethan and user46915.

,.+++[->>+<-----<]>>---<-[>.<]

Previous version: Subtract 48 from the input, and if it's not zero, add 1 to the 48 to print ASCII 1 forever, otherwise print 0.

-[>+<-----]>--->,<[->->+<<]>[>+<]>.<[>.<]

I ran it here, but due to buffered output, you cannot see any output since the program never terminates on 1.

Edit: I had forgotten to print 0 on input 0. Fixed now. I like the >.< faces at the end.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ @ThomasKwa I'm guessing not, but I'm not sure since I don't see an algorithm specifically for modulo 2. The divmod algorithm is a little long. \$\endgroup\$
    – mbomb007
    Commented Nov 3, 2015 at 19:13
  • 2
    \$\begingroup\$ You can shorten it a bit more by merging the pieces of code together a bit better and directly using your input register instead of having a separate "48" register: ,.[>+>+<<-]-[>-<-----]>+++[>.<] \$\endgroup\$
    – Ethan
    Commented Nov 3, 2015 at 21:53
  • \$\begingroup\$ Attempted a solution with mod 2. Definitely looks like subtracting 48 is the right way to go. ,.[->+>+<<]>>[->[>-<[-]]>+[<+>-]<<]>[<<.>>] \$\endgroup\$ Commented Nov 3, 2015 at 23:34
  • 1
    \$\begingroup\$ @Ray That's the default and is generally assumed. Had I used another implementation, I would've said so. \$\endgroup\$
    – mbomb007
    Commented Nov 4, 2015 at 5:17
  • 1
    \$\begingroup\$ You can get one more byte off by combining subtraction and copying together: ,.+++[->>+<-----<]>>---<-[>.<] \$\endgroup\$
    – user46915
    Commented Nov 9, 2015 at 6:09
22
\$\begingroup\$

Pyth, 4 3 2

Wp

There is a no! trailing space (thanks isaac :) ). The space used to be required to make the while loop compile, but Pyth has since been updated. Normally that would disqualify using it, but since this is a catalog it should be valid.

Explanation:

Wp        : implicit Q = eval(input)
W         : while
 p        : print and return the value of Q, to be evaluated as the while condition
          : Functions without enough arguments automatically use Q now
          : do nothing in the body of the while loop
\$\endgroup\$
9
  • 6
    \$\begingroup\$ I was inspied by this answer to add implicit pass to Pyth. The space is now unnecessary. pyth.herokuapp.com/?code=WpQ&input=0&debug=0 \$\endgroup\$
    – isaacg
    Commented Nov 4, 2015 at 1:37
  • 58
    \$\begingroup\$ Crossed four still looks like a four. \$\endgroup\$ Commented Nov 4, 2015 at 2:54
  • 1
    \$\begingroup\$ Eh, I'm just getting so bored of seing pyth dominate everything all the time :(. LOL. \$\endgroup\$ Commented Dec 8, 2015 at 4:12
  • 1
    \$\begingroup\$ @AshwinGupta my language technically beat it, so it's not completely dominating :) \$\endgroup\$
    – Cyoce
    Commented Jan 5, 2016 at 7:53
  • \$\begingroup\$ @Cyoce yeah! Good job! I rest assured that something can beat pyth lol. \$\endgroup\$ Commented Jan 5, 2016 at 15:01
20
\$\begingroup\$

Piet, 27 18 16 codels

(Codel is a fancy name for pixel used to avoid confusion when an image is stretched for viewing. I counted codels instead of bytes because piet scripts are saved as images, so the physical size may vary. I think an ideal file format that would save this piet as efficiently as possible would take 11 bytes. In practice, my tiny gif file is 62 bytes, with optimal palette data. Tell me if I should use this as the size of my entry instead of the codel amount.)

Original image: tiny version

Enlarged: enlarged version

In piet, the difference between two colors is what determines which command runs, so seeing the same color twice doesn't mean it does the same action. The execution begins in the top-left codel. Then it moves horizontally, performing the following:

  1. Read a number and put it on the stack
  2. Duplicate the top of the stack
  3. Pop and output the top of the stack
  4. Pop the top of the stack and rotate clockwise that number of times.

If the input was 1, the cursor then moves down into the lime codel, which pushes 1 on the stack. Then the execution continues going left. When the cursor passes from a color to white and from white to a color, nothing happens. Since black is considered as walls too, the cursor ends up going back to the lime codel on the top line, and repeats the whole thing from step 2.

If, however, the input was 0, the cursor will never go down and will end up in the blue J on the right (pun intended, it was worth it), were it will stay trapped (because the top, right, left and bottom sides of this J-shaped block are next to black codels or the edge of the image). Since the cursor is trapped, execution ends.

Unexpected values:
If the user writes another number, it will still be printed, then the cursor will rotate more or less times based on the value.

  • Multiple of 4 or 0: execution continues horizontally and ends.
  • Multiple of 3: Since going up is impossible, the cursor immediately rotates clockwise and continues horizontally, then ends.
  • Multiple of 2 and not a multiple of 4: the cursor rotates and starts moving to the left. Luckily, all this does is perform a bunch of operations that don't affect the program flow and end up emptying the stack. When an operation can't be done because the stack is empty, it is simply ignored. When it hits the top left corner, the cursor has nowhere else to go but to the right again, effectively restarting the program.
  • Other values: The cursor goes down as if it would with 1, which makes it print 1 forever. If the input is 5, the output will be 5111111111111...

Any non-integer value will terminate the program. Execution will continue normally, but all operations will be ignored since there is nothing in the stack. So in a way, the program never crashes - it either stops normally or loops forever.


PietDev friendly version

PietDev (a very basic online Piet IDE) seems to have trouble with white codels so I made a new version which manually rotates back up instead of relying on proper white codel automatic rotation. And I didn't even need to use a new color! If you want to test with it, make sure you draw a black border around the code because PietDev doesn't support custom program sizes.

tiny version

enlarged version


Older versions

The first version didn't push 1 back on the stack and instead looped back to an earlier duplication instruction. It also had decorative useless codels.

Tiny pattern which is actually a piet code

Enlarged version

Then I had the idea to push 1 on the stack to remove the blank line. It's funny how I thought of it thanks to my decorative codels.

tiny version

large version

Then I realized I had an extraneous dup that wasn't needed anymore, and I reduced the number of colors to save up on palette data in the image. I also got rid of the single decorative codel because I don't know.

\$\endgroup\$
9
  • 8
    \$\begingroup\$ I've never seen a Piet answer scored in anything other than codels, but I think the optimal byte count is also interesting to include :) \$\endgroup\$ Commented Nov 3, 2015 at 21:39
  • 1
    \$\begingroup\$ There are 20 different codel values, which means you should be able to pack three codels into 13 bits, then eight triplets into 13 bytes for a storage density of 2.6 codels per byte. But someone has to define that language first. I suggest the name DPPi = densely packed piet. \$\endgroup\$ Commented Nov 8, 2015 at 15:05
  • 1
    \$\begingroup\$ @JanDvorak I counted 21 values to add a special one for line break, and once you're got the first line break the parser can guess where the other ones should be. But I didn't go as far as combining codels into triplets, which makes much more sense than wasting 5 bits per codel. Clever. \$\endgroup\$
    – Domino
    Commented Nov 8, 2015 at 19:30
  • 1
    \$\begingroup\$ Just add the dimensions as the first couple of bytes. You don't need an extra symbol. \$\endgroup\$ Commented Nov 8, 2015 at 19:37
  • 1
    \$\begingroup\$ @everyone who wants to try it out: Don’t try this solution with PietDev because PietDev only prints a single 1 and terminates. But the solution works properly with npiet. \$\endgroup\$
    – M L
    Commented Feb 15, 2016 at 23:23
19
\$\begingroup\$

Chip, 6 bytes

e*faAs

Chip is a 2D language that behaves a bit like an integrated circuit. It takes input, one byte at a time, and breaks out the bits to individual input elements. Output stitches the values of output elements back together into bytes.

Let's break this down:

* is a source signal, it will send a true value to all adjacent elements. e and f correspond to the fifth and sixth bit of the output. So, e*f produces binary 00110000, which is ASCII char "0".

Now, A is the first bit of input and a is the first bit of output, so aA copies that bit from input to output. So, when combined with e*f, an input of ASCII "0" produces "0", and "1" produces "1". (There is no interaction between f and a, since neither produce any signal.)

The s on the end, when activated by a true signal, will prevent input from advancing to the next byte, meaning that the whole thing will run again with the same input.

Since the first byte of "0" is zero, it won't activate this element and the program will print "0", and thereby exhaust its input, which allows it to terminate. "1", however, activates this element, which means that "1" is output, but not consumed on the input, allowing the cycle to repeat indefinitely.

If values 0x0 and 0x1 are used for output, rather than ASCII, we can eliminate the e*f part, resulting in only 3 bytes:

aAs

If the zero must terminate itself, rather than expecting stdin to close, we get the following, which inverts the first byte with ~, and passes the result to t, which terminates the program (10 bytes):

aA~te*f
 s

(t also produces no signal, so there is no interaction between t and e.)

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Nice answer! Since this is a catalog challenge, there's no need to mark this as non-competing, so I've removed that bit for you. Welcome to PPCG! \$\endgroup\$
    – user45941
    Commented Jan 30, 2017 at 23:31
  • 5
    \$\begingroup\$ I took the liberty of adding Chip to TIO. Try it online! \$\endgroup\$
    – Dennis
    Commented Jan 31, 2017 at 1:24
  • \$\begingroup\$ @Dennis, question for you: how would I get TIO to update its source? Last week I fixed a bug in the Chip interpreter, but it hasn't propagated the change into TIO. Is this something I need to ask someone to do for me? \$\endgroup\$
    – Phlarx
    Commented Feb 7, 2017 at 17:18
  • \$\begingroup\$ I've pulled Chip. If you need something updated, just leave a message in talk.tryitonline.net. \$\endgroup\$
    – Dennis
    Commented Feb 7, 2017 at 17:21
16
\$\begingroup\$

Brainbool, 5 bytes

,.[.]

Brainbool is Brainfuck, but it only operates on bits, and does I/O through 0 and 1 characters.

\$\endgroup\$
3
  • 3
    \$\begingroup\$ I knew there had to be a BF derivative where this could be feasibly done. \$\endgroup\$ Commented Nov 3, 2015 at 18:26
  • 16
    \$\begingroup\$ I feel like "Boolfuck" might be a better name for it, but well done regardless. \$\endgroup\$ Commented Nov 4, 2015 at 5:36
  • 2
    \$\begingroup\$ @JamesMurphy it seems that exists already: esolangs.org/wiki/Boolfuck \$\endgroup\$
    – DLeh
    Commented Nov 9, 2015 at 20:49
16
\$\begingroup\$

Bitwise Cyclic Tag, 3 bits or < 1 byte

Bitwise Cyclic Tag is one of the simplest Turing-complete languages out there. It works with two bitstrings, the program and the data. The bits of the program are read cyclically and interpreted as follows:

  • 0: Delete the first data bit (and output it, in implementations that have output).
  • 1x: If the first data bit is 1, append x (representing either 0 or 1) to the end of the data. (If the first data bit is 0, do nothing.)

The program runs until the data string is empty.

Truth-machine

110

When the data string is set to 0:

  • 11 does not append anything because the first data bit is not 1.
  • 0 deletes/outputs 0.
  • The data string is now empty and the program halts.

When the data string is set to 1:

  • 11 appends a 1.
  • 0 deletes/outputs 1.
  • The data string is back to a single 1 and the program is back to where it started, so we loop forever.
\$\endgroup\$
15
\$\begingroup\$

LOLCODE, 119 bytes

GIMMEH n
n R SUM OF n AN 0
BOTH SAEM n AN 0, O RLY?
YA RLY
 VISIBLE 0
NO WAI
 IM IN UR l
  VISIBLE 1
 IM OUTTA UR l
OIC

Ungolfed:

HAI

BTW, Read n as a string from STDIN and convert to an integer
GIMMEH n
n R SUM OF n AN 0

BTW, Test n for equality with 0
BOTH SAEM n AN 0, O RLY?
YA RLY
    BTW, Write 0 to STDOUT and exit
    VISIBLE 0
NO WAI
    BTW, Loop forever, printing 1
    IM IN YR l
        VISIBLE 1
    IM OUTTA YR l
OIC

KTHXBYE
\$\endgroup\$
4
  • 2
    \$\begingroup\$ 1. Which interpreter are you using? 2. Can you MAEK n A NUMBR to cast? 3. Can you use DIFFRINT instead of BOTH SAEM and switch the conditionals? \$\endgroup\$
    – lirtosiast
    Commented Nov 9, 2015 at 5:15
  • 3
    \$\begingroup\$ @ThomasKwa I was using LOLCOFFEE, the one on repl.it. (Which appears to be down at the moment, so I'll test your suggestions once it's back up.) \$\endgroup\$
    – Alex A.
    Commented Nov 9, 2015 at 5:28
  • \$\begingroup\$ Doesn't O RLY? cast to boolean? \$\endgroup\$
    – Leaky Nun
    Commented Jul 22, 2016 at 17:38
  • \$\begingroup\$ @LeakyNun No...? O RLY? is like a postfix if. \$\endgroup\$
    – Alex A.
    Commented Jul 22, 2016 at 23:54
13
\$\begingroup\$

Labyrinth, 7 bytes

 ?+
@!:

Labyrinth is a 2D stack-based language where control flow depends on the sign of the top element of the stack, checked after every instruction. Execution begins moving rightward from the first valid instruction on the top row, which here is the ?.

The relevant instructions are:

?      Input integer
+      Add top two elements (Labyrinth's stack has infinite 0s on the bottom)
:      Duplicate top element
!      Output as number
@      Terminate program

If the input is 0, the IP reads input with ?, adds the top two of the stack (0 + 0 = 0), then duplicates : and outputs ! a 0. Here we encounter the sole junction in the program, and have to check the top of the stack to determine where to go. Since the top is 0, we move forward and terminate with @.

On the other hand, if the input is 1, we do the same instruction as before (but outputting a 1) before reaching the junction at the !. Now the top of the stack is positive, causing us to turn right into the ?. On EOF Labyrinth pushes 0, so we do 0 + 1 = 1 at the +, duplicate :, and output !. Once again we have a 1 at the top of the stack and the loop continues.

For a bonus, here's @MartinBüttner's 7 byte solution, which operates similarly:

?+!@
1!

Note that, unlike most languages, 1 actually pops n off the stack and pushes n*10 + 1, making the building up of large numbers easy. However, since the top of the stack is empty at that point, it's no different from merely pushing 1.

\$\endgroup\$
13
\$\begingroup\$

C, 37 bytes

A different take on how to do it in C.

main(c){for(gets(&c);putchar(c)&1;);}

c defaults to an int of value 1. gets(&c) gets a string from stdin, here clobbering the value of c, hackishly since c is not a char*. putchar(c) prints the value of c to stdout, and returns c. Since '0' is 48 and '1' is 49 in ASCII, we can use the last bit (&1) to determine which it is. If it's '0', the loop breaks. Otherwise, it goes forever.

Compiles (with a warning about gets) and runs under gcc-4.8 on Linux.

\$\endgroup\$
4
  • 3
    \$\begingroup\$ Presumably this only works on little-endian architectures. \$\endgroup\$
    – Neil
    Commented Nov 4, 2015 at 20:20
  • \$\begingroup\$ @Neil I would assume so. \$\endgroup\$
    – cbojar
    Commented Nov 4, 2015 at 21:29
  • \$\begingroup\$ @Neil Endianness only affects byte order in multibyte values. \$\endgroup\$ Commented Nov 7, 2015 at 21:55
  • 2
    \$\begingroup\$ @LegionMammal978 c defaults to an int, which is a multibyte value, and on a big-endian architecture, gets will set the wrong byte. \$\endgroup\$
    – Neil
    Commented Nov 8, 2015 at 0:51
13
\$\begingroup\$

><>, 7 bytes

i2%:n:,

This uses the fact that ><> pushes -1 on EOF, which is 1 mod 2. It also uses divide by 0 for termination (which is apparently okay since the consensus is that STDERR output is ignored).

Just for reference, exiting cleanly without errors is an extra byte:

i2%:n?!;
\$\endgroup\$
1
  • \$\begingroup\$ i2%:n?. With input on the stack like the other answers, this could be just :?:n \$\endgroup\$
    – Jo King
    Commented Jun 29, 2021 at 4:48
11
\$\begingroup\$

><>, 6 bytes

::n?!;

Pushes the input on the stack to start

:        copy top element on stack
 :       copy top element on stack again
  n      pop and outputs top element
   ?     condition trampoline - pops top element, if it is zero skips next instruction
    !    trampoline skips next instruction
     ;   finish execution
\$\endgroup\$
10
  • 2
    \$\begingroup\$ Here at PPCG, we love our explanations. +1 \$\endgroup\$ Commented Nov 3, 2015 at 22:08
  • 3
    \$\begingroup\$ I'm pretty sure this only works with literal 0 and 1 inputs, when it's supposed to work with 48 ('0') and 49 ('1'). Am I mistaken? \$\endgroup\$ Commented Nov 3, 2015 at 22:09
  • \$\begingroup\$ @quartata If it was me I'd say that, to be fair to any answers that use from more traditional methods of getting input, you should have to put 48 or 49 on the stack. It's your challenge though and it's not a huge deal anyway so ¯\_(ツ)_/¯ \$\endgroup\$ Commented Nov 3, 2015 at 22:16
  • 2
    \$\begingroup\$ There's another problem with this: if the stack is pre-populated, then you have to add 3 bytes for the -v flag. \$\endgroup\$ Commented Nov 4, 2015 at 8:57
  • 1
    \$\begingroup\$ @Aaron: For what it's worth, I too thought it was 2 bytes for -v, then I was corrected. So you're not the only one. :) \$\endgroup\$ Commented Nov 4, 2015 at 20:52
11
\$\begingroup\$

APL, 6 bytes

→⎕←⍣⍲⎕

Explanation:

     ⎕ Read the input, then
 ⎕←    write it out
   ⍣   repeatedly
    ⍲  until NAND of it with itself becomes true.
→      Branch to zero to avoid printing the result again.
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Are the second and the last characters supposed to look different? Because they don't for me. \$\endgroup\$ Commented Nov 8, 2015 at 15:09
  • \$\begingroup\$ @JanDvorak Nope, they're the same. \$\endgroup\$
    – Alex A.
    Commented Nov 9, 2015 at 4:39
  • 2
    \$\begingroup\$ OK, now I'm looking at it on mobile and everything but the two arrows looks the same to me :-D \$\endgroup\$ Commented Nov 9, 2015 at 7:15
11
\$\begingroup\$

Seriously, 4 3 bytes

Crossed-out 4 is still 4 :(

,W■

, reads a value from STDIN. W starts a loop that runs while the value on top of the stack is truthy, with the body . prints the top stack element without popping. The loop is implicitly closed at EOF.

On input of 0, the loop never executes (since 0 is falsey), and the program ends at EOF, automatically popping and printing every value on the stack. On input of 1 (or any value that is not 0, "", or []), the loop runs infinitely.

In Actually, the leading , is not needed (thanks to implicit input), bringing the score down to 2 bytes.

\$\endgroup\$
0
10
\$\begingroup\$

GNU sed, 10

:;/1/{p;b}

Explanation

  • : define an unnamed label
  • /1/ If input matches the regex 1, then
  • p print the pattern space (i.e. 1)
  • b and jump back to the unnamed label (forever)
  • If the input was not 1 (i.e. 0), then the pattern space is printed unmodified and the program ends.
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Shave 1 character off using :;p;/1/b and the n flag, for a total of 9 bytes. Since sed -f is used anyway to run the script file, adding that extra flag doesn't require 2 bytes. \$\endgroup\$
    – seshoumara
    Commented Aug 28, 2016 at 16:08
10
\$\begingroup\$

Brian & Chuck, 21 bytes

,}<-{-?<SOH>_{+?
_>+{?<.p

Here, <SOH> should be replaced with the corresponding control character (0x01).

Explanation

The basic idea is to subtract the character code of the input (48 or 49) from the p at the end of Chuck, which will either give a ? (which is a valid command) or a @ which is a no-op.

, reads the input character into Chuck's first cell (marked with _). We want to decrement this value down to 0 in a loop, while making some other changes:

}< moves to the p and - decrements it. Then { moves back to the input cell - decrements that as well. As long as this isn't zero yet, ? gives control to Chuck. Now > moves Brian's tape head one cell to the right (which is initialised to 1) and + increments that. Then we reset the loop with {?.

By the time the first cell on Chuck hits 0, the <SOH> cell will have been incremented to the character we've read from STDIN and p will be ? for input 1 or @ for input 0.

Now ? doesn't switch control any more. The 0 or 1 after it is a no-op, as is the null-byte (represented by _). { moves back to Chuck's first cell and + increments to ensure that it's positive, such that ? hands control over to Chuck.

This time >+ increments the cell after the end of Brian's initial tape. That cell is garbage but we'll never use it. Now { doesn't scan all the way to the front of Brian's tape, but only to the _. Hence ? is a no-op because the current cell is zero. Then <. moves one to the left (the copy of the input character) and prints it.

Finally, we encounter the ? or @. If the input was 0 and this cell is @ it's a no-op and the program terminates. But if the input was 1 and this cell is ? we hand over to Brian whose {+? will reset the loop on Chuck, and now we're printing 1s forever (until the integer in the cell at the end of Brian's tape doesn't fit into memory any more, I suppose...).

Bonus

Sp3000 and I have been golfing away at this for several days. We started out around 40 bytes and arrived at two completely different, but tied solutions at 26 bytes. Only when I started to write up the explanation for mine, did the 21-byte solution above occur to me. Many thanks to Sp for throwing ideas around and teaching each other some golfing tricks in B&C. :)

This is his 26 byte solution:

>,----{?{>1?0
#I<?_}<.<<<?

And this is mine:

,{>-<-?_0+?_1{<?
_®{?_{>.?

Where ® is a byte with value 174 (e.g. just save the file as ISO 8859-1).

At the core mine works similarly to the 21-byte solution, in that ® becomes } for input 1 and ~ (no-op) for input 0, but the execution is much less elegant.

His solution is quite neat in that the source code is ASCII-only and that it doesn't require a loop to process the input. Instead, ---- turns 1 into - and 0 into , (a no-op for Chuck). That - will then change the first ? on Brian's tape into a >, thereby creating different control flow for the 1-case.

\$\endgroup\$
9
\$\begingroup\$

Thue, 34 bytes

1::=12
2::=~1
0::=~0
@::=:::
::=
@

Explanation:

1::=12 Instances of the substring "1" can become "12"

2::=~1 Instances of the substring "2" can be removed, printing "1"

0::=~0 Instances of the substring "0" can be removed, printing "0"

@::=::: Instances of the substring "@" can be replaced with strings from the input

::= End list of substitution rules

@ The initial string is "@"

\$\endgroup\$
0
9
\$\begingroup\$

Arnold C, 134 bytes

IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 0         //or 1
STICK AROUND i
TALK TO THE HAND 1
CHILL
TALK TO THE HAND 0
YOU HAVE BEEN TERMINATED

While this isn't as entertaining as the other ArnoldC answer, it's golfed. For example, indentation is unnecessary, and so are the macros @NO PROBLEMO and @I LIED.

Tested with this version of the language, which cannot take input.

\$\endgroup\$
9
\$\begingroup\$

Cubix, 5 6 bytes

Cubix is @ETHproductions new 2 dimensional language where the commands are wrapped around the faces of a cube. Online interpreter Thanks to @ETHproductions for the saving.

!I\@O

This ends up expanded out to the cube

  !
I \ @ O
  .

This starts with the I command. Input an integer onto the stack.
\, redirects the instruction pointer down over the no op.
O, outputs the numeric value of top of stack.
!, skip the next command (@) if top of stack true. This will jump the \ redirect if 1
\, redirects the instruction pointer to the @ exit program.

This takes advantage of the fact the stack isn't popped by the O ? ! commands.

\$\endgroup\$
5
  • \$\begingroup\$ Nice. I'm really glad to see someone else using my language :) I have another 6-byte solution that only uses 5 instructions (plus a no-op), so perhaps I'll post that. \$\endgroup\$ Commented Mar 15, 2016 at 1:02
  • \$\begingroup\$ @ETHproductions post it for sure. I think you've got a promising language here :) \$\endgroup\$
    – MickyT
    Commented Mar 15, 2016 at 1:15
  • \$\begingroup\$ You can save a byte by removing the ? and just using !: !I\@O \$\endgroup\$ Commented Mar 15, 2016 at 15:26
  • \$\begingroup\$ @ETHproductions very nice \$\endgroup\$
    – MickyT
    Commented Mar 15, 2016 at 17:47
  • 1
    \$\begingroup\$ I've written a brute-forcer for this (warning: freezes your browser for a minute or two), which comes up with exactly five 5-byte solutions: @IOw!, @I?Ov, @!IOw, !IOW@, !I\@O \$\endgroup\$ Commented Mar 17, 2016 at 15:39
8
\$\begingroup\$

Foo, 6 bytes

&1($i)

Input is hardcoded as the second character, since Foo doesn't have STDIN input. Don't we agree that Foo is awesome now? :)

Explanation

&1          Set current cell to 1
  (  )      Do-while loop (or, at least according to the interpreter)
   $i       Print current cell as int
\$\endgroup\$
1
  • 2
    \$\begingroup\$ I always liked Foo. \$\endgroup\$ Commented Nov 3, 2015 at 16:48
8
\$\begingroup\$

Perl, 18 + 1 = 19 13 + 1 = 14 bytes

print while$_

Run like this:

echo -n NUM | perl -p truth.pl

Thanks to ThisSuitIsBlackNot (who is way better at Perl golfing than me) for golfing off five bytes.

\$\endgroup\$
6
  • 2
    \$\begingroup\$ Statement modifiers are your friend! Also, if you ensure that the input has no trailing newline, you can drop the +0: echo -n 0 | perl -pe'print while$_' (13 bytes + 1 for -p). perl -M5.010 -pe'say while$_' would be even shorter, but that results in inconsistent newlines between 0 vs. 1. \$\endgroup\$ Commented Nov 4, 2015 at 4:46
  • \$\begingroup\$ @ThisSuitIsBlackNot Ah-ha! I tried print while$_ but I couldn't figure out why it didn't work. I didn't realize you couldn't have the trailing newline on the input. \$\endgroup\$ Commented Nov 4, 2015 at 4:47
  • \$\begingroup\$ Yep, the string 0 is false but 0 + newline is true. See perldoc perlsyn. \$\endgroup\$ Commented Nov 4, 2015 at 4:52
  • 2
    \$\begingroup\$ say is shorter, even if you count -E as an extra byte. \$\endgroup\$
    – Dennis
    Commented Nov 4, 2015 at 5:26
  • 2
    \$\begingroup\$ @Dennis ...which I just realized can be fixed with -l: perl -lpE 'say while$_' (11 bytes + 2 for -lp). \$\endgroup\$ Commented Nov 4, 2015 at 14:25
1
2 3 4 5
17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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