178
\$\begingroup\$

A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

  • Gets a number (either 0 or 1) from STDIN.

  • If that number is 0, print out 0 and terminate.

  • If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

  • take input from STDIN or an acceptable alternative
    • If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program
  • must output to STDOUT or an acceptable alternative
    • If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.
  • when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory
  • the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

  • if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes 

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes 

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes 

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes 

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 320px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 62732; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

\$\endgroup\$
19
  • 3
    \$\begingroup\$ Assuming any behaviour is fine for all invalid inputs? \$\endgroup\$ Commented Nov 3, 2015 at 17:33
  • 3
    \$\begingroup\$ @Cruncher Yes, the only inputs you should expect to get are 0 and 1. \$\endgroup\$ Commented Nov 3, 2015 at 17:38
  • 5
    \$\begingroup\$ Catalog is borked. \$\endgroup\$ Commented Nov 6, 2015 at 15:18
  • 2
    \$\begingroup\$ Catalog appears to consider Bf and bf to be different languages. \$\endgroup\$ Commented Nov 10, 2015 at 1:13
  • 1
    \$\begingroup\$ Is one allowed to print an infinite number of 1s? That is, not print out 1s forever, but print out an infinite list of 1s all at once? This would be theoretically demonstrated, but the language has no notion of printing more than once. It just generates an output. So is it okay if it runs indefinitely, but would print infinite 1s given infinite time (to finish executing)? \$\endgroup\$ Commented Apr 26, 2020 at 1:42

509 Answers 509

1
11 12
13
14 15
17
1
\$\begingroup\$

makina, 23 bytes

v>>P >?EJ U>PU ^0n< ;1< 

Explanation

The first automaton starts in the top left, and immediately goes down and right into the ?, or if. The condition for the if is the E, or number input. Once input is given, the condition automaton jumps forwards and out of bounds, causing it to return its value. If that value is 0, or false, the first automaton turns left and goes into the top P, or print. The print spawns a new automaton going right, which jumps over the U-turn, goes left, into the n, or number. It reads the 0, turns up, does a U-turn, hits the semicolon (ending the number), and goes out of bounds, returning a 0 to the print. The first automaton then goes out of bounds and halts. However, if the value is 1, or true, the automaton turns right and proceeds directly into the n, goes left, reads the 1, and halts. Then, the first automaton goes out if the print, into the U-turn, making it go back to the arrow to the left of the print, starting the whole cycle again.

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

Applesoft BASIC, 28 26 bytes

1INPUTA 2PRINTA 3IFA GOTO2 
\$\endgroup\$
1
\$\begingroup\$

Eukleides, 40 bytes

a=number();for i=0to 0;print a;i=i-a;end 

Pretty straightforward. number() takes in a number as input. For loop seems to be the golfiest means of looping for this task. While loop skips the i=i-a; but requires two prints.

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

JavaScript (Node.js), 54 bytes

A JavaScript answer that actually uses both STDIN and STDOUT

n=process.argv[2];do{process.stdout.write(n)}while(+n) 
\$\endgroup\$
1
\$\begingroup\$

Prolog (SWI), 28 bytes

:-get(X),repeat,put(X),X=48. 

Try it online!

Gets a single character, then repeatedly print it, stopping if it is a zero.

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

Nekomata, 2 bytes

ᶦP 

Attempt This Online!

ᶦ Iterate the following function zero or more times until it fails P Check if the input is positive 
\$\endgroup\$
1
\$\begingroup\$

Funky, 28 bytes

s=io.read()while(-print(s))a 

Try it online!

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

Thunno 2, 2 bytes

Attempt This Online!

 # implicit input ( # while TOS is not 0: ß # print without popping # implicit output 
\$\endgroup\$
1
\$\begingroup\$

Tsept v1.0, 45 bytes

Tsept is an open-source esolang I created; it's not really meant for code golfing, as even basic tasks like setting a register to a number take many instructions, and even though there are seven different registers it's almost impossible to do anything without the stacks.

?PBKpPxIIIPAPAPAPABpBPBSPBxDDPAPADPBKB!BKBPBi 

