148
\$\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\$
  • \$\begingroup\$ Can we assume that the program halts when the processor finishes executing the written code, for a machine code entry? \$\endgroup\$ – lirtosiast Nov 3 '15 at 16:58
  • 3
    \$\begingroup\$ Assuming any behaviour is fine for all invalid inputs? \$\endgroup\$ – Cruncher Nov 3 '15 at 17:33
  • 3
    \$\begingroup\$ @Cruncher Yes, the only inputs you should expect to get are 0 and 1. \$\endgroup\$ – a spaghetto Nov 3 '15 at 17:38
  • 4
    \$\begingroup\$ Catalog is borked. \$\endgroup\$ – Addison Crump Nov 6 '15 at 15:18
  • 2
    \$\begingroup\$ Catalog appears to consider Bf and bf to be different languages. \$\endgroup\$ – Mooing Duck Nov 10 '15 at 1:13

376 Answers 376

4
\$\begingroup\$

HP48's RPL, 22.5 bytes

« WHILE DUP REPEAT DUP END »

Since there is no such thing as STDIN or STDOUT on the HP48, the input is taken on the stack, and one "0" or an infinity of "1"s are pushed back on the stack.

If you try it, you will have to kill the program in order to see the "1"s since the stack is not refreshed while the program is running (Just press the "ON" button).

PS: The HP48's memory is made of 4 bits words, hence the non-integer bytes size

\$\endgroup\$
4
\$\begingroup\$

Retina, 9 7 bytes

