161
\$\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\$
18
  • \$\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\$ Nov 3 '15 at 17:38
  • 4
    \$\begingroup\$ Catalog is borked. \$\endgroup\$ Nov 6 '15 at 15:18
  • 2
    \$\begingroup\$ Catalog appears to consider Bf and bf to be different languages. \$\endgroup\$ Nov 10 '15 at 1:13

436 Answers 436

1 2
3
4 5
15
4
\$\begingroup\$

Befunge-98, 16 bytes

&>:;#,1';#<_'0,@

Tested in pyfunge and BeQunge.

Simpler two-line version

&>:! |
@^,1']'0,

I like the previous one more, but this is what I came up with first.

\$\endgroup\$
6
  • \$\begingroup\$ I'm not 100% sure on my Befunge skills, but &:.jq>:.< appears to work, and is 9 bytes. \$\endgroup\$
    – user45941
    Nov 3 '15 at 19:07
  • \$\begingroup\$ @Mego Damn. :-P \$\endgroup\$ Nov 3 '15 at 19:08
  • \$\begingroup\$ Whoops, looks like I missed a char. &::.jq>:.< for 10. \$\endgroup\$
    – user45941
    Nov 3 '15 at 19:11
  • \$\begingroup\$ As @ThomasKwa pointed out in chat, &::.jq# works and is 7. \$\endgroup\$
    – user45941
    Nov 6 '15 at 19:04
  • \$\begingroup\$ @Mego I'm not going to steal that. I'll let the inventor(s) post it. \$\endgroup\$ Nov 6 '15 at 19:08
4
\$\begingroup\$

Prolog, 28 bytes

a(X):-write(X),X=0,!;a(X).

The cut ! is necessary to terminate the execution in the interpreter, otherwise it will wait to see if the user wants to get other answers.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ No need for the extra parentheses! Saves 2 bytes. \$\endgroup\$
    – mat
    Jan 4 '16 at 13:41
  • 1
    \$\begingroup\$ @mat true. Not sure what I was thinking! \$\endgroup\$
    – Fatalize
    Jan 4 '16 at 13:41
4
\$\begingroup\$

Turing Machine Code, 19 bytes

0 0 * * 1
0 * 1 r 0

Halts on 0 because there is no state 1.

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

Shakespeare Programming Language, 189 bytes

.
Ajax,.
Ford,.
Act I:.
Scene I:.
[Enter Ajax and Ford]
Ford:
Listen to thy heart.
Scene II:.
Ford:
Open thy heart.Is cat as big as you?If so, let us return to scene II.
[Exeunt]

Ungolfed:

The Construction of a Truth-Machine in Denmark.

Hamlet, the input.
Ophelia, who orders him around.

Act I: A truth-machine.

Scene I: In which Hamlet learns that all he needs, he can find in his heart.

[Enter Hamlet and Ophelia]

Ophelia:
  Listen to thy heart.

Scene II: In which Ophelia proclaims her doubts about Hamlet.

Ophelia:
  Open thy heart. Is my lover as fair as thee?
  If so, let us return to scene II.

[Exeunt]

I'm using drsam94's SPL compiler + GCC to compile this.

To test:

$ python splc.py tm.spl > tm.c
$ gcc tm.c -o tm.exe
$ echo 0 | ./tm
0
$ echo 1 | ./tm
1111111111111111111111111111111111111111111111...
\$\endgroup\$
2
  • \$\begingroup\$ Do you have the link for the Python implementation of SPL? looking to work on a JavaScript fork of it... \$\endgroup\$ Aug 30 '16 at 23:03
  • \$\begingroup\$ @WallyWest Here it is! \$\endgroup\$
    – Copper
    Aug 30 '16 at 23:07
4
\$\begingroup\$

Japt, 4 bytes

ÿ ©ß

As of 25 Oct 2016, I have implemented the recursion feature ß, which calls the entire program as a function. This is used here like so:

      // Implicit: U = input integer
ÿ     // Since there's no value to work on, use U here. Alert U and return it.
  ©   // If U is truthy (1),
   ß  //   run the program again with the same inputs.

Test it online!

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Yay! We should hold competitions between Japt, 𝔼𝕊𝕄𝕚𝕟, and Teascript to see which is the most effective JS-based lang. \$\endgroup\$ Nov 4 '15 at 3:10
  • \$\begingroup\$ @ןnɟuɐɯɹɐןoɯ That sounds great! But let's have at least another week to develop the langs; I've only worked on the Japt interpreter for ~8 hours and gotten ~2/3 of the features (all the easy ones) done. :-) \$\endgroup\$ Nov 4 '15 at 3:13
  • \$\begingroup\$ Sure! I could probably implement some improvements, too. \$\endgroup\$ Nov 4 '15 at 3:52
  • \$\begingroup\$ Just curious, is there a shorter way to do this in newer Japt versions? \$\endgroup\$
    – FlipTack
    Dec 22 '16 at 13:24
  • 1
    \$\begingroup\$ @Flp.Tkc Actually, it can be Uÿ ©ß because ß implicitly uses the inputs as arguments. Thanks ;-) \$\endgroup\$ Dec 22 '16 at 14:05
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\$

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\$
1
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\$
0
4
\$\begingroup\$

