172
\$\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
  • 3
    \$\begingroup\$ Assuming any behaviour is fine for all invalid inputs? \$\endgroup\$
    – Cruncher
    Nov 3, 2015 at 17:33
  • 3
    \$\begingroup\$ @Cruncher Yes, the only inputs you should expect to get are 0 and 1. \$\endgroup\$ Nov 3, 2015 at 17:38
  • 5
    \$\begingroup\$ Catalog is borked. \$\endgroup\$ Nov 6, 2015 at 15:18
  • 2
    \$\begingroup\$ Catalog appears to consider Bf and bf to be different languages. \$\endgroup\$ 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
    Apr 26, 2020 at 1:42

494 Answers 494

1
3 4
5
6 7
17
3
\$\begingroup\$

Brain-Flak, 6 bytes

{(())}

While the top of the stack is non-zero, push 1. Input to the stack is implicit, and output would also be, but if the program doesn't halt, nothing is outputted. However, one is continually pushed onto the stack, and it's the closest Brain-Flak can get to infinite output.

Try it online!

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

Perl -p, with the following restrictions ppencode, 15 bytes.

  • Use only keywords with lowercase alphabets only
  • Separate each of them with just a space
print while sin

Try it online!

How it works

  • sin(0) is zero
  • sin(1) is not zero
  • -p is for implicit I/O for line by line

Alternatives

sin can be replaced with one of following keywords:

abs int oct hex
\$\endgroup\$
3
  • \$\begingroup\$ can you do print while-$_? \$\endgroup\$
    – Jo King
    Aug 19, 2021 at 4:50
  • \$\begingroup\$ @JoKing if I had changed the restriction. \$\endgroup\$
    – user100411
    Aug 19, 2021 at 11:51
  • \$\begingroup\$ Oh, i don't know how I missed that oops \$\endgroup\$
    – Jo King
    Aug 19, 2021 at 12:39
3
\$\begingroup\$

Unlambda, 15 bytes

``c``@?1i `c`|i

Try it online!

\$\endgroup\$
2
  • 2
    \$\begingroup\$ This sent me down a bit of a rabbit hole of Unlambda. What a wild language! \$\endgroup\$
    – Mayube
    Oct 26, 2021 at 14:02
  • 1
    \$\begingroup\$ @Mayube mission successful ;) \$\endgroup\$ Oct 27, 2021 at 0:42
3
\$\begingroup\$

ErrLess, 12 10 bytes

Thanks to Aaroneous Miller for saving 2 bytes

q@#@8*1-[.

No newlines/spaces.

Explanation

