139
\$\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\$ – quartata Nov 3 '15 at 17:38
  • 3
    \$\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

351 Answers 351

1
\$\begingroup\$

><>, 6 Bytes

::n?!;

Input is assumed to be on the stack. It's duplicated twice, printed, and checked if it's non-zero. If it's non-zero, skip the end program command and loop around.

Note that this does not print any spacing between the 1s.

\$\endgroup\$
1
\$\begingroup\$

Husk, 5 bytes

¶?∞;I

Try it online!

Explanation

 ?  I  -- if the input is truthy
  ∞    --   repeat it infinitly many times
   ;   --   else create singleton list
¶      -- join by newlines

Thanks @H.PWiz for golfing off 1 byte!

\$\endgroup\$
  • 1
    \$\begingroup\$ 5 bytes: ¶?∞;± or, if string input is valid: ?∞;i \$\endgroup\$ – H.PWiz Nov 21 '17 at 21:06
1
\$\begingroup\$

GolfScript - 13 bytes

~{.}{.p}while

Basically a

while(arg){
    print(arg)
}
print(arg)

GolfScript doesn't have a real-time STDOUT, everything is printed from the stack to the console at the end of the execution, it has to be stopped manually.

\$\endgroup\$
1
\$\begingroup\$

Evil, 74 bytes

fjzaeeeaeeawbmxruuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuusbaeeeaeew

A program that will request for a character of input. Every lowercase letter corresponds to a different instruction. Here's an analysis.

f: goes Forward in the program and searches for the closest marking character, or m. This skips all of the code that will continuously output 1 to stdout.

jzaeeeaeeawb: Continuously output 1 to stdout. The character b searches Backwards for the marking character. However, at this point the marking mode is set to 'alternate', so instead of searching for m, it's searching j, which is at the beggining. The random amount of es with a and z set the counter, or accumulator, to the ASCII representation of 1. w would do what you might think: Write the value of the accumulator to stdout.

mxr: This is executed right after f. The marking character has now been found, and we continue with x, which switches the marking mode from 'standard' (m) to 'alternate' (j). Then, r Reads stdin for a character and sets the accumulator to the ASCII representation of the input, which would be either 48 for 0 or 49 for 1.

uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuusb: Each u decrements the accumulator. The whole operation brings the accumulator down from 48 to 0 or 49 to 1. This is crucial for the following command; the letter s will Skip the next command only if the value of the accumulator is 0. That next command searches backwards for j, which goes all the way back to outputting 1 to stdout. Note that I could probably shorten the amount of bytes here by replacing some us with es, which weave the accumulator.

aeeeaeew: Now, if the accumulator had hit 0, this snippet puts the accumulator back to 48, or 0, and w Writes the accumulator value to stdout.

Original interpreter in Java: http://web.archive.org/web/20070906133127/http://www1.pacific.edu/~twrensch/evil/evil.java

\$\endgroup\$
1
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 38 bytes

	N =INPUT
L	OUTPUT =N
	GT(N) :S(L)
END

Try it online!

	N =INPUT	;* read input as n
L	OUTPUT =N	;* print input
	GT(N) :S(L)	;* if n > 0, goto L
END
\$\endgroup\$
1
\$\begingroup\$

Acc!!, 39 37 bytes

N
Count i while _%2-i%2+1 {
Write _
}

Try it online!

This takes input through N, then prints the input _ until the equation _%2-i%2+1 is 0. This looks like:

48
  48%2-0%2+1 => 1
  48%2-1%2+1 => 0
  48%2-2%2+1 => 1
  48%2-3%2+1 => 0
49
  49%2-0%2+1 => 2
  49%2-1%2+1 => 1
  49%2-2%2+1 => 2
  49%2-3%2+1 => 1

This is shorter than the easy approach (39 bytes):

N
Write _
Count i while _%2 {
Write _
}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

AWK, 20 bytes