Red, 28 bytes

func[a][until[prin a a = 0]]

Try it online!

Makes use of the fact that until will always execute its block at least once. The loop will only terminate if the argument passed to the function is 0, otherwise it will keep printing forever.

\$\endgroup\$
2
  • \$\begingroup\$ The loop will also terminate if you pass 0.0, 0%, $0, #"^(null)", 0:0, because it relies on the lax comparison. There's also ask for taking input from STDIN. \$\endgroup\$
    – 9214
    Jun 1 at 17:00
  • \$\begingroup\$ is there a consensus on how red/rebol function submissions should be made? this answer only seems to have the body. \$\endgroup\$
    – Razetime
    Jun 5 at 4:59
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\$
2
  • \$\begingroup\$ One-liner (also 35 byte): main=interact(\x->[1,read x..1]>>x) \$\endgroup\$
    – Laikoni
    Feb 28 '18 at 11:55
  • \$\begingroup\$ main=interact(\[c]->[c,'1'..c]) is 31 bytes. \$\endgroup\$
    – Lynn
    Sep 30 '20 at 23:24
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\$
1
  • \$\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\$

PoGo, 10 bytes

ifpouftogo

Explanation:

  • if - accept numerical input and place the result into the current memory cell
  • po - add current position in code to the top of the po stack
  • uf - output the value in the current memory cell as a number
  • to - execute the following command only if the value in the current memory cell is >0
  • go - pop the most recent po location off the stack and jump there

The "po" stack is a call stack used for flow control.

The program in pseudo code:

read int x
do:
    print x
while x > 0
\$\endgroup\$
3
\$\begingroup\$

Labyrinth, 6 bytes

?|:!:/

In the case of a 0 input, this terminates with an error. For a beautiful solution which exits cleanly, see Sp3000's answer.

Since the code is linear, the instruction pointer will move back and forth on the code (it will turn around when hitting a dead end, executing the instruction at the end only once). So what is happening?

?  Read the input as an integer.
|  Compute the bitwise OR of the top two stack elements (there is an infinite supply of
   zeroes at the bottom). This is a no-op at this point.
:  Duplicate the input.
!  Print it as an integer.
:  Duplicate the input.
/  Divide the input by itself. If the input was 0, the interpreter will throw an error,
   polluting STDERR, but we can ignore that. STDOUT remains unchanged. If the input was
   1, then 1/1 just yields 1 again and execution continues leftwards.
:  Duplicate the 1.
!  Print it.
:  Duplicate the 1.
|  Bitwise OR between 1 and 1 gives 1.
?  Try reading another integer. But we're at EOF, so this pushes 0.
   We're in a dead end, so the IP turns around and moves back to the right.
|  Bitwise OR between 1 and 0 gives 1.
   At this point, the state is exactly the same, as the first time we hit |, so from here
   on it's an infinite loop, printing two 1s per iteration.
\$\endgroup\$
3
\$\begingroup\$

Haystack, 15 12 bytes

0io=v
  ^1?|

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

\$\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\$

COMMAND.COM, 12 + 10 + 11 = 33 bytes

0.BAT:

@ECHO 0
@EXIT

1.BAT:

@ECHO 1
@1

Start COMMAND.COM with the above two files in the current directory. Then when it requests input, type either 0 or 1. Also works with CMD.EXE.

If you don't want the Microsoft version and copyright then you can use CMD /K ECHO OFF instead. I've therefore added 11 bytes for this, but subtracted 4 bytes, as you no longer need the @s at the start of each line.

If command-line arguments are acceptable and you are allowed use COMMAND /C 0 or COMMAND /C 1 then you can remove the @EXIT from 0.BAT. In that case the size is 7 + 11 + 1 + 1 = 20 bytes.

\$\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\$
2
  • \$\begingroup\$ See this line for an explanation of the bug behavior. \$\endgroup\$ 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\$ Nov 4 '15 at 1:22
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\$

𝔼𝕊𝕄𝕚𝕟, 6 chars / 11 bytes

↻ôï|ï;

Try it here (Firefox only).

\$\endgroup\$
3
  • 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\$ 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\$
0
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\$
1
  • \$\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\$ Jan 22 '19 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\$

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\$
1 2
3
4 5
15

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.