Note that you'll need a Linux machine to run this since there is no web-based interpreter for it (yet).

Analysis

?PBKpPxIIIPAPAPAPABpBPBSPBxDDPAPADPBKB!BKBPBi ?PBKpP Store input in register B xIIIPAPAPAPA Set accumulator to 48 BpBPB Swap stack value and accumulator SP Subtract ASCII 1 from accumulator and push to stack BxDDPAPADPB Calculate jump offset KB!BKBPBi Loop 
\$\endgroup\$
1
\$\begingroup\$

(,) 63 Chars or \$63\log_{256}(3)\approx\$ 12.48 Bytes

This was quite fun, kudos to Dadsdy for creating this language!

((),((())))(()(),(()())()(),,,(()),(()()))(,,,(()),(()()),(())) 

Try it!

Explanation

Set var_1 to the ascii value of the input (48 or 49) ((),((()))) var_2 = var_2 + 2; repeat while var_1 > var_2 (()(),(()())()(),,,(()),(()())) print var_1; repeat while var_2 > var_1 (,,,(()),(()()),(())) 

In practice this counts up in twos until var_2 becomes at least as big as the input. If the input was 0 (ascii 48) var_2 will be 48 and the last loop will run only once, if the input was 1 (ascii 49) var_2 will be 50 and the last loop will never terminate.

\$\endgroup\$
1
  • \$\begingroup\$ The behaviour of the loop executing only once if the conditions are equal is pretty helpful \$\endgroup\$ Commented Jun 23, 2023 at 2:27
1
\$\begingroup\$

(,), 46 bytes

((),(((()))(())),,,(),,((())))(,,(()),,((()))) 

Try it online!

Outputs separated by newlines.I also have an alternative 46 byter using a similar strategy.

Explanation:

Note that the var shorthand below will return -1 for 0 (representing EOF) and 1 for -1, otherwise the value stored at that index (default 0).

((),(((()))(())),,,(),,((()))) First expression () Set var1 ,(((()))(())) To var(var(var(1))+var(1)) So when var(1) maps to: 0 -> var(var(0)+0) = var(-1+0) = 1 1 -> var(var(1)+1) = var(1+1) = 0 basically alternating between 0 and 1 each loop my other solution flips between 0 and -1 instead ,,,(), Repeat while 1>-1 ((())) A maximum of input char times (,,(()),,((()))) Second expression ,,(()) Output var1 ,,((())) Execute once if var(var(1)) == -1 And repeat forever if var(var(1)) > -1 
\$\endgroup\$
1
\$\begingroup\$

Thue++, 17 bytes

0::=~0 (?=1)::=~1 

Input is the state string, output is the alerts.

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

MaybeLater, 48 bytes

whenx is1{write(1)when0spass x=1}write(x=read()) 

One could remove when0spass for 37 bytes, though doing so causes a stack-overflow pretty quickly.

A Pretty Canonical MaybeLater answer, hooks to x being assigned to 1 by writing a 1 and setting x to 1 again, causing an infinite loop. when 0 seconds pass is required to avoid recursion errors by using the event queue instead. Either way, writes the result of the read.

Try it online!

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

Shenzhen I/O, 51 bytes, 3¥, 5 Lines

@mov p0 acc teq acc 0 +mov 0 x1 +mov 0 x0 -mov 1 x1 

Takes an input on p0 and outputs to a LCD at x1. If the input is 0, writes to an unconnected XBus wire and will wait indefinitely (this is the closest to terminating that I can think of). If the input is non-zero, loops forever writing 1.

Here is a screenshot of the two cases simultaneously.

enter image description here

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

><x>, 105 bytes

lddddddddddddddddddddddddddddddddddddddddddddddddn?v >n< 
\$\endgroup\$
2
  • \$\begingroup\$ Welcome codegolf @none1 ; This is a nice try. \$\endgroup\$ Commented Oct 31, 2023 at 17:39
  • \$\begingroup\$ @none1 16 byte version \$\endgroup\$ Commented Nov 29, 2023 at 19:02