{do{print}while($0)}

This is the first thing I came up with. I tried to come up with something clever more clever but they were all longer.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

C (gcc) , 42 bytes

main(t){gets(&t);do puts(&t);while(t-48);}

Try it online

\$\endgroup\$
1
\$\begingroup\$

Wumpus, 6 bytes

Iv=O=:

Try it online!

Explanation

In Wumpus, the IP gets reflected off the program boundary (instead of wrapping around or terminating). Since there is no redirecting control flow in this program, the IP simply bounces back and forth, executing a loop with loop body

Iv=O=:=O=v

Let's go through this:

I   Read an integer N from STDIN. On subsequent iterations, this will push a zero.
v   Bitwise OR. On the first iteration this ORs the input with an implicit zero
    which does nothing. On subsequent iterations, this gets rid of the zero that
    was just pushed.
=   Duplicate the input.
O   Print it to STDOUT.
=   Duplicate it again.
:   Compute N/N. For input 0, this ends the program, due to the attempted division
    by zero. For input 1, this just gives back 1.
=   Duplicate the input.
O   Print it to STDOUT.
=   Duplicate the input.
v   Bitwise OR. Just gets rid of one copy of the input.
\$\endgroup\$
1
\$\begingroup\$

Stax, 5 4 3 bytes

Crossed out 4 is still 4 ;(

wQc

Try it at staxlang.xyz!

 w      Until popping results in a falsy value:
  Q       Peek and print with a newline.
   c      Copy the value atop the stack.

I'm loving this new language.

Thanks to @Weijun Zhou for reminding me of implicit input.

\$\endgroup\$
  • \$\begingroup\$ I am glad to find another user of Stax writing impressive answers. Maybe you should check out the chat as well although there are not much to see at the moment. \$\endgroup\$ – Weijun Zhou Mar 3 '18 at 20:57
  • \$\begingroup\$ You don't need the comma at the beginning. There is implicit input. \$\endgroup\$ – Weijun Zhou Mar 3 '18 at 21:03
  • \$\begingroup\$ Also I suggest you use this link: staxlang.xyz/#c=wQc&i=0%0A1&a=1&m=2. It automatically runs your program. \$\endgroup\$ – Weijun Zhou Mar 3 '18 at 21:14
  • \$\begingroup\$ @WeijunZhou Whoops, thanks! \$\endgroup\$ – Khuldraeseth na'Barya Mar 3 '18 at 21:14
1
\$\begingroup\$

Ruby, 16 bytes

uses the -n flag

p 1while~/1/;p 0

~/1/ matches the last line of input to the regular expression /1/

Try it online!

\$\endgroup\$
  • \$\begingroup\$ you don't have to count flags any longer; just note in the body which one you've used (as you already have done) \$\endgroup\$ – Giuseppe Mar 5 '18 at 23:14
  • \$\begingroup\$ @Giuseppe thanks, is this the consensus opinion now? \$\endgroup\$ – Asone Tuhid Mar 5 '18 at 23:16
  • \$\begingroup\$ Yeah, see here. \$\endgroup\$ – Giuseppe Mar 5 '18 at 23:18
  • \$\begingroup\$ @Giuseppe so should I call it Ruby + -n? \$\endgroup\$ – Asone Tuhid Mar 5 '18 at 23:28
1
\$\begingroup\$

ShinyLisp, 22 bytes

+:Ge _&^:Pu~:I:P^~N:Qx

I figure now is as good a time as any to introduce my new golfing language. It's still largely a work in progress, but it's usable.

Ungolfed:

(= (gets))
(loop '% (puts) (cond (p %) () (quit)))

Explanation:

(= (gets))       -- Reads a line of user input and assigns it %
(loop '% ...)    -- Loop forever using % as the (constant) loop value
(puts)           -- Print the value of %
(cond (p %) ...) -- If % (treated as a number) is nonzero then...
()               -- Do nothing
(quit)           -- Else exit the program
\$\endgroup\$
1
\$\begingroup\$

Linotte, 52 bytes

a:
e est un nombre
début
demande e
e!
tant que e,e!

Linotte is a french programming language aimed at beginners. Translated into English:

a:
e is a number
start
ask for e
e!
while e, e!

e! is shorthand for affiche e, which means "display e".

You can find a download here.

\$\endgroup\$
1
\$\begingroup\$

Fortran (GFortran), 42 bytes

READ*,I
DO
PRINT*,I
IF(I==0)EXIT
ENDDO
END

Try it online!

\$\endgroup\$
1
\$\begingroup\$

brainfuck, 25 bytes

Note: This is a different "language" than this answer, because it requires a brainfuck variant that exits when the memory pointer is moved left of the initial position, whereas this needs a brainfuck variant that can read and write left of the initial position.

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

Try it Online!

Explanation

,.             Read and print a character.
[[<+>->+<]>-]  Write the range from the code point of the character down to one.
<+[<<]>        Go to the first element in the sequence if the length is odd, otherwise
                go to the cell before.
[.]            Print the value at the pointer forever if the input is odd, determined by
                if the pointer is on or outside the sequence of numbers in memory.

Here are two other interesting solutions i found, which may be golfable (29 bytes each):

,.+++[->+>+++++<<]>--->+[<.>]
,.[->+>+>--[<+>--]<<<]>>[<.>]
\$\endgroup\$
1
\$\begingroup\$

Lua, 41 bytes

a=io.read()while q~="0"do print(a)q=a end

Explanation:

a=io.read(): read input from user and store in variable a

while q~="0"do: compares q to the string "0", q starts as nil, which isn't "0" so the loop runs at least once. Because the input is a string we have to compare with the string "0", not the number 0

print(a)q=a: prints a (1 or 0) and sets q to a, so if a = "1" the loop continues, if a = "0" the loop stops

end: end of loop, like } in other languages

Whitespace is not needed after parenthesis/quotation marks, for example print(a)q=a is equivalent to print(a) q=a

\$\endgroup\$
  • \$\begingroup\$ Hi and welcome to PPCG! \$\endgroup\$ – Herman L May 26 '18 at 10:48
1
\$\begingroup\$

Rust, 90 bytes

use std::io::*;fn main(){let
b=&mut[0];stdin().read(b);while{stdout().write(b);b==b"1"}{}}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

FerNANDo, 37 bytes

_ _ _ 1 _ _ _ _ C
C
0 0 1 1 0 0 0 C
C

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Z80Golf, 9 bytes

00000000: cd03 80ff fe30 20fb 76                   .....0 .v

Try it online!

Disassembly

start:
  call $8003
loop:
  rst $38
  cp $30
  jr nz, loop
  halt

The Z80Golf machine initializes whole memory and all registers to zero before loading the program.

call $8003 calls getchar, which takes a byte from stdin to register a. On EOF, the register a does not change and the carry flag is set.

rst $38 simulates a call to putchar which prints the register a. The function is actually at $8000, so PC slides through $00 bytes (NOPs) in the memory until it hits the address $8000.

The rest is just a straightforward do-while loop in assembly, no tricks involved.


Z80Golf, Byte IO, 8 bytes

00000000: cd03 80ff b820 fc76                      ..... .v

Try it online!

Disassembly

start:
  call $8003
loop:
  rst $38
  cp b
  jr nz, loop
  halt

The only difference is the use of cp b, where b is used in place of constant zero.


Z80Golf, Byte IO, Tricky version, 8 bytes

00000000: cd03 80b8 2002 ff76                      .... ..v

Try it online!

Disassembly

start:
  call $8003
  cp b
  jr nz, infinity
  rst $38
  halt
infinity:

If the input is zero, rst $38 and then halt is executed, exiting the program normally. Otherwise, something weird happens:

  • PC goes to infinity:, slides through NOPs, and then putchar is executed.
  • The putchar has a ret instruction, so sp becomes 2 and execution is returned to the address $03cd.
  • Then putchar is executed again. sp becomes 4, pc is $b880.
  • Now pc wraps around and comes to $0000, the start of the program.
  • call $8003 is run, which overwrites the program so $80b8 becomes $0300.
  • getchar sets the carry flag, but we don't care anyway. EOF is hit so a is untouched.
  • Now cp b became nop, but jr nz, infinity is intact. Again putchar is run, sp becomes 6, pc is $0220. putchar again, sp = 8, pc is $76ff, putchar again, sp = 10 = $000a, pc = $0000.
  • The call $8003 became call $0303, which now effectively calls putchar instead. No problem, now one loop just prints a twice. Note that a call leaves $0300 to the memory, but fortunately $00 is NOP and $03 is inc bc, which does not affect the program's logic. (Single-byte inc does affect the flags, but double-byte ones don't, so jr nz isn't affected either.)
  • The call is now a heat wave filling the memory with $0300. Eventually, sp wraps around to $0002 again, and finally overwrites $cd03 into $0300, deleting the call .

The heat wave is finally over, and the only thing left is:

  jr nz, infinity
  rst $38
  halt
infinity:

The conclusion is that we have an infinite loop printing 1 as a byte.

Note that putchar is NOT an actual piece of code in memory. It is "simulated" when the PC hits $8000, along the ret instruction.

\$\endgroup\$
1
\$\begingroup\$

Pascal (FPC), 54 bytes

var a:word;begin read(a);repeat write(a)until a<1 end.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

VSL, 36 bytes

fn main(){do{print(i)}while Bool::i}

This is probably familiar to anyone who knows any C-esque language but this takes input using a global variable i. The Bool::i 'casts' the integer to a boolean (well technically just does i & 1 == 1).

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Backhand, 9 bytes

{I>{@:1O_

Try it online!

A little convoluted, but that's Backhand's way.

Explanation:

{I>{@:1O_
{           # Step left, bouncing off the wall and changing directions
 I          # Get input as a number
  >         # Enter loop by setting the direction to right
     :      # Dupe input
        _   # Step left if 1, otherwise right and change directions
       O    # Both output here, but are going in different directions
    @       # Terminate if 0
  >{  1     # Otherwise push 1 to the stack and restart the loop again
\$\endgroup\$
1
\$\begingroup\$

brainfuck, 28 bytes

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

Try it online!

This should be portable to almost all implementations of brainfuck. If you don't mind negative cells, you can save 2 bytes by removing the initial >>.

Explanation:

 >>                # Go right
 ,.                # Get input and print it once
 [[>]+<[-<]<+>>]   # Convert the number to binary while preserving it
 >[<]<<            # If the last digit of the binary is odd
 [.]               # Print the input forever
\$\endgroup\$
1
\$\begingroup\$

!@#$%^&*()_+, 10 bytes

*0_+!#(!#)

Try it online!

Explanation

*0_+!#(!#)
*             take byte of input
 0            push 48
  _+          subtract
    !#        duplicate and output
      (  )    while the top of the stack is not 0:
       !#     duplicate and output
\$\endgroup\$
1
\$\begingroup\$

Rockstar, 34 Bytes

Rockstar is a quite new computer programming language, designed for creating programs that are also song lyrics. Rockstar is heavily influenced by the lyrical conventions of 1980s hard rock and power ballads.

Listen to your heart
Say your heart
While it is not nothing
Scream it

But yes, you are right, it's longer than 34 bytes, but so poetic, I couldn't resist get some lyrics in. You could even sing it!. Here's the golfed version:

Listen to X
Say X
Until X
Say X
\$\endgroup\$
1
\$\begingroup\$

Alchemist, 24 bytes

_->In_a+Out_a
a->a+Out_a

Try it online!

I couldn't figure out a shorter way using only one output section. The closest I came was 25 bytes

Explanation:

_->In_a            # a = input
       +Out_a      # Output a
a->a               # While a
    +Out_a         # Output a
\$\endgroup\$
1
\$\begingroup\$

Gol><>, 5 bytes

IZh1n

Thanks to JoKing for helping golf this down further!!!

Try it online!

\$\endgroup\$
  • \$\begingroup\$ You don't have to handle numbers greater than one \$\endgroup\$ – Jo King Feb 5 at 21:01
  • \$\begingroup\$ your tio link has an extra : in it. I also think you can remove the > \$\endgroup\$ – Jo King Feb 10 at 21:43
0
\$\begingroup\$

Lua For windows, 70 bytes

Use lua for windows for this

I=io.read() If I=="1" then while 1 do print"1" end elseif print"0" end

This program works because it takes a 0 or 1 from stdin then if it's a one it makes a while loop that prints one if it's a 0 it prints 0 then the program ends

\$\endgroup\$
  • \$\begingroup\$ Does this rely on functionality specific to Windows? Why couldn't this be run with Lua on other systems? \$\endgroup\$ – Alex A. Nov 4 '15 at 3:16
  • 1
    \$\begingroup\$ This could be shorter if you just called If io.read()=="1" instead of assigning it to an alias. \$\endgroup\$ – James Murphy Nov 4 '15 at 5:41
0
\$\begingroup\$

Ceylon, 91 88 bytes

Improved (explanation at the end):

shared void run()=>("0"<(process.readLine()else"")then{1}.cycled else{0}).each(print);

This was the original (91 bytes):

shared void run(){if("0"<(process.readLine()else"")){while(0<1){print(1);}}else{print(0);}}

Unfortunately the most part goes to reading the input and making sure it is defined.

shared void run() {
    if("0"<(process.readLine() else "")) {
        while(0<1) {
            print(1);
        }
    } else {
        print(0);
    }
}

I merged this null check (in the else "" form) with the decision into one if, so when the input is ended without a line being read, it also prints 0. Also, any string sorting less than "0" lexicographically prints 0, and any string lexicographically > "0" will produce the 1-loop.

The 0<1 is used instead of true because it is shorter.

Here is a functional approach, unfortunately it can't compete (107 bytes after whitespace removal) due to the length of parseInteger:

shared void run() {
    value i = parseInteger(process.readLine() else "") else 0;
    (1:i).cycled.follow(i).each(print);
}

It cycles a range starting at 1 of length i (i.e. either {} or {1}), resulting in {} or {1,1,1,1,...}, prepends i (which results in {0} or {1,1,1,1,1,1,...}), and prints each element.


A different functional approach without variables and parsing is this one (88 bytes, shrinked version at the top):

shared void run() =>
        ("0" < (process.readLine() else "") then
    { 1 }.cycled else { 0 }).each(print);

This does the case distinction in an expression, using the then and else operators to produce either the {1,1,1,...} stream or the {0} singleton, and then calls print(...) on each element of that stream.

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

C#, 120 98 bytes

using c=System.Console;class o{static void Main(){if(c.Read()=='1')for(;;c.Write(1));c.Write(0);}}

Ungolfed:

using c=System.Console;
class o
{
    static void Main()
    {
        if(c.Read()=='1')
            for(;;c.Write(1));
        c.Write(0);
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ 2-byte gain: int a=c.Read();do c.Write(a-48);while(a>48); \$\endgroup\$ – LegionMammal978 Dec 6 '15 at 16:10
  • 1
    \$\begingroup\$ 95 bytes based on @LegionMammal978 answer using c=System.Console;class P{static void Main(){int a=c.Read()-48;do c.Write(a);while(a>0);}} \$\endgroup\$ – krontogiannis Aug 29 '16 at 10:26

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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