q     { Input a number a number, `n` }
@#    { Output `n` }
@8*1- { Push `8*n-1` to stack (7 for 1, -1 for 0) }
[     { Jump backwards by that many instructions }
      { Goes to right after input for 7, just before halt for -1 }
.     { Halt }

ErrLess is a stack-based language I made for fun over the last few months. You can read the docs here, and I also started a tutorial.

Try it online!

\$\endgroup\$
6
  • \$\begingroup\$ 10 bytes: q@#@8*1-[. It could be 8 bytes with q@#@5*[., but hitting [ or ] with a 0 goes into an endless loop, since it doesn't move the pointer. Not sure if that is intentional or not. \$\endgroup\$ Oct 26, 2021 at 15:24
  • \$\begingroup\$ Also, this is a really neat looking language! Just so you know, you could check out pythonanywhere.com to host your Python interpreter online. I use it for my languages, and it's also used for Vyxal and Rattle. \$\endgroup\$ Oct 26, 2021 at 15:28
  • \$\begingroup\$ @AaroneousMiller The endless loop thing is intentional, just another edgecase you have to constantly keep track of, or else your program breaks... I'll check out pythonanywhere, thx! \$\endgroup\$
    – Ruan
    Oct 27, 2021 at 13:10
  • \$\begingroup\$ lol, I love it! \$\endgroup\$ Oct 27, 2021 at 13:11
  • \$\begingroup\$ 8 bytes by terminating with an error (lol) q@#@2$]] \$\endgroup\$
    – Jo King
    Nov 1, 2021 at 9:43
3
\$\begingroup\$

Brainfuck, 27 25 23 bytes

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

I ran it here (Uses negative cells, get around this by adding a << to the beginning)

I used modulus 2 instead of subtracting 48 to differentiate 0 and 1 which cuts down some characters. I also copied and did modulus at the same time.

Old answers:

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

,.[->+>+<<]>[-[>>]>[.]<<<-]
\$\endgroup\$
1
  • \$\begingroup\$ Site is no longer available (also, i think you mean adding a >> to the beginning to avoid negative cells). You can save a byte by doing [+.-] instead \$\endgroup\$
    – Jo King
    Dec 16, 2021 at 0:17
3
\$\begingroup\$

StupidStackLanguage, 5 bytes

htxux

Try it online!

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

Plumber, 28 20 bytes

[]
=]]][=[]
  ][=[][

Try it Online!

I figured Plumber could use some love, so I thought I'd give it a try. It's a pretty fun language to work with! There's no online interpreter for it, so the TIO link is to Javascript, with the interpreter in the header, compliments of @RedwolfPrograms.

This simply takes in input, prints it, and if it is non-zero, it keeps printing it forever.

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

K (ngn/k), 13 bytes

{x}{ \x}/.1:0

(Don't) Try it online!

The web interpreter does support stdin (via a popup prompt), and entering a 0 will print a single 0. But entering a 1 will hang the entire tab.

We need an unbounded loop, which means either m m/ or a recursive function. The latter being {x o/ \x}@.1:0 is 1 byte longer than the above.

{x}{ \x}/.1:0  full program
          1:0  read stdin as a single list of bytes (= single string)
         .     eval it
{ }{   }/      while loop:
 x               while the value is truthy,
     \x          debug-print the value (print with newline) and return it unchanged

If the input is 0, the loop runs zero times and the resulting value 0 is implicitly printed. If the input is 1, the loop runs forever, printing 1\n repeatedly.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ an ATO link is useful for showing output: {x}{ \x}/.1:0 \$\endgroup\$
    – Razetime
    Aug 11, 2022 at 10:55
  • \$\begingroup\$ also, {x}( \)/.1:0 seems to work \$\endgroup\$
    – Razetime
    Aug 11, 2022 at 10:56
3
\$\begingroup\$

Piet + ascii-piet, 12 bytes (2×6=12 codels)

tavnsJ dl jj

Try Piet online!

As a grid:

tavnsj
 dl jj

As an image:

There was an existing answer with 12 codels, but I got this independently. Any smaller image size is likely not possible, though ascii-piet encoding allows to omit trailing black cells on each line (which makes the linked answer 11 bytes) and therefore may allow for a bit more optimization.

How it works

If the input is 1:

      InN        [1]
Loop: DP+        []   (rotate right once)
      OutN       []   (stack underflow, ignored)
      Push1      [1]
      Dup        [1 1]
      Goto Loop
      DP+        [1]  (rotate right once)
      OutN       []   (print 1)
      Push1      [1]
      Dup        [1 1]
      Goto Loop ...

If the input is 0:

InN    [0]
DP+    []   (go straight through)
Push1  [1]
Not    [0]
OutN   []   (print 0)
HALT
\$\endgroup\$
2
\$\begingroup\$

Pip, 5 bytes

WaPaa

In pseudocode:

while(a)
    print(a)
autoprint(a)

a is the first command-line argument. (The OP commented on the sandbox post that this was an acceptable way to take input, even though Pip is capable of taking input from stdin.)

\$\endgroup\$
1
  • \$\begingroup\$ WaPaa. I love these weird types of languages because when you put them into TTS programs they have a conniption. \$\endgroup\$
    – Cyoce
    Dec 16, 2015 at 18:29
2
\$\begingroup\$

tinylisp, 36 bytes

This is a language that I'm basing an upcoming challenge on. The spec in the challenge doesn't include the disp function, but the reference implementation does.

(d M(q((x)(i x(i(disp x)0(M x))0))))

Defines a function M that takes an argument x (the closest that the language has to input). If x is falsey, we return 0, which is printed. If x is truthy, we want to display x and then recurse. There isn't any equivalent to Common Lisp's progn in the language, so the best way to do this is to use the disp call as the condition of an if. The result is falsey, thus putting the recursive call (M x) in the else branch.

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

Sisi, 22 bytes

Sisi doesn't have any way to take user input, so the number is expected to be stored in the variable x (presumably on line 1).

2 print x
3 jumpif x 2

Pretty straightforward: print the number, and keep doing so as long as it's 1.

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

Stuck, 9 Bytes

Stuck has a while loop function (which I never added to the docs on Esolangs, but it has existed for a little over 2 months) which makes this possible. It wasn't before this as far as I know :P.

ip"1="'ph
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Dammit I was trying to make a truth machine in Stuck but couldn't figure out how to do it without a while loop \$\endgroup\$ Nov 3, 2015 at 20:15
  • \$\begingroup\$ @quartata Sorry about that :P Whenever I get enough free time I will update the documentation. \$\endgroup\$
    – Kade
    Nov 3, 2015 at 20:20
2
\$\begingroup\$

Beam, 25 23 13 bytes

rSn(`)>@<
H@<

Try it in the online interpreter! (Warning: it may crash your browser with an input other than 0.)

Beam is a 2D language, based on the concept of a beam of light moving through the 2D source code. Beam is oriented around two main memory values: one held by the beam, and one called the "store". Here are the commands used, in order:

  • r - Set the beam to the next ASCII code in the input. (48 for 0, 49 for 1)
  • S - Set the store to the beam.
  • n - If beam != store, point the beam downward. Does nothing the first time.
  • ( and ) - If store != 0, point the beam right/left, respectively.
  • ` - Decrement the store by 1.

Now, the beam enters (`) from the left, and bounces back and forth until the store reaches 0. If the store's initial value is 48 (0), it will exit to the left, traveling through these chars:

  • n - If beam != store, point the beam downward. This time, since the beam is 48 and the store is 0, it does its job.
  • < - Unconditionally point the beam to the left.
  • @ - Output the beam as an ASCII character. Prints 0.
  • H - Halt the program.

However, if the store's initial value is 49 (1), it exits the loop to the right, and runs through this code:

  • > - Unconditionally point the beam to the right.
  • @ - Output the beam as an ASCII character. Prints 1.
  • < - Unconditionally point the beam to the left.
  • @ - Output the beam as an ASCII character. Prints 1.
  • > ...

...and so on until the end of time (or until your browser crashes).

Thanks to @MickyT for this awesome layout!

P.S. If you want to learn more about Beam, check out and vote on this post!

\$\endgroup\$
2
  • \$\begingroup\$ +1 I like it, didn't think I could shorten it, but here's a slightly shorter version. 2 Lines rSn(`)>@< and H@< for 13 \$\endgroup\$
    – MickyT
    Nov 3, 2015 at 22:16
  • \$\begingroup\$ @MickyT Holy cow, that's brilliant! I'll update in a sec \$\endgroup\$ Nov 3, 2015 at 22:18
2
\$\begingroup\$

JavaScript (ES6), 77 73 64 61 bytes

x=prompt()==1;j=a=>{if(x)setTimeout(j,9);console.log(+x)};j()

This program doesn't crash your web browser!

Explanation:

x = prompt() == 1;             // this makes sure input is 1 or not while defining
j = a => {                     // es6 arrow function
  if (x)                        // if x is 1
    setTimeout(j, 9);            // make sure to do this function again in 9ms
  console.log(+x);              // log the number
};
j();                           // call j
\$\endgroup\$
6
  • \$\begingroup\$ Better version: x=prompt()==1;j=()=>{if(x)requestAnimationFrame(j);console.log(x?1:0)};j() \$\endgroup\$ Nov 3, 2015 at 19:53
  • \$\begingroup\$ Even better, replace j=()=> with j=a=> \$\endgroup\$ Nov 3, 2015 at 19:59
  • \$\begingroup\$ Actually, using x=prompt(); is shorter, but you have an x==1?1:0 that could just be x. That leaves x=prompt();j=a=>{if(x==1)requestAnimationFrame(j);console.log(x)};j() at 69 bytes. However, instead of using requestAnimationFrame you could use a setTimeout, which is shorter and leads to x=prompt();j=a=>{if(x==1)setTimeout(j,10);console.log(x)};j() at 69. Oh crap! That would mean that JS beats Stack! D: \$\endgroup\$ Nov 3, 2015 at 20:12
  • \$\begingroup\$ Haha. The reason I use x==1?1:0 is so that if the user inputs "true" it counts as 0. \$\endgroup\$
    – Nebula
    Nov 3, 2015 at 20:50
  • \$\begingroup\$ (oh my, it's liam4! hey!) But you don't need to. The only inputs needed 1 and 0. \$\endgroup\$ Nov 3, 2015 at 21:01
2
\$\begingroup\$

Brainfuck, 54 bytes

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

Explanation:

+++[>++++[>++++<-]<-]>>> Set a register to 48 (ASCII 0), using multiplication to reduce the byte count (3*4*4), then set the pointer to the next instruction

,. Receive and print a line of input

[>+<<[>>-<<-]>>>+<<-]Set the next register to be a numerical value, and the one after to represent the ascii output value

> Move the data pointer to the numerical register

[>.<] While the numerical register is not 0, print the ascii register

\$\endgroup\$
3
  • \$\begingroup\$ I already have a shorter BF program, but just so you know, 48 can be made shorter. See this helpful page. \$\endgroup\$
    – mbomb007
    Nov 3, 2015 at 21:44
  • \$\begingroup\$ Thanks. Yeah, I didn't see your program before I posted mine, must have missed it when scrolling through. \$\endgroup\$
    – Ethan
    Nov 3, 2015 at 22:01
  • \$\begingroup\$ Try running the code snippet contained in the question. \$\endgroup\$
    – mbomb007
    Nov 3, 2015 at 22:12
2
\$\begingroup\$

brainfuck, 20 bytes

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

This requires an interpreter that exits with an error upon stepping out of bounds with < (such as this one). Stepping over the left edge in case of an even value was the easiest way I found to do a parity test. I wouldn't be surprised if it could be a couple of bytes shorter.

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

Batch, 44 bytes

@set/p n=
:a
@echo %n%
@if %n%==1 goto :a

Explanation

  • set /p reads from stdin into a variable
  • :a is a GOTO marker, because batch does not have while loops

The rest should be obvious: output the variable n and if n is 1, repeat.

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

VBA, 54 48 Bytes

Sub f(u):Do:Debug.Print u:Loop While u>0:End Sub

Look Guys, VBA can fit on one line(almost) and be hard(ish) to read like all the other Languages.

Debug.Print could be Msgbox but I feel that isn't the Spirit of the challenge and you really don't want Never ending pop-ups

Old Code

Sub f(u):Do:Debug.Print u:If u=0 Then End
Loop:End Sub
\$\endgroup\$
2
  • \$\begingroup\$ Using ActiveSheet.Range("A1") as your input and running in the Immediate Window, you can reduce to 31 bytes: ?[A1]:Do Until[A1]=0:?[A1]:Loop \$\endgroup\$ May 9, 2018 at 9:40
  • \$\begingroup\$ For sure. Any of my VBA answers are designed not to run in immediate and do not use sheets. VBA can for sure be shortened by using those methods and I encourage you to explore the possibilities. But at the time there were few to no VBA responses so I limited myself to Subs only. \$\endgroup\$
    – JimmyJazzx
    May 9, 2018 at 10:15
2
\$\begingroup\$

FORTH, 44 bytes 39 bytes 31 bytes

Edit:

As suggested by @Nate Eldredge, we can shorten the code, if we allow extra spaces in the output. This program is 31 bytes long:

: P BEGIN DUP . ?DUP 0= UNTIL ;

Sample run:

1 P
0 P

First version:

: P BEGIN DUP 48 + EMIT ?DUP 0= UNTIL ;

Sample run:

1 P
0 P

Explanation:

We expect the value 'b' of 0 or 1 on the stack.

: P       -- beginning a word P                          ( b ) 
BEGIN     -- starting a loop                             ( b )
DUP 48 +  -- creating an ASCII code for the character    ( b  b+48 )
EMIT      -- echoing the character                       ( b )
?DUP      -- dup'ing the value if non-zero               ( 1  1 ) or ( 0 )
0=        -- testing if the value is zero                ( 1 FALSE) or ( TRUE )
UNTIL     -- end of the loop if true                     ( 1 ) or ( - )
;         -- finishing the word

If I take the challenge seriously, FORTH has Standard I/O capabilities, but it is natural in FORTH to take the input from the stack.

If I use the STDIO feature, the code looks like this (44 bytes)

: P KEY BEGIN DUP EMIT DUP 48 = UNTIL DROP ;

Sample run:

P

(Note, that in my environment the standard input was buggy)

\$\endgroup\$
2
  • 2
    \$\begingroup\$ My FORTH is rusty, but wouldn't it be easier and shorter to use . instead of 48 + EMIT? \$\endgroup\$ Nov 5, 2015 at 19:45
  • \$\begingroup\$ @NateEldredge . puts an extra space after the number, otherwise it's OK. I've read in some answers that it may be acceptable. If that's the case we can shorten the code. I'll update the answer. \$\endgroup\$
    – gaborsch
    Nov 5, 2015 at 23:12
2
\$\begingroup\$

MIPS asm, 24 bytes

main:
li $v0, 5  # load read int
syscall  # exec read int, stores value in $v0
move $a0, $v0  # store in $a0
li $v0, 1  # load print int
loop:
syscall  # print $a0
bgtz $a0, loop  # loop while $a0 is greater than zero

Had to learn MIPS recently, might as well do something fun with it.

\$\endgroup\$
2
\$\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\$
2
\$\begingroup\$

Marbelous, 23

This version doesn't terminate after the zero is printed, but that should be alright:

..}0
../\//
>0
}0
+O
+O

Old version:

}0@0
\\
../\+O
>0\/+O
@0

It doesn't add a newline between each 1, but whatevs.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ You need to terminate if your language is at all capable of terminating. \$\endgroup\$
    – lirtosiast
    Nov 18, 2015 at 3:31
2
\$\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\$
5
  • \$\begingroup\$ "APL-style C" - you mean nightmares? \$\endgroup\$
    – user45941
    Nov 15, 2015 at 5:07
  • \$\begingroup\$ @Mego yep, pretty much \$\endgroup\$
    – Hipe99
    Nov 15, 2015 at 5:14
  • \$\begingroup\$ I think you're being unfair to APL. \$\endgroup\$
    – lirtosiast
    Nov 16, 2015 at 1:20
  • \$\begingroup\$ @ThomasKwa it's a direct quote. \$\endgroup\$
    – Hipe99
    Nov 16, 2015 at 19:41
  • \$\begingroup\$ @Hipe that is horrible. must it be golfed? \$\endgroup\$
    – cat
    Jul 22, 2016 at 11:18
2
\$\begingroup\$

Python 2- 64 bytes

x=input()
if x==0:print"0"
elif x==1:
 while True: print"1"
\$\endgroup\$
1
  • \$\begingroup\$ A trick you can exploit in Python is that 0 is the same as False and anything but 0, including 1, is True. This generally holds in most programming languages \$\endgroup\$
    – bioweasel
    Nov 1, 2016 at 20:00
2
\$\begingroup\$

Java, 87 bytes

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

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

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

Detour, 2 bytes

,~

Try it online!

, will print a value then push it to the next cell.

~ is a filter, so it will push a value IFF it is greater than 0.

Cells wrap around the edges.

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

HALT, 49 bytes

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

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

Online interpreter (Firefox only)

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

Shtriped, 33 bytes

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

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

Explanation:

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

BASTARD, 83 bytes

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

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

Explanation:

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

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

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

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

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Programming Puzzles and Code Golf Stack Exchange. This is a great first answer, +1. Your language looks interesting; once you've got enough reputation you could get help developing it on Chat. \$\endgroup\$
    – wizzwizz4
    Feb 19, 2016 at 15:05
1
3 4
5
6 7
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.