1
\$\begingroup\$

><x>, 16 9 bytes

-7 bytes thanks to Bubbler

Abuses the fact that after every instruction, the accumulator is bound to [0, 255]. This allows us to just square the input until it's 0 or 1. Thankfully, ASCII "0", 48, takes only one square to equal 0, and ASCII "1" needs just 4 to equal 1 .

lssss>n?< 
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I think lssss>n?< works. \$\endgroup\$ Commented Nov 29, 2023 at 23:58
1
\$\begingroup\$

sed -n, 10 bytes

To avoid the expensive loop, duplicate the line and use D for looping:

h G P /1/D 

Try it online!

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

ELVM IR, 50 bytes

getc A mov B,A sub A,48 .x: putc B jeq .x,A,1 exit 

Explanation:

getc A - Input A as ASCII mov B,A - Copy A to B sub A,48 - Subtract A by 48, which converts ASCII to number, while B still stores the ASCII .x: putc B - Output B (The ASCII) jeq .x,A,1 - If A (The number) is equal to 1, jump to .x exit - Exit 
\$\endgroup\$
1
\$\begingroup\$

Chef, 179 bytes

a. Ingredients. 0 a 1 b Method. Take a from refrigerator. V the a. Put b into 3rd mixing bowl. Pour contents of the 3rd mixing bowl into the baking dish. V until ved. Serves 1. 

Try it online!

A test of my new [REDACTED] compiler. As Chef always prints values only at program termination, this technically doesn't fulfill the requirements, but the baking pan (the thing that has the output) does fill up with infinite 1s so it technically counts. Here's the original code as a teaser:

def $in; read $in; while $in { print 1; flush; }; 
\$\endgroup\$
1
\$\begingroup\$

Uiua, 5 bytes

⍢⟜&p∘ 

Try it

Do without popping print &p while top of stack is 1 .

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

Easyfuck, 5 bytes

"[']' 

" - input

[ ] - while loop

' ' - output

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

How dare you fuck the brain, 10 8 bytes

;/H^I|N) 

Try it online

\$\endgroup\$
1
  • \$\begingroup\$ Since TIO does not directly support the language, it's not immediately obvious where the code is found in the link. You may want to point that out. \$\endgroup\$ Commented Oct 8, 2024 at 18:06
1
\$\begingroup\$

Python 3 52 bytes

B=print def A():B(1);A() A()if input()=='1'else B(0) 

Defines a recursive function, which I believe is shorter than a while loop. Ternary statement then executes it.

Probably not the most golfed down answer.

\$\endgroup\$
1
  • \$\begingroup\$ Hi there hello, welcome to the Code Golf StackExchange! Nice first answer! \$\endgroup\$ Commented Sep 21 at 4:05
1
\$\begingroup\$

Binary encoded lambda calculus (6.75 bytes or 54 bits)

000101100100010001101000011100110100000010110111011010

returns 0 if applied to 0, if aplied to 1 returns a lazylist of 1's

Definitions Uses the de-facto standard definition of integers, booleans and lists.

0 = λf.λx.x, 1 = λf.λx.(fx), 2 = λf.λx.(f(fx)), etc.

Booleans arent needed at all. still interesting.

True = λa.λb.a (take a and b and return a)

False = λa.λb.b (take a and b and return b)

list = λf.((fH)T) (H and T are preinserted Head and Tail)

so to construct a list, you use λH.λT.λf.((fH)T) taking Head X and Tail Y, and return λf.((fX)Y) then you can get the head X by applying True and the Tail Y by applying false. This will not be needed per se as we will only construct the list, but is interesting to know.

NOTE: this was the definition for a pair, but a list is a pair where the first argument is a value and the second argument is another list.

Pieces

The Y combinator Takes a function f, and turns it into f(Yf) thus, Yf -> f(Yf). Do you see the recursion?

Usualy defined as: (λf.(λx.f(xx))(λx.(f(xx))))

BUT! if we define it as (λf.(λx.xx)(λx.(f(xx)))) that reduces directly to (λf.(λx.f(xx))(λx.(f(xx)))), and is 5 bits smaller. lets call the compressed Y combinator Y'