/1/+>G`

Try it online!

Explanation

The stage G` itself is really a no-op (it's a Grep stage with an empty regex, which always matches). So it's all in the configuration. > prints the result of this stage (which is just the input) and /1/+ wraps it in a loop which runs as long as the string contains a 1. There's also implicit output at the end of the program. So we go through these two possibilities:

  • If the input is 0, the /1/ condition fails, so the loop is never run. Instead, the program terminates, and the 0 is printed at the end.
  • If the input is 1, the /1/ condition matches, so the loop gets executed. The loop iteration itself does nothing but print that 1, so the string's value won't change and the loop will continue indefinitely.
\$\endgroup\$
4
\$\begingroup\$

Brachylog, 4 bytes

Thanks to Fatalize for saving 1 byte.

w?1↰

Try it online!

Explanation

w     Write the input to STDOUT.
 ?1   Check whether the input equals 1.
   ↰  If so, recursively call the main predicate with 1 again.
\$\endgroup\$
  • \$\begingroup\$ What a pity that w's output isn't its input. \$\endgroup\$ – Erik the Outgolfer Feb 28 '18 at 20:14
4
\$\begingroup\$

PUBERTY, 369 bytes

It is May 1, 2018, 3:01:04 PM.Y is in his bed, bored.His secret kink is J.Soon the following sounds become audible.oh yeah yeah yeah hrg fap yeah yeah yeah fap yeah fap yeah yeah mmf yeah yeah yeah hrg yeah hrg fap yeah yeah yeah yeah fap yeah fap yeah mmf yeah yeah yeah yeah yeah yes yeah yeah yeah yeah yeah hrg fap yeah fap yeah fap yeah yeah yeah yeah mmf yeah mmf

Ungolfed

It is May 1, 2018, 3:01:04 PM.
Yhprum is in his bed, bored.
His secret kink is humaninteraction.
Soon the following sounds become audible.

oh yeah yeah yeah
hrg
    fap yeah yeah yeah fap yeah fap yeah yeah
mmf

yeah yeah yeah

hrg
    yeah
    hrg
       fap yeah yeah yeah yeah fap yeah fap yeah
    mmf
    yeah yeah yeah yeah yeah

    yes

    yeah yeah yeah yeah yeah
    hrg
        fap yeah fap yeah fap yeah yeah yeah yeah
    mmf
    yeah
mmf

This was very much harder than I expected it to be using this language.

Explanation

PUBERTY is a wonderful language. It has 6 registers (A, B, C, D, E, F) and one register pointer, all initialized to 0. At the end of each instruction, REGPTR %= 6 and REG[REGPTR] %= 256.

These are the commands used in this program:

  • oh reads an ASCII character and stores its value into the current register
  • yeah increments REGPTR by 1
  • hrg...mmf loops until the current register has a value of zero
  • fap increments the current register by 1
  • yes prints the ASCII char corresponding to the value of the current register

The program starts with the header - the first four lines

It is May 1, 2018, 3:01:04 PM.

This sets $D to the Unix timestamp of the date % 256. In this case, we set it to 48. This statement is required

Yhprum is in his bed, bored.

This initializes $C to 6, the number of chars in the name, but we don't use this at all. This statement is required.

His secret kink is humaninteraction.

This line is where you declare all your kinks, if you want to learn about what they do, check out the esolang page since we don't use them here. This statement is required.

Soon the following sounds become audible.

Required line, does nothing.

oh yeah yeah yeah
hrg
    fap yeah yeah yeah fap yeah fap yeah yeah
mmf

yeah yeah yeah

read in a 0 or 1, then loop until $D is zero while incrementing $A and $B. This leaves us with $A containing ASCII value 0 or 1, depending on what was inputted and $B containing 208. Then move REGPTR back to A

hrg
    yeah
    hrg
       fap yeah yeah yeah yeah fap yeah fap yeah
    mmf
    yeah yeah yeah yeah yeah

    yes

In the inner loop, move REGPTR to $B (which has the value 208) and loop until it is zero while incrementing $A and $F. This leaves us with $A containing 48 or 49 (the ASCII codes for 0 or 1) and F containing 48. Then print $A, which will output a 0 or 1 depending on which one was inputted.

    yeah yeah yeah yeah yeah
    hrg
        fap yeah fap yeah fap yeah yeah yeah yeah
    mmf
    yeah
mmf

Now we move REGPTR to $F and loop until that is zero while incrementing $A and $B. This leaves us with $A containing the ASCII value 0 or 1 and $B containing 208, just like it had at the start of the loop. The loop then exits if $A == 0 or loops infinitely if $A == 1.

This is my first codegolf answer so excuse any mistakes I made pls.

\$\endgroup\$
4
\$\begingroup\$

PowerShell, 16 15 bytes

for(;$args){1}0

Try it Online!

Edit:
-1 byte thanks to @AdmBorkBork

\$\endgroup\$
4
\$\begingroup\$

brainfuck (portable), 29 28 bytes

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

Try it online!

(Improved by 1 byte thanks to Jo King, who found a terser way to start the [<<] loop.)

I know that on PPCG it's normally sufficient for an answer to work on one interpreter, but as this is a catalogue, I wanted a demonstration of a brainfuck answer that should work on any interpreter, and which exits without error on input 0. This program makes no assumptions about cell size, EOF behaviour, wrapping, tape extension to the left, etc. It's the shortest brainfuck truth-machine I'm aware of with these properties.

Explanation

>>>,.[[->+<<+>]>-]<+[<<]>[.]
>>>,                            Input a character to the fourth cell
    .                           Output that character
     [           ]              While the current cell is nonzero:
      [->+<<+>]                   Move the value to the next and previous cells
               >                  Make the next cell current
                -                 and decrement it
                  <+            Starting behind the current cell, at value 1
                    [<<]        Move back two cells at a time until we find zero
                        >[ ]    If the cell to the right is nonzero:
                          .       Output it forever

The basic idea here is to create a range on the tape, containing all values from the input's ASCII code down to 0. (So for example, if the input is 0, we get 48 in the third cell, 47 in the fourth cell, 46 in the fifth cell, etc..) Once we've done that, we look at alternate values of the range until we end up at a tape element before the start of the range. If the range has an even length (i.e. the input has an even ASCII code), we'll end up two cells to the left of it, so moving to the right we'll end up in a cell we've never written to (and thus still has the value zero). If the range has an odd length, we'll end up only one cell to its left, so >[.] will move to the first cell of the range (i.e. the user input) and output it in a loop forever.

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

AppleScript, 93 Bytes

...this verbosity astounds me.

set a to(display dialog""default answer"")'s text returned
repeat while a="1"
log 1
end
log 0
\$\endgroup\$
3
\$\begingroup\$

Haskell, 38 35 bytes

main=interact x
x"1"=cycle"1"
x a=a

The input must not be terminated by a newline. This works for me: echo -n 1 | ./truth-machine.

Edit: thanks @Zgarb for 3 bytes.

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

CJam, 8 bytes

q~{_o}h;

There's no point in linking to the online interpreter, because that one doesn't like infinite loops.

This one works as well, printing newlines:

q~{_p}h;

Explanation

q~   e# Read and evaluate input.
{    e# While the top of the stack is truthy (i.e. 1.).
  _o e# Print a copy of the value on the stack.
}h
;    e# We only get here if the value was 0. If so, discard the other 0 on the stack.
\$\endgroup\$
3
\$\begingroup\$

TI-BASIC, 8 bytes

There are two programs that achieve 8 bytes:

Repeat not(Ans
Disp Ans
End

Repeat is TI-BASIC's do-until loop, so it doesn't check the condition the first time. The other way is recursion (name the program prgmT):

Disp Ans
If Ans
prgmT

Both take input from Ans; call using 0:prgmT or 1:prgmT.

\$\endgroup\$
  • \$\begingroup\$ TIL the TI-84 doesn't have tail-call optimization for recursive programs. :( \$\endgroup\$ – Jakob May 25 '18 at 21:30
3
\$\begingroup\$

Minkolang, 7 bytes

nd$,N?.

Try it here. (DON'T click Run!)

Explanation

n     Take integer from input
d     Duplicate
$,    0 if 0, 1 otherwise
N     Output as integer
?.    Halt if 0, continue otherwise

This works because n pushes -1 if the input is empty...which is truthy! Also, Minkolang is toroidal so when the program counter moves off the right edge, it wraps around to the left edge and continues.

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

Mouse, 16 bytes

?0=[0!$](1^1!)$

Ungolfed:

? 0 = [           ~ Read a number from STDIN and test it for equality with 0
  0 ! $           ~ If equal, print 0 and exit
]
( 1 ^             ~ While true,
  1 !             ~ Print 1
)$                ~ End of program
\$\endgroup\$
3
\$\begingroup\$

Haystack, 15 12 bytes

0io=v
  ^1?|

Still working on a oneliner (if it's possible).

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

C, 35 chars

main(c){for(gets(&c);c%puts(&c););}

This is even hackier than cbojar's solution, from which I copied the abuse of the parameter c (int used as char[4]), along with the reliance on little-endian.

puts returns a non-negatve number on success, which (on my Linux/gcc4.8.2) happens to be the number of bytes printed, which happens to be 2. c%2 tests if c is odd, which is true for '1' and false for '0'.

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

Squirrel, 48 bytes

local a=stdin.readn('b')-48;do print(a) while(a)
\$\endgroup\$
3
\$\begingroup\$

Quipu, 20 bytes

\/1&
/\/\
1&??
>>
::
\$\endgroup\$
3
\$\begingroup\$

TeaScript, 21 16 bytes

TeaScript is JavaScript for golfing, created by user Vɪʜᴀɴ.

for(;alert×|x;);

The input is automatically stored in variable x. × (U+00D7 Multiplication Sign) is a shortcut for (x).

Try it in the online interpreter

\$\endgroup\$
  • \$\begingroup\$ See this line for an explanation of the bug behavior. \$\endgroup\$ – Mama Fun Roll Nov 4 '15 at 0:27
  • \$\begingroup\$ @ןnɟuɐɯɹɐןoɯ Ah, yes. That explains why whil(x) did the same thing, but not whi(x). Thanks! \$\endgroup\$ – ETHproductions Nov 4 '15 at 1:22
3
\$\begingroup\$

O, 14 bytes

i{1{1o1}w}{0o}?

O is a work-in-progress language with loads of commands and an interpreter written in "APL-style C", which means incomprehensible code.

i Get input as String

{ Start a CodeBlock (like ruby)

1 Push 1 to the stack

{ Start a CodeBlock

1 Push 1 to the stack

o Pop the stack and print it

1 Push 1 to the stack

} Push the CodeBlock to the stack

w Do the CodeBlock on the top of the stack while the value under it is true. (Pops them both.)

} Push the CodeBlock to the stack

{ Start a CodeBlock

0 Push 0 to the stack

o Pop the stack and print it

} Push the CodeBlock to the stack

? If the 3rd down value in the stack is truthy, do the CodeBlock 2nd down in the stack, otherwise do the CodeBlock on the top. (Pops the first 3 values on the stack.)

\$\endgroup\$
  • \$\begingroup\$ "APL-style C" - you mean nightmares? \$\endgroup\$ – Mego Nov 15 '15 at 5:07
  • \$\begingroup\$ @Mego yep, pretty much \$\endgroup\$ – Hipe99 Nov 15 '15 at 5:14
  • \$\begingroup\$ I think you're being unfair to APL. \$\endgroup\$ – lirtosiast Nov 16 '15 at 1:20
  • \$\begingroup\$ @ThomasKwa it's a direct quote. \$\endgroup\$ – Hipe99 Nov 16 '15 at 19:41
  • \$\begingroup\$ @Hipe that is horrible. must it be golfed? \$\endgroup\$ – cat Jul 22 '16 at 11:18
3
\$\begingroup\$

O, 12 11 6 bytes

j{.o}w

When 0 is inputted, 0 is outputted and the program ends. When 1 is inputted, 1 is outputted forever.

Explanation:

j     Get input as Number
{  }w While the input is 1
 .o    Print the 1
      Print the stack when code ends, which will only contain 0
\$\endgroup\$
3
\$\begingroup\$

Binary-Encoded Golfical, 11+1 (-x flag)= 12 bytes

Hexdump of binary encoding:

00 40 02 15 14 1B 1A 17 14 24 1D

Original image:

enter image description here

Magnified 125x, with color labels:

enter image description here

Rough translation:

*p=readnum
lbl A
print *p
if *p!=0 goto A
\$\endgroup\$
3
\$\begingroup\$

Turing Machine Code, 19 bytes

0 0 * * 1
0 * 1 r 0

Halts on 0 because there is no state 1.

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

𝔼𝕊𝕄𝕚𝕟, 6 chars / 11 bytes

↻ôï|ï;

Try it here (Firefox only).

\$\endgroup\$
  • 2
    \$\begingroup\$ Is the language name supposed to be "ESMin", or just five boxes? \$\endgroup\$ – mbomb007 Nov 4 '15 at 17:01
  • 1
    \$\begingroup\$ ESMin in double-struck. It doesn't show up properly in some fonts, though... :( \$\endgroup\$ – Mama Fun Roll Nov 4 '15 at 17:53
  • 1
    \$\begingroup\$ Ah, okay. I can only see the double-struck letters ℂ, ℍ, ℕ, ℙ, ℚ, ℝ, and ℤ. \$\endgroup\$ – mbomb007 Nov 4 '15 at 22:03
3
\$\begingroup\$

Mathematica, 36 33 bytes

For[Print[i=Input[]],i>0,Print@i]
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 5 bytes

Code:

Di[D?

Explanation:

D      # Duplicate input
 i     # If True (or 1), do
  [    # Infinite loop
   D   # Duplicate top of the stack
    ?  # Pop a, print a with no newline
\$\endgroup\$
  • \$\begingroup\$ Based on the date this was posted I assume implicit input wasn't a thing yet back then, but both D can be removed now to save 2 bytes. \$\endgroup\$ – Kevin Cruijssen Jan 22 at 16:26
3
\$\begingroup\$

Batch, 35 bytes

@IF %1==0 (exit)
:l
@echo 1&goto l

Please, anyone who can golf this more is more than welcome to.

\$\endgroup\$
3
\$\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\$
  • \$\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\$ – Mego Jan 25 '16 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\$ – senegrom Jan 25 '16 at 13:36
  • \$\begingroup\$ Fair enough, I didn't consider -Xss. Upvoted, and welcome to PPCG! \$\endgroup\$ – Mego Jan 25 '16 at 13:37
  • 1
    \$\begingroup\$ @SeanBean "take input from STDIN or an acceptable alternative" - command-line arguments are an acceptable input method. \$\endgroup\$ – Mego Sep 1 '16 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\$ – senegrom Sep 7 '16 at 18:28
3
\$\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\$
  • \$\begingroup\$ such amazing much wow where's rightgoat \$\endgroup\$ – Seadrus Feb 23 '16 at 3:12
  • 1
    \$\begingroup\$ @Seadrus ---I ate him---. I mean, he'll be coming soon \$\endgroup\$ – Chathuahua Feb 23 '16 at 3:12
  • \$\begingroup\$ No he won't, you're the only goat left ;) \$\endgroup\$ – J Atkin Feb 24 '16 at 3:12
3
\$\begingroup\$

Whenever, 72 bytes

From the webpage:

Introduction

Whenever is a programming language which has no sense of urgency. It does things whenever it feels like it, not in any sequence specified by the programmer.

Design Principles

  • Program code lines will always be executed, eventually (unless we decide we don't want them to be), but the order in which they are executed need not bear any resemblance to the order in which they are specified.
  • Variables? We don't even have flow control, we don't need no steenking variables!
  • Data structures? You have got to be kidding.

The official java interpreter doesn't seem to handle read() but the spec says it should work so.

1 -2,2#read();
2 defer(1) again(2) print("1");
3 defer(1||2) print("0");

The program works like this:

  • Initially 1, 2 and 3 are on the list but 2 and 3 must wait until 1 is gone.
  • When 1 is executed it removes 2 and then adds 2 back stdin times. Therefore:
    • 2 is only on the list if stdin was 1.
    • 3 must wait until 2 is gone so it can only execute if stdin was 0.
  • If 2 is executed it will add itself to the list again and print '1'.
  • If 3 is executed (meaning 2 is not on the list) it will print '0'.
  • At this point we will be in one of two states:
    • 2 will be on the list printing '1' and 3 will be perpetually waiting
    • 1, 2 and 3 will all be gone and the program will end.
\$\endgroup\$
3
\$\begingroup\$

R, 16 28 25 bytes

x=scan();while(x)cat(1);0

Edited to read x

\$\endgroup\$
  • \$\begingroup\$ this isn't valid, because the 0 will be printed out with an additional [1] preceding it, and the post states that 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. \$\endgroup\$ – Giuseppe Mar 3 '18 at 15:24
3
\$\begingroup\$

Gaot++, 125 bytes

bleeeeeeeeeeet
bleeeet bleeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeet
bleeeeeeeet

Compressed: 11e4e6e13e13e13e13e9e8e6e

Try it online!

\$\endgroup\$

Your Answer

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

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