The weird function W (λz.λv.(vn)z))

NOTE: this is not a closed lambda term, as it uses n. This isnt an issue though as the function its used in has n in a lambda.

The Combined function C

Just Y' applied to W

(Y' W) which is also ((λf.(λx.xx)(λx.(f(xx)))) (λz.λv.(vn)z))) Which reduces to (λv.(vn)((λx.λv.(vn)(xx))(λx.λv.(vn)(xx)))) then to (λv.(vn)(λv.(vn)((λx.λv.(vn)(xx))(λx.λv.(vn)(xx))))) and then to (λv.(vn)(λv.(vn)(λv.(vn)((λx.λv.(vn)(xx))(λx.λv.(vn)(xx)))))) and etcetera. an infinite lazy list of n.

The main function M λn.((n C) n) all together, this is λn.((n ((λf.(λx.xx)(λx.(f(xx)))) (λz.λv.(vn)z)))) n) this is where n gets 'bound'.

Results

Apply M to 0 or also (λf.λx.x) and you get (((λf.λx.x) ((λf.(λx.xx)(λx.(f(xx)))) (λz.λv.(v(λf.λx.x))z)))) (λf.λx.x))

then Reduce to ((λx.x) (λf.λx.x))

and then to (λf.λx.x) Also known as 0

Apply it to one, and after some amount of hard to explain steps where it aplies one to 1 and does some other steps to make a identity function or something, it returns the lazy list of n, but n is now one. so apply M to one and it it returns a lazy list of one.

Lazy list of one here: ((λf.(λx.xx)(λx.(f(xx)))) (λz.λv.(v((λf.λx.(fx))))z)))

Encoding

But then, we need to convert the whole thing into binary encoded lambda calculus. I wont bother with the details, but it becomes 000101100100010001101000011100110100000010110111011010

00011001 C 10 is M

C is 01000100011010000111001101000000101101110110 or 01 Y' W

Y' is 0001000110100001110011010 and W is 00000101101110110

Try it here: lambda calculus applet, then simply apply it to 1 or 0 (input so its not included) and that integer gets automatically translated.

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

Tcl, 38 bytes

gets stdin r puts $r while $r puts\ $r 

Try it online!

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

8ial, 87 74 69 bytes

PUT $1 ;d JIR l $1 0 JIR l $1 1 DEC $1 JMP d ;l OUT $1 JIR l $1 1 END 

someone pointed out that PSH was really only used for storing outputs so now it's END

\$\endgroup\$
0
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\$
2
  • \$\begingroup\$ Does this rely on functionality specific to Windows? Why couldn't this be run with Lua on other systems? \$\endgroup\$ Commented Nov 4, 2015 at 3:16
  • 2
    \$\begingroup\$ This could be shorter if you just called If io.read()=="1" instead of assigning it to an alias. \$\endgroup\$ Commented Nov 4, 2015 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\$
2
  • 1
    \$\begingroup\$ 2-byte gain: int a=c.Read();do c.Write(a-48);while(a>48); \$\endgroup\$ Commented Dec 6, 2015 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\$ Commented Aug 29, 2016 at 10:26
0
\$\begingroup\$

x86 (Linux / NASM syntax), 86 bytes

mov dx,1 ; 3rd argument to read(): length of buffer mov ecx,esp ; 2nd argument to read(): the buffer ; 1st argument to read(): the FD is already 0 mov ax,3 ; read system call number int 128 ; invoke syscall, returns eax=1 == num of read bytes l:mov ax,4 ; start of loop, eax=syscall number of write() int 128 ; invoke syscall, returns eax=1 == num of written bytes cmp byte[esp],49 ; compare buffer against '1' jz l ; loop of it's the same int 128 ; invoke syscall otherwise (syscall 1 == exit) 

Compile with nasm -f elf h.asm && ld -o h h.o -m elf_i386 and ignore all warnings. :-)

\$\endgroup\$
1
11 12
13
14 15
17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.