| Bytes | Lang | Time | Link |
|---|---|---|---|
| nan | Binary encoded lambda calculus 6.75 bytes or 54 bits | 251013T171823Z | maledisc |
| nan | Bitwise Cyclic Tag | 170208T222044Z | DLosc |
| 052 | Python 3 | 250921T032234Z | Random D |
| 067 | 8ial | 241127T201330Z | Gleb |
| 008 | How dare you fuck the brain | 241008T175911Z | Gleb |
| 014 | 'Python' is not recognized | 241109T102404Z | Gleb |
| 039 | Tcl | 170131T011050Z | sergiol |
| 068 | SAKO | 250314T163758Z | Acrimori |
| nan | Piet + asciipiet | 220331T140642Z | Bubbler |
| 048 | Bespoke | 250115T222652Z | Josiah W |
| 090 | Malbolge | 250108T161831Z | Weird Gl |
| 032 | Hatchback | 241211T175127Z | madeforl |
| 009 | punchcode | 241127T222536Z | madeforl |
| 018 | ibe | 241127T214429Z | madeforl |
| 014 | MAWP v1.1 | 200805T123930Z | Razetime |
| 273 | Qdeql | 240908T153854Z | Bbrk24 |
| 034 | Boo | 160203T193607Z | user4594 |
| 012 | Befalse quirkster | 240523T000516Z | Bubbler |
| 005 | Easyfuck | 240325T011752Z | Quadrupl |
| 005 | Uiua | 240320T014712Z | noodle p |
| 179 | Chef | 240319T230341Z | Seggan |
| 050 | ELVM IR | 240221T120741Z | None1 |
| 011 | *><> | 240216T211322Z | Bee H. |
| 010 | sed n | 231130T143910Z | Philippo |
| 009 | > | 231129T185958Z | Bee H. |
| 198 | Intcode | 231129T193047Z | Bee H. |
| 013 | Trilangle | 230221T222404Z | Bbrk24 |
| 028 | shell | 231031T174005Z | gildux |
| 105 | > | 231031T133807Z | None1 |
| 005 | Shenzhen I/O | 231020T124324Z | corvus_1 |
| 048 | MaybeLater | 230927T024030Z | ATaco |
| 045 | Desmos | 211028T171750Z | thejonym |
| 017 | Thue++ | 230722T031921Z | Dadsdy |
| 058 | Racket | 230719T172245Z | Ed The & |
| 028 | ForWhile | 230719T150411Z | bsoelch |
| nan | 230531T140209Z | Dadsdy | |
| 040 | AArch64 machine code + Linux syscalls | 230624T081257Z | landfill |
| 046 | 230623T035803Z | Jo King | |
| nan | 230623T013321Z | Leo | |
| 045 | Tsept v1.0 | 230622T175602Z | kevidryo |
| 010 | x86 machine code | 190111T184314Z | 640KB |
| 039 | hyperscript | 230501T132647Z | The Thon |
| 012 | Desmoslang Assembly | 230530T051604Z | Dadsdy |
| 002 | Thunno 2 | 230528T140152Z | The Thon |
| 028 | Funky | 230322T042747Z | ATaco |
| 002 | Nekomata | 230321T054959Z | alephalp |
| 031 | Google Forms | 230207T184204Z | rydwolf |
| nan | 230108T172319Z | The Thon | |
| 027 | nroff/troff | 221019T041427Z | IY5dVSjA |
| 022 | ArcPlus | 170608T085709Z | Mayube |
| 028 | Prolog SWI | 220902T113957Z | Jo King |
| 043 | LeafLang | 220831T040120Z | Breadlea |
| 005 | Brainfuck | 160920T061621Z | ATaco |
| 013 | K ngn/k | 220811T090807Z | Bubbler |
| nan | Shell posix | 220810T182105Z | Breadlea |
| 043 | Python | 220725T231049Z | Eric Xue |
| nan | Fig | 220726T184420Z | Seggan |
| 054 | JavaScript Node.js | 220725T104603Z | Leaf |
| 040 | Eukleides | 190430T134238Z | brhfl |
| 067 | A0A0 | 220515T182426Z | stefvans |
| 014 | SMALL | 220515T180816Z | stefvans |
| 026 | Applesoft BASIC | 220515T154924Z | Ohentis |
| 023 | makina | 220515T135528Z | Ginger |
| 036 | PostScript | 220430T074029Z | bartysla |
| 031 | tinylisp | 220416T041254Z | des54321 |
| 020 | Plumber | 210521T171504Z | Aaroneou |
| 034 | 10IPL | 210416T150315Z | rydwolf |
| 008 | dotcomma | 200824T003723Z | rydwolf |
| 026 | Pari/GP | 220114T121656Z | alephalp |
| 007 | Add++ | 170604T184905Z | caird co |
| 005 | StupidStackLanguage | 211224T043004Z | whqwert |
| 033 | Desmos | 211223T173329Z | Aiden Ch |
| 024 | AHHH | 211217T173839Z | DLosc |
| 016 | APOL | 211209T131844Z | Ginger |
| 028 | Batch | 211209T200624Z | T3RR0R |
| 023 | Brainfuck | 211116T035757Z | Luke Stu |
| 041 | INTERCAL | 211116T070528Z | user1004 |
| nan | 211116T060532Z | Nate T | |
| nan | Pure Bash | 211111T095933Z | user1004 |
| 010 | ErrLess | 211023T073734Z | Ruan |
| 006 | Pure CPython 3.10 bytecode | 211029T084502Z | pxeger |
| 034 | Hello Hell | 211028T124744Z | Aaroneou |
| 034 | Python 3 | 211028T111408Z | Zaid Al |
| 008 | Clam | 190107T212226Z | Mayube |
| 005 | Braingolf | 170503T211239Z | Mayube |
| 015 | Unlambda | 211026T133150Z | Samuel W |
| 117 | Arduino | 210813T021644Z | Bbrk24 |
| 015 | ppencode | 210709T092425Z | user1004 |
| 027 | n/t/roff | 210819T025137Z | user1004 |
| 010 | Flipbit | 210723T230550Z | Aaroneou |
| 041 | NimLang | 210627T220107Z | Qaziquza |
| nan | Mascarpone | 210627T172705Z | Soup Gir |
| 049 | Dis | 210623T083559Z | user1004 |
| 004 | yuno | 210621T222708Z | hyperneu |
| 006 | BrainFlak | 210610T122046Z | Jay Ryan |
| 047 | Squire | 210609T163553Z | EasyasPi |
| 013 | sed | 210609T162332Z | Yelp |
| 046 | Ocaml | 210609T155522Z | tbrugere |
| 028 | Red | 210601T150412Z | Aaroneou |
| 012 | Piet | 210606T192625Z | Tangible |
| 007 | 2D Deadfish | 210529T070737Z | wasif |
| 010 | Barrel | 210523T193238Z | LorenDB |
| 011 | Knight | 210522T010019Z | EasyasPi |
| 004 | Stax | 210521T211502Z | user1040 |
| 015 | Subleq 8bit | 210521T182444Z | Axuary |
| 016 | Starry | 210521T172432Z | Jay Ryan |
| 002 | Duocentehexaquinquagesimal | 210417T025114Z | Makonede |
| 003 | Vyxal | 210514T064531Z | Undersla |
| 013 | Pxem | 210505T051833Z | user1004 |
| 072 | CASL II | 210505T050152Z | user1004 |
| 054 | CSASM v2.3.1 | 210424T012327Z | absolute |
| 041 | Pinecone | 210422T164140Z | wasif |
| 013 | V vim | 210416T161533Z | Razetime |
| 010 | Grok | 210416T170328Z | Aaroneou |
| 040 | Python | 210323T123732Z | user1008 |
| 022 | Turing Machine Code | 151103T170251Z | SuperJed |
| 020 | x86_16 machine code | 210321T124712Z | Febriyan |
| 047 | Python 3 | 210308T195636Z | M Virts |
| 005 | Builtout | 210308T165103Z | Bo_Tie |
| 006 | v³ | 210209T162657Z | Bo_Tie |
| 010 | convey | 210122T121729Z | Jo King |
| 011 | BRASCA | 210122T094729Z | SjoerdPe |
| 035 | Python 3 | 201201T132208Z | SeoFerna |
| 003 | 05AB1E | 201129T010144Z | Makonede |
| 120 | Fugue | 201128T161724Z | LegionMa |
| 006 | Prelude | 151103T192343Z | Martin E |
| 082 | NDBall | 201102T131145Z | QTpye |
| 025 | MarioLang | 160630T141307Z | user5420 |
| 045 | Acrostic | 201001T074147Z | JosiahRy |
| 137 | Poetic | 200930T230527Z | JosiahRy |
| 008 | sed 4.2.2 | 200930T195713Z | Chris |
| 004 | Arn | 200821T135736Z | ZippyMag |
| 010 | 1+ | 200802T140911Z | Twilight |
| 019 | Turing Machine Code | 200121T161821Z | ouflak |
| 634 | RAKIAC machine language | 200130T200539Z | Roninkoi |
| 040 | Python3 | 200130T151953Z | JBarrioG |
| 017 | AWK | 200130T150547Z | rootbeer |
| 068 | Comp | 200130T141542Z | user8505 |
| 055 | Wren | 200123T055133Z | user8505 |
| 120 | Shakespeare Programming Language | 200116T155802Z | Hello Go |
| 032 | JavaScript | 200115T002544Z | Benji |
| 003 | tq | 200101T015225Z | user8505 |
| 001 | W s | 191214T013034Z | user8505 |
| 035 | Python 3 | 191226T150549Z | Sagittar |
| nan | Keg | 190607T023037Z | user8505 |
| 003 | Gaia | 191028T174021Z | Business |
| 321 | Jasmin | 151103T215624Z | ankh-mor |
| 5432 | MathGolf | 191013T024754Z | user8505 |
| 010 | Cascade | 190923T062812Z | Jo King |
| 290 | Verbosity v2 | 190921T131407Z | caird co |
| 086 | Rust compiler nightly | 190918T161154Z | leo60228 |
| 187 | Unsuspectedhangul | 190911T064643Z | LegenDUS |
| 032 | JavaScript | 190829T164022Z | Naruyoko |
| 004 | Befunge | 170901T031236Z | MercyBea |
| 006 | Runic Enchantments | 190826T190532Z | Draco18s |
| 007 | Befunge93 | 190826T185758Z | osuka_ |
| 004 | 33 | 190808T084834Z | TheOnlyM |
| 007 | Pip | 190807T180917Z | Kenzie |
| 123 | Pyramid Scheme | 170130T025442Z | Conor O& |
| 128 | Enterprise | 190618T012754Z | Tux1 |
| 105 | EZLang | 190606T124033Z | LegenDUS |
| 028 | Aheui | 190606T111155Z | LegenDUS |
| 012 | Ruby + np | 180305T231039Z | Asone Tu |
| 013 | GolfScript | 190604T221324Z | clabe45 |
| 082 | NuStack | 190528T152700Z | Mayube |
| 032 | VSL | 181227T011209Z | Downgoat |
| 257 | Malbolge | 190521T213341Z | ThePlasm |
| 089 | INTERCAL | 190521T193207Z | Unrelate |
| 003 | AlgiX with x | 190506T183807Z | Mayube |
| 025 | VTL2 | 190503T162340Z | brhfl |
| 041 | Python 3 | 190430T165638Z | movatica |
| 065 | C++ gcc | 190430T164307Z | movatica |
| 034 | Rockstar | 190122T141518Z | gaborsch |
| 052 | C gcc | 190310T040046Z | Benjamin |
| 019 | Tamsin | 190310T032758Z | Esolangi |
| 018 | Deoxyribose | 180316T133449Z | georgewa |
| 005 | Gol><> | 190205T035600Z | KrystosT |
| 024 | Alchemist | 190204T105339Z | Jo King |
| 139 | Turing Machine But Way Worse | 190204T052643Z | MilkyWay |
| 038 | Lua | 190117T213936Z | Alex All |
| 005 | bitch | 190108T001928Z | Helen |
| 010 | !@#$%^&*_+ | 190111T161244Z | Conor O& |
| 028 | brainfuck portable | 180705T054015Z | ais523 |
| 054 | F# .NET Core | 190109T050140Z | dana |
| 028 | brainfuck | 190109T000424Z | Jo King |
| 009 | Backhand | 190108T233558Z | Jo King |
| 194 | Little Man Computer | 181214T224121Z | FlipTack |
| 119 | Assembly nasm | 181212T231430Z | Mayube |
| 054 | Pascal FPC | 180813T224831Z | AlexRace |
| 010 | Flobnar | 180813T220719Z | Esolangi |
| 009 | Z80Golf | 180810T050005Z | Bubbler |
| 049 | Acc! 49 Bytes | 151103T185125Z | The Fift |
| 019 | Selfmodifying Brainfuck | 151103T193633Z | mbomb007 |
| 015 | Pepe | 180806T080409Z | RedClove |
| 045 | Python 2.7 | 180709T200609Z | Stealthy |
| 015 | PowerShell | 180716T143111Z | J. Bergm |
| 369 | PUBERTY | 180717T005905Z | Yhprum |
| 004 | MATL | 160123T164804Z | Luis Men |
| 037 | FerNANDo | 180709T165453Z | Erik the |
| 030 | 2DFuck | 180507T181928Z | wastl |
| 061 | ABAP | 180705T075113Z | Noir Ant |
| 090 | Rust | 180705T065811Z | null |
| 010 | Ahead | 180622T053611Z | snail_ |
| 041 | Lua | 180526T092936Z | Marre3 |
| 042 | Charm | 180525T235123Z | LyricLy |
| 025 | brainfuck | 180525T195527Z | Endenite |
| 029 | TIS n 1 1 | 180502T205238Z | Phlarx |
| 037 | Whitespace | 151104T092908Z | n̴̖̋h̷͉̃ |
| 042 | Fortran GFortran | 180316T145245Z | rafa1111 |
| 012 | Quarterstaff | 180306T223835Z | Destruct |
| 009 | Momema | 180309T040438Z | Esolangi |
| 011 | QUARK | 180308T170238Z | moonhear |
| 052 | Linotte | 180308T053736Z | Conor O& |
| 033 | Python 2 | 180306T024901Z | Allen Fi |
| 022 | ShinyLisp | 180306T001235Z | Silvio M |
| 036 | Yabasic | 180305T223144Z | Taylor R |
| 026 | Reflections | 180304T205752Z | wastl |
| 003 | Stax | 180303T204719Z | Khuldrae |
| 2927 | R | 151104T000554Z | MickyT |
| 041 | Kotlin Script | 180302T185830Z | jrtapsel |
| 004 | Brachylog | 180228T113152Z | Martin E |
| 033 | Aheui | 180218T101537Z | 0xrgb |
| 395 | ORK | 180218T084628Z | DLosc |
| 021 | Draw | 180210T233540Z | ivzem |
| 041 | Zephyr | 161008T201159Z | DLosc |
| 021 | Forked | 180210T021210Z | MD XF |
| 006 | Wumpus | 180210T195852Z | Martin E |
| 042 | C gcc | 180204T090301Z | PrincePo |
| 060 | Forte | 170131T065045Z | DLosc |
| 020 | AWK | 180131T141155Z | Robert B |
| 011 | FALSE | 180131T134554Z | 12Me21 |
| 011 | Dreaderef | 180131T051521Z | Esolangi |
| 007 | Retina | 151103T210306Z | Martin E |
| 037 | Acc!! | 180118T143722Z | Conor O& |
| 028 | #+ | 180118T140101Z | Conor O& |
| 005 | Pyt | 180116T172243Z | mudkip20 |
| 038 | SNOBOL4 CSNOBOL4 | 180116T152817Z | Giuseppe |
| 074 | Evil | 170101T220552Z | user6280 |
| 034 | Whispers | 171210T142300Z | caird co |
| 026 | JavaScript | 171010T054712Z | Ephellon |
| 053 | Swift | 151208T125254Z | Simon |
| 013 | GolfScript | 171121T212555Z | FedeWar |
| 005 | Husk | 171121T205559Z | ბიმო |
| 006 | ><> | 171121T201902Z | Bolce Bu |
| 038 | Bitwise | 171121T175008Z | MD XF |
| 040 | JavaScript ES5 | 170508T123027Z | user6903 |
| 126 | Java | 170608T092115Z | user4490 |
| 911 | Duck Duck Goose | 170719T180107Z | ABot |
| 004 | Implicit | 170907T022402Z | MD XF |
| 103 | Java OpenJDK 8 | 171115T150210Z | Luca H |
| 039 | Python 2 | 170806T225919Z | Stan Str |
| 031 | JavaScript | 151104T160041Z | Solomon |
| 037 | MATLAB | 151103T164951Z | Stewie G |
| 030 | CMD | 171010T053123Z | Ephellon |
| 028 | 4 | 171002T153749Z | KSmarts |
| 141 | INTERCAL | 171002T150506Z | KSmarts |
| 005 | Pyth | 170908T043534Z | Stan Str |
| 219 | Thotpatrol | 170904T210356Z | Mr. Negi |
| 040 | Whitespace | 170904T052135Z | Josiah W |
| 020 | Excel VBA | 170903T182131Z | Taylor R |
| 017 | 6502 machine code C64 | 170901T152240Z | Felix Pa |
| 225 | HP48's RPL | 151104T052241Z | LeFauve |
| 058 | 8th | 170813T140249Z | Chaos Ma |
| 128 | Assembly as | 170806T205024Z | Marcos |
| 006 | Cubically | 170805T111701Z | TehPers |
| 050 | Python 2 | 170805T093137Z | Husnain |
| 028 | Cubically | 170804T224710Z | MD XF |
| 007 | Ly | 170804T234947Z | LyricLy |
| 8079 | C# .NET Core | 170718T164821Z | Kamil Dr |
| 019 | ILL | 170718T162229Z | Socratic |
| 018 | Lean Mean Bean Machine | 170717T100508Z | Mayube |
| 006 | Triangular | 170614T160355Z | MD XF |
| 005 | Noether | 170606T212752Z | Beta Dec |
| 003 | Wise | 170606T134726Z | Mayube |
| 032 | Decimal | 170606T032311Z | MD XF |
| 011 | MarioLANG | 170526T050244Z | user6933 |
| 617 | Taxi | 170522T193615Z | Engineer |
| 010 | Aceto | 170411T113253Z | L3viatha |
| 040 | Javascript Node | 170507T201442Z | Sullof |
| 025 | OIL | 170411T112250Z | L3viatha |
| 033 | REXX | 170411T111939Z | idrougge |
| 008 | Alice | 170411T111213Z | Martin E |
| 016 | Deadfish i | 170308T115821Z | fergusq |
| 007 | BitCycle | 170210T232819Z | DLosc |
| 030 | Common Lisp | 151104T144902Z | Joshua T |
| nan | 170209T071813Z | Matthew | |
| 014 | Pyramid | 161222T033011Z | clismiqu |
| 022 | SmileBASIC | 170130T043818Z | 12Me21 |
| 006 | Chip | 170130T210800Z | Phlarx |
| 005 | Threead | 170113T041917Z | Pavel |
| 010 | QBIC | 170105T171355Z | steenber |
| 004 | Japt | 151103T171117Z | ETHprodu |
| 002 | PlatyPar | 151214T174848Z | Cyoce |
| 003 | Pushy | 161222T120131Z | FlipTack |
| 009 | Haystack | 161222T101032Z | user4180 |
| 020 | PHP | 161221T020234Z | Titus |
| 010 | stacked | 161221T011652Z | Conor O& |
| 024 | PHP | 151109T203532Z | Martijn |
| 003 | Jelly | 161209T185051Z | JayDepp |
| 022 | TSQL | 161209T091636Z | grabthef |
| 005 | BrainInt | 161208T182300Z | NoOneIsH |
| 016 | Underload | 161122T101317Z | user6213 |
| 008 | Fuzzy Octo Guacamole | 160331T154704Z | Riker |
| 011 | Doxical | 161117T062633Z | clismiqu |
| 087 | D | 161103T024959Z | Adalynn |
| 038 | Valve scripting language | 161103T002641Z | Conor O& |
| 006 | Dip | 161101T163517Z | Oliver N |
| 032 | Javascript | 161101T162232Z | CT14.IT |
| 006 | JAISBaL | 160711T201225Z | Socratic |
| 030 | PHP | 161027T100908Z | CT14.IT |
| 036 | Crystal | 161026T200928Z | Zatherz |
| 006 | reticular | 161004T190846Z | Conor O& |
| 007 | ABCR | 161006T085553Z | Steven H |
| 038 | Moorhen 1 or original creators version 1 here | 161005T110120Z | Destruct |
| 004 | LI | 161004T080013Z | Steven H |
| 059 | Copy | 160924T201758Z | TuxCraft |
| 005 | braingasm | 160924T175033Z | daniero |
| 043 | Logicode | 160920T085337Z | clismiqu |
| 034 | Lua | 160920T061348Z | ATaco |
| 007 | Turtlèd | 160920T034647Z | Destruct |
| 012 | dc | 160830T063709Z | seshouma |
| 017 | Straw | 160909T182030Z | TuxCraft |
| 005 | Cubix | 160315T000829Z | MickyT |
| 266 | Woefully | 160906T105134Z | Destruct |
| 088 | Java | 160901T084739Z | Shaun Wi |
| 003 | Seriously | 151109T030456Z | user4594 |
| 033 | Python 2 | 160901T083749Z | gowrath |
| 009 | Ru | 160901T090002Z | TuxCraft |
| 006 | ><> | 160901T082006Z | gowrath |
| 034 | PHP | 160722T082418Z | Sefa |
| 021 | PowerShell | 160829T214646Z | Chirishm |
| 040 | C | 160829T143547Z | Stefano |
| 095 | Churro | 160829T131701Z | Copper |
| 023 | TSQL | 160826T145205Z | S.Karras |
| 028 | Perl 6 | 160826T001639Z | bb94 |
| 189 | Shakespeare Programming Language | 160825T185055Z | Copper |
| 008 | MarioLANG | 151104T155808Z | Martin E |
| 125 | Gaot++ | 160723T174204Z | Leaky Nu |
| 057 | JQuery | 160722T095802Z | Ronronne |
| 036 | Racket | 160722T073325Z | Winny |
| 058 | eacal | 160720T232345Z | Conor O& |
| 002 | Sesos | 160717T000939Z | Dennis |
| 003 | Silicon | 160630T133516Z | m654 |
| 011 | Tellurium | 160524T124819Z | m654 |
| 141 | WistfulC | 160606T203708Z | jqkul |
| 024 | PowerShell | 160104T171016Z | beatcrac |
| 012 | Scratch | 160524T163117Z | weatherm |
| 006 | UGL | 160421T225700Z | Leaky Nu |
| 432 | Pyth | 151103T172603Z | FryAmThe |
| 004 | Pyke | 160426T172946Z | Blue |
| 045 | Julia | 151104T024657Z | Alex A. |
| 029 | JavaScript | 151124T023535Z | Adam Dal |
| 025 | R | 160411T125832Z | Masclins |
| 032 | Common Lisp | 160411T172608Z | JPeroute |
| 031 | Javascript | 160411T170434Z | Qwertiy |
| 052 | Lua | 160208T082833Z | Katenkyo |
| 006 | Reng v.3.3 | 160408T174427Z | Conor O& |
| 101 | Oration | 160408T171335Z | Riker |
| 012 | Fission | 160406T203224Z | MickyT |
| 011 | Pylongolf2 | 160401T060609Z | user4701 |
| 7214 | Befunge | 160330T152934Z | Leaky Nu |
| 029 | Come Here | 160326T111827Z | SuperJed |
| 225 | Wierd | 160317T040852Z | Jerry Je |
| 026 | Beatnik | 160316T224807Z | MickyT |
| 006 | Gogh | 160316T213603Z | Downgoat |
| 027 | NTFJ | 160302T151704Z | ETHprodu |
| 052 | ForceLang | 160229T032440Z | SuperJed |
| 083 | BASTARD | 160219T120424Z | s4b3r6 |
| 033 | Shtriped | 160219T080207Z | Calvin |
| 016 | Piet | 151103T190008Z | Domino |
| 072 | Whenever | 160218T053332Z | Jerry Je |
| 1614 | Piet | 160215T225634Z | M L |
| nan | beeswax | 160106T235332Z | M L |
| 022 | Ruby | 160216T052236Z | Nirajan |
| 007 | Pylons | 160215T214135Z | Morgan T |
| 012 | DUP | 160208T010128Z | Mama Fun |
| 003 | Simplex v.0.8 | 151103T171603Z | Conor O& |
| 006 | AnnieFlow | 160203T214050Z | Fricativ |
| 016 | CJam | 160204T141108Z | username |
| 049 | HALT | 160204T034951Z | Chathuah |
| 003 | Jelly | 160202T005914Z | Dennis |
| 002 | Detour | 160121T181950Z | Cyoce |
| 007 | Befunge93+ | 160201T224126Z | histocra |
| 087 | Java | 160125T121130Z | senegrom |
| 053 | TrumpScript | 160124T222805Z | J Atkin |
| 035 | Batch | 160125T024440Z | sudoBash |
| 005 | 05AB1E | 160124T114051Z | Adnan |
| 004 | Vitsy | 151103T164633Z | Addison |
| 094 | Pike | 160122T171541Z | cat |
| 033 | Mathematica | 151104T010300Z | LegionMa |
| 010 | Mouse16 | 160118T204204Z | cat |
| 611 | 𝔼𝕊𝕄𝕚𝕟 | 151103T220201Z | Mama Fun |
| nan | 160116T181132Z | Conor O& | |
| 008 | Cardinal | 160107T023400Z | M L |
| 005 | Staq | 160107T014023Z | M L |
| 019 | Turing Machine Code | 160107T013925Z | KoreanwG |
| 045 | Julia | 160107T012237Z | M L |
| 028 | Prolog | 151106T150746Z | Fatalize |
| 3721 | BotEngine | 151103T165322Z | SuperJed |
| nan | BinaryEncoded Golfical | 160103T132812Z | SuperJed |
| 064 | Python 2 | 160103T090037Z | Sidsy |
| 012 | ROOP | 151224T025803Z | DarkPhan |
| 006 | O | 151116T010816Z | jado |
| 095 | Java | 151215T021150Z | Randolph |
| 008 | Mouse2002 | 151215T014023Z | cat |
| 013 | Milky Way 1.0.0 | 151202T142659Z | Zach Gat |
| 031 | STATA | 151208T035909Z | bmarks |
| 021 | Brian & Chuck | 151112T142415Z | Martin E |
| 047 | Groovy | 151103T164316Z | a spaghe |
| 093 | Go | 151201T230635Z | cat |
| 014 | O | 151114T200438Z | Hipe99 |
| 003 | Microscript | 151103T164206Z | a spaghe |
| 004 | Rotor | 151114T160304Z | a spaghe |
| 019 | Arcyóu | 151122T221450Z | jqkul |
| 016 | TeaScript | 151103T214205Z | ETHprodu |
| 023 | Marbelous | 151118T030512Z | TheDocto |
| 022 | Marbelous | 151117T055628Z | Sparr |
| 002 | Motorola MC14500B Machine Code | 151103T174633Z | lirtosia |
| 024 | Aubergine | 151109T071835Z | quintopi |
| 106 | VB.NET | 151115T231124Z | Jens |
| nan | COMMAND.COM | 151104T202946Z | Neil |
| 005 | WTFZOMFG | 151115T051617Z | alephalp |
| 020 | Quipu | 151115T032340Z | alephalp |
| 048 | Squirrel | 151114T201154Z | Laff-O-T |
| 038 | ResPlicate | 151109T054440Z | quintopi |
| 134 | Arnold C | 151112T145501Z | lirtosia |
| 035 | C | 151111T131803Z | ugoren |
| 097 | Java | 151108T175800Z | ESP |
| 007 | DStack | 151111T003057Z | DarkPhan |
| 033 | PHP | 151104T110436Z | insertus |
| nan | Minecraft | 151106T081444Z | Addison |
| 030 | Brainfuck | 151103T182254Z | mbomb007 |
| 119 | LOLCODE | 151109T045322Z | Alex A. |
| 034 | Python 2 | 151109T042157Z | TanMath |
| 003 | Microscript II | 151108T182946Z | SuperJed |
| 034 | Thue | 151103T165530Z | SuperJed |
| 007 | Befunge98 | 151108T043853Z | lirtosia |
| 015 | ><> | 151106T025725Z | clapp |
| 024 | MIPS asm | 151107T010106Z | Kyle G |
| 060 | HSPAL | 151103T184806Z | SuperJed |
| 009 | GolfScript | 151106T182127Z | aditsu q |
| 006 | Burlesque | 151106T151351Z | mroman |
| 031 | FORTH | 151104T233657Z | gaborsch |
| 012 | Haystack | 151105T130612Z | sweerpot |
| 014 | TML | 151105T132612Z | WizardOf |
| 047 | Atari Basic | 151105T115828Z | user9023 |
| 041 | Python 2 | 151104T052831Z | James Mu |
| 046 | Scala | 151105T051829Z | triggerN |
| 020 | AutoHotkey | 151104T232036Z | DanTheMa |
| 006 | APL | 151104T231229Z | user4691 |
| 006 | Hexagony | 151103T195204Z | Martin E |
| 187 | Swift | 151104T135145Z | vrwim |
| 086 | x86 Linux / NASM syntax | 151104T181554Z | Kijewski |
| 048 | VBA | 151104T174800Z | JimmyJaz |
| 020 | Ruby | 151103T171156Z | histocra |
| 006 | ><> | 151103T220015Z | Blake Lo |
| 097 | LaTeX | 151104T123217Z | sweerpot |
| 098 | C# | 151104T082557Z | sweerpot |
| 007 | ><> | 151103T183241Z | Sp3000 |
| 006 | Labyrinth | 151104T145636Z | Martin E |
| 030 | Loader | 151103T170013Z | SuperJed |
| 011 | Math++ | 151103T170830Z | SuperJed |
| 031 | Batch | 151104T135720Z | user2428 |
| 037 | C | 151104T034735Z | cbojar |
| 028 | JavaScript | 151103T212757Z | intrepid |
| 044 | Batch | 151104T100206Z | Fabian S |
| 020 | brainfuck | 151103T223405Z | feersum |
| 010 | PoGo | 151104T084836Z | Fabian S |
| 045 | SWIProlog | 151104T084817Z | DLosc |
| 088 | Ceylon | 151104T080956Z | Paŭlo Eb |
| 054 | Brainfuck | 151103T212153Z | Ethan |
| nan | Perl | 151103T173717Z | a spaghe |
| 037 | ??? | 151104T033401Z | Alex A. |
| 076 | C++ | 151104T015308Z | Tas |
| 016 | Mouse | 151104T025939Z | Alex A. |
| 061 | JavaScript ES6 | 151103T193941Z | Nebula |
| 070 | Lua For windows | 151104T012042Z | Alex All |
| 021 | pb | 151103T223910Z | undergro |
| 032 | JavaScript | 151103T165201Z | ETHprodu |
| 013 | Beam | 151103T182613Z | ETHprodu |
| 029 | Python 2 | 151103T195652Z | xnor |
| 054 | Browser LiveScript | 151103T210646Z | Zane Mar |
| 007 | Ouroboros | 151103T182446Z | DLosc |
| 120 | Java | 151103T184038Z | intrepid |
| 007 | Minkolang | 151103T202002Z | El'e |
| 009 | Stuck | 151103T201449Z | Kade |
| 013 | Bash + GNU utils | 151103T193602Z | Digital |
| 010 | GNU sed | 151103T193243Z | Digital |
| 006 | 3var | 151103T191426Z | Sp3000 |
| 016 | Befunge98 | 151103T185751Z | PurkkaKo |
| 067 | Stack | 151103T190433Z | anOKsqui |
| 008 | TIBASIC | 151103T182931Z | lirtosia |
| 005 | Brainbool | 151103T182546Z | lirtosia |
| 022 | Sisi | 151103T181024Z | DLosc |
| 036 | tinylisp | 151103T180601Z | DLosc |
| 296 | Arnold C | 151103T175458Z | DeleteMe |
| 023 | QBasic | 151103T174434Z | DLosc |
| 005 | Pip | 151103T173848Z | DLosc |
| 009 | APL | 151103T173640Z | marinus |
| 008 | CJam | 151103T164243Z | Martin E |
| 007 | Labyrinth | 151103T172859Z | Sp3000 |
| 035 | Haskell | 151103T164746Z | nimi |
| 039 | C | 151103T172240Z | feersum |
| 093 | AppleScript | 151103T165736Z | Addison |
| 024 | PowerShell | 151103T164306Z | AdmBorkB |
| 030 | Ruby | 151103T165157Z | Peter Le |
| 006 | Foo | 151103T164754Z | Sp3000 |
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.
Bitwise Cyclic Tag, 3 bits or 0.375 bytes
Bitwise Cyclic Tag is one of the simplest Turing-complete languages out there. It works with two bitstrings, the program and the data. The bits of the program are read cyclically and interpreted as follows:
0: Delete the first data bit (and output it, in implementations that have output).1x: If the first data bit is1, appendx(representing either0or1) to the end of the data. (If the first data bit is0, do nothing.)
The program runs until the data string is empty.
Truth-machine
110
When the data string is set to 0:
11does not append anything because the first data bit is not1.0deletes/outputs0.- The data string is now empty and the program halts.
When the data string is set to 1:
11appends a1.0deletes/outputs1.- The data string is back to a single
1and the program is back to where it started, so we loop forever.
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.
8ial, 67 bytes
PUT $1
JIR o $1 1
PSH $1
OUT
JIR e $1 0
;o
PSH $1
OUT
JIR o $1 1
;e
if you know the 67 meme, then just say it.
however i will try to make a 8ial interpreter later that can be encoded to binary
'Python' is not recognized, 17 15 14 bytes
0@?[0|;]jl1|jl
Input "0", Input "1" or anything else
Explanation
0@ " Pushes zero then the input to the stack "
?[...] " Checks if the two TOS's match, if it is... "
0|; jl..jl " ...print 0 and halt, else enter the loop that... "
1| " ...prints the number 1 "
SAKO, 68 bytes
CZYTAJ:I
GDYI=0:1,INACZEJ2
2)TEKST
1
SKOCZDO2
1)TEKST
0
STOP1
KONIEC
I believe this to be an optimal solution.
Piet + ascii-piet, 12 bytes (2×6=12 codels)
tavnsJ dl jj
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
Bespoke, 48 bytes
truth:a machine?fiction or fact
answer:i am true
This is adapted from an example program I bundled with the source code of the official interpreter, but without the trailing CONTROL END (because it's not needed!).
Malbolge, 113 90 bytes
(=BA@?>=<;:381x543,bO/.-,+$)('~g$#"!~=|{zLxwvutWr1p0.--kjihgfI7cF!`_|0\[ZfXWVUNSL5POlMLKig
Do you remember when I was trying to write a short program to produce infinite output? Want to see me do it again? So, as it turns out, my previous printing program can be modified so that it works as a truth-machine... This is not a joke, don't ask me how, don't ask me why, but there was just enough remaining space available in the program to add a small branching that somehow happens in a nop zone of the previous program. This is some Malbolge magic (or should I say devilry?) right there. Like my previous program, it also works with Malbolge Unshackled.
It will be kind of hard to explain how the program works, since it has so many segments now, so I will not explain how the main loop of the program works again, just the branching and the general logic that transformed it into a truth-machine:
jpooooooo
oopopjooo
p <- Start of the program, setting up the main loop
/<ooooop
ooopjoooo
oi <- Retrieves the input, prints it, set up address [72] if 0,
[73] if 1, and goto address
ooo/ooo
oojoio<ii
<ooooooj/
ojiooi/oo
o <- The main loop, the address resetting loop and other values
for crazyops
v <- Address [72], stop the program
oooopopjooiooo <- Address [73], put 1 back into the accumulator
and start loop
<i <- Printing loop
Hatchback, 32 bytes
0 0 0 16 0 1 0 6 0 65281 1 65535
asks for input, prints, checks if its 1 and if it is continue printing.
punchcode, 16 9 bytes
hexdump:
00000000: 16 01 05 1A 1D 0B 11 1E 0D | .........
uncompiled:
-START |
---O-OO-|
-------O|
-----O-O|
---OO-O-|
---OOO-O|
----O-OO|
---O---O|
---OOOO-|
----OO-O|
ibe, 18 bytes
addsQakqasQshQmqmq
explanation: (ibe doesn't support comments so this code is not valid)
ad | initialize 1 item in tape: Q
dsQ | get input and set it to Q
akq | point 0 (aka 'q')
asQ | print Q
shQmqmq | if Q is not equal to 0, go to point 0. (aka, if input is 1 then it will loop forever)
Qdeql, 678 531 273 bytes
&------------------------------------------------\=-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\-=-\/\/==/*/------------------------------------------------\=/=\--\/\/=/*
-147 by computing the ASCII 0 as (0 - 208) rather than putting 48 directly
-258 by computing the ASCII 1 similarly
Explanation:
& get input
---------- ---------- ---------- ---------- -------- subtract 48
\ while not 0:
queue must be 1 0 0 now
= skip the 1
get an ASCII 1:
-==-==-==-==-==-==-==-==-==-==
-==-==-==-==-==-==-==-==-==-==
-==-==-==-==-==-==-==-==-==-==
-==-==-==-==-==-==-==-==-==-==
-==-==-==-==-==-==-==-==-==
\-=-\/\/==/
* print the ASCII 1
/ end while
get an ASCII 0:
---------- ---------- ---------- ---------- --------
\=/= \--\/\/=/
* print it
Motivation is a funny thing. If you had asked me last year if I wanted to write Qdeql code the answer would be no. But I need test cases for my interpreter, and Ørjan's transpiler from Brainfuck generates code that's too verbose to run in a reasonable amount of time.
Boo, 34 bytes
def f(x):
print x;while x:print x
Boo is a language inspired by Python and implemented in .NET. Its syntax is very similar to Python 2's.
Befalse (quirkster), 12 bytes
,!/$.$1!
&?/
, Take a char from stdin
! Jump to enter the loop
$. Print as char and keep it
$1& Dup and Bitwise AND with 1
(! jumps over the newline to keep running on the second line)
? If zero, jump out of the loop
Otherwise, keep running infinitely
Befalse, 15 bytes
,!/$.$\
\?&1/
Same program, but does not exploit any interpreter-specific features/bugs.
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.
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; };
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
><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?<
Intcode, 19 bytes | 8 ints
Everyone's favorite intcode computer from the Advent Of Code 2019.
3,0,4,0,1005,0,2,99
Trilangle, 13 bytes
?!<(@^\<.#^)/
Try it on the online interpreter!
Unfolds to this:
?
! <
( @ ^
\ < . #
^ ) / . .
As in every Trilangle program, control flow starts at the north corner heading southwest. \|/_ reflect control flow, while <^7>vL change the direction conditionally (depending on both the stored value and the direction of the IP).
The IP starts on the red path, where it encounters the following instructions:
?: Read an integer from STDIN!: Write an integer to STDOUT (with trailing newline)(: Decrement\: Redirect control flow<: Branch
Upon reaching the branch instruction, the number inputted will already have been outputted once, and the stored value will be one less than that: -1 if the input is 0, or 0 if the input is 1. The branch instruction proceeds left for negative values and right otherwise.
If the value inputted was 0, the program follows the green path, which immediately hits @ (end program). Otherwise, it follows the blue path:
/: Redirect control flow): Increment, to cancel out the decrement instruction from earlier^: Redirect control flow(Walk off the edge of the board, and wrap around to the southeast corner)
.: No-op#: Skip the next instruction
After encountering #, the IP jumps into the middle of the yellow loop. ! prints out the stored value (1) repeatedly, and the other two characters keep it in the loop.
<^ is not the only combination of control flow manipulators that works. I've found that at least the following pairs also work: <7, <v, <<, L>, ^>, >>. Interestingly, <\ causes it to print every odd number twice (1, 1, 3, 3, 5, 5, ...). All other pairs I've tried exhibit one of three behaviors:
- Loop without hitting
!(e.g.L<) - Exit early, printing out finitely many numbers (e.g.
<_) - Print a couple 1's before going back to the start and waiting for more input (e.g.
<|)
shell, 28 bytes
[ 0 -eq $1 ]&&echo 0||yes 1
><x>, 105 bytes
lddddddddddddddddddddddddddddddddddddddddddddddddn?v
>n<
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.
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.
Desmos, 51 50 45 bytes
o→\left\{i=0:[0],join(1,o!)\right\}
i=0
o=0
Try It Online! (Click the play button on the ticker up top (metronome icon) to run the program)
Desmos doesn't exactly have standard I/O support, but this should get the point across. Input is the i variable, output is the o variable. Each line is a separate expression, and the first expression needs to be in the ticker, as shown in the TIO.
Addendum: at the very least, this output method is accepted by default. Not sure about the input.
EDIT: a surprising -1, apparently → parses properly as an action! Unfortunately, it still costs 3 bytes, which is the same as \to, BUT it allows me to change \to join to →join since the parser gets confused by \tojoin
EDIT: -5 thanks to zygan on discord who showed me that an action itself can be piecewise, and also me realizing that o! is shorter than o^o and doesn't even have to rely on wacky edge case behavior lol
Racket, 58 bytes
#!racket
(let l([n(read)])(print n)(if(= n 0)(void)(l n)))
Explanation
Our program creates a recursive named let statement that loop if n is not equal to 0. On the first iteration, we read user input into n. We print ns value and test whether we should loop or not.
#lang racket
(let loop ([n (read)])
(print n)
(if (= n 0)
(void)
(loop n)))
ForWhile, 28 bytes
ForWhile does not have infinite loops, so to output indefinitely the program has to continuously copy its source code behind the instruction pointer.
_:49=[{}1+20[:@;20-$1-:)'#]#
Explanation
_ \ read a character from standard input
:49= \ check if it is one
[ ]# \ if the character is not one, print it
{}1+20[:@;20-$1-:)'# \ infinite 'loop'
{} \ get the current instruction pointer (empty procedure)
1+ \ offset instruction pointer such that it points to start of code block
20[:@;20-$1-:) \ copy code starting at { to position after #
'# \ print the second value on the stack (the character read from standard input)
ForWhile, 42 bytes
This version has constant memory usage
_:49=[34(!;$1-]{}10+:34[:@;34-$1-:)49#$.]#
it works similarly to the shorter version, but additionally deletes the old code and cleans up the stack
AArch64 machine code + Linux syscalls, 40 bytes
00: 528007e8 mov w8, #63 // read()
04: 2a1f03e0 mov w0, wzr // 0 = stdin
08: 910003e1 mov x1, sp // to stack
0c: d2800022 mov x2, #1 // 1 byte
10: d4000001 svc #0 // syscall, should mov x0, #1
14: 394003e9 ldrb w9, [sp] // load byte
18: 52800808 mov w8, #64 // write()
1c: d4000001 svc #0 // syscall, w0 = 1 = stdout
20: 3707ffe9 tbnz w9, #0, 1c // loop last instruction if byte & 1
24: d65f03c0 ret
Can be used as a void (void), or an int (void) such as main(), returning 1.
If you want to use it as _start() without segfaults, replace the ret with:
24: 52800ba8 mov w8, #93 // exit()
28: d4000001 svc #0 // syscall
(,), 46 bytes
((),(((()))(())),,,(),,((())))(,,(()),,((())))
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
(,) 63 Chars or \$63\log_{256}(3)\approx\$ 12.48 Bytes
This was quite fun, kudos to Dadsdy for creating this language!
((),((())))(()(),(()())()(),,,(()),(()()))(,,,(()),(()()),(()))
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.
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
x86 machine code, PC DOS, 10 bytes
00000000: a082 00cd 293c 3174 fac3 ....)<1t..
Listing
A0 0082 MOV AL, DS:[82H] ; AL = first char from command line
DISPLAY:
CD 29 INT 29H ; DOS fast write AL to console
3C 31 CMP AL, '1' ; was input a '1'?
74 FA JE DISPLAY ; if so, loop "forever"
C3 RET
Sample output
A standalone DOS .COM program.
A>TRUTH.COM 0
0
A>TRUTH.COM 1
111111111111111111111111111111111111111111111111111111111111111111111111111111
111111111111111111111111111111111111111111111111111111111111111111111111111111
111111111111111111111111111111111111111111111111111111111111111111111111111111
111111111111111
(ended because Ctrl-Break was hit)
Note: shouldn't ever crash or run out of memory since no memory is used. More likely it'll just burn a permanent screen full of 1's onto your IBM 5151 monochrome CRT monitor (so in a sense it will run forever).
hyperscript, 39 bytes
init log prompt()repeat while it log it
Full program
hyperscript, 44 bytes
def f(n)repeat while n>0 log n end log n end
Function
<script src="https://unpkg.com/hyperscript.org@0.9.8"></script>
<script type="text/hyperscript">
def f(n)repeat while n>0 log n end log n
</script>
<label style="font-family:monospace">n: <input type="number"style="font-size:1.5rem;width:4.5ch"_="on change call f(my value)" /></label>
(Note: it will crash if you give it 1)
AFAIK hyperscript can't take input from STDIN, so I'm using a function instead.
Ungolfed:
def f(n)
repeat while n > 0
log n
end
log n
end
Desmoslang Assembly, 12 Bytes
7+2*IJTGE1TO
Thunno 2, 2 bytes
(ß
# implicit input
( # while TOS is not 0:
ß # print without popping
# implicit output
Nekomata, 2 bytes
ᶦP
ᶦ Iterate the following function zero or more times until it fails
P Check if the input is positive
Google Forms, 3 sections + 1 question
Google Forms has two features which I believe make it qualify as a (very limited) programming language:
- Multiple sections, which allow arbitrary rules for which sections redirect to which, allowing for uncontrolled infinite loops
- The ability to make different responses to a question take the user to a different section upon clicking "next", allowing for input/conditionals, and controlling loops based on input
Google Forms also has a back button, which may make it possible to store arbitrarily large amounts of information, though there's no way to make use of that information without the human running the program doing something.
Thunno, \$ 6 \log_{256}(96) \approx \$ 5 bytes
(actually 4.94 bytes, but the leaderboard doesn't take floats)
!)[1ZK
(No ATO link since that's on an outdated version)
Explanation
!)[1ZK # Implicit input
! # Push `not input` (i.e., 1 if input == 0; 0 if input == 1)
) # Break if the top of the stack is truthy (i.e. input == 0)
# Since the stack is filled with 0s at the start, 0 is implicitly output in this case
[ # while True:
1ZK # print 1
nroff/troff, 27 bytes
Ties with user100411's 27 bytes answer. This version, however, does REALLY outputs 1's FOREVER for input 1, while previous version halts by stack overflow.
.de a
\\$1
.while \\$1 1
..
Usage
.a 0
.a 1
ArcPlus, 22 bytes
(: n (,))(@ (p n) (p n
Verbose version:
(set n (input))
(while (print n) (print n))
Prolog (SWI), 28 bytes
:-get(X),repeat,put(X),X=48.
Gets a single character, then repeatedly print it, stopping if it is a zero.
Leaf-Lang, 43 Bytes
Note: Link to interpreter is liked above.
code:
input toNumber 1=while 1 print stop 0 print
Brainfuck, 5 Bytes
,.[.]
I/O is as 0x00 / 0x01 bytes.
I just think it's a neat thing.
K (ngn/k), 13 bytes
{x}{ \x}/.1:0
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.
Shell (posix), 26 bytes (code) + 1 (input) = 27 bytes
run:
$ ./<name> <1 or 0>
code:
[ $1 = 1 ]&&yes 1||echo 0
Explained:
[ $1 = 1 ] is a hacky way of evaluating if argv[1] is equal to 1
in bash && executes if the previous command finishes with exit code 0
yes 1 yes is a command that takes in a string and prints continually to stdout
in bash || executes if the previous command finishes with a non-zero exit code
echo 0 self explainatory.
Old versions
[ $1 -eq 1 ]&&yes 1||echo 0
[ $1 == 1 ]&&yes 1||echo 0
Fig, \$4\log_{256}(96)\approx\$ 3.292 bytes
?x(;
See the README to see how to run this
The ? could be replaced with a ! for the same effect.
?x(; # The program
? # If
x # The input is truthy (i.e. 1)
(; # Print the input forever
# Otherwise print the condition (which was 0)
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)
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.
A0A0, 67 bytes
I0S1M2V0G0
G-1G-1G-1G-1
O0
A0A0
A0C3G1G1A0
A0O1A0
A0A1G-3G-3A0
G-3
The top line takes input, then adds one to this number and multiplies it by two. For input 0 we now have 2 and for input 1 we have 4. This is used as the offset for the goto instruction. If we jump by two we end up at line three which prints zero and halts. If we jump by four, we get to line five and get to an fininite loop.
A0 A0
A0 C3 G1 G1 A0
A0 O1 A0
A0 A1 G-3 G-3 A0
G-3
This infinite loop simply prints one (on the third line in the loop: O1).
SMALL, 14 bytes
$->x{x=1?1!}0!
Ungolfed code:
$ -> x
{
x = 1?
1!
}
0!
We first read from stdin and store the input in x, with the following line.
$->x
We then enter an iteration, where we first compare if x is 1. If that's the case, we print 1. Since this check will never be false, this iteration will be infinite.
{
x = 1?
1!
}
If the condition in this iteration is false, the entire iteration stops and we go to the last line, which prints a single zero after which the program halts.
0!
Applesoft BASIC, 28 26 bytes
1INPUTA
2PRINTA
3IFA GOTO2
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.
PostScript, 36 bytes
.runstdin 0 eq{0 =}{{1 =}loop}ifelse
Probably needs to be run through ghostscript to get the .runstdin operator.
tinylisp, 31 bytes
(d A(q((N)(i N(A(c 1(disp 1)))0
Defines a function A that takes the required input, as tinylisp has no concept of program input.
Plumber, 28 20 bytes
[]
=]]][=[]
][=[][
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.
10IPL, 34 bytes
11001000 01001100 00100010 10100001 10100100 00100010 10100001 10100100 00100010 10100001 10100100 00100010 10100001 10100100 00100010 10100001 10100100 00100010 10100001 10100100 00100010 10100001 00100010 00011010 00101010 00101010 00101010 00101010 00101010 00000100 00000100 00000100 00110010 11110000
Program:
; input
inp rp0
; r1
xor r1, rp0
; rp0 OR r1
rtr r1
nor rp0, r1
nor rp0, rp0
rtr r1
nor rp0, r1
nor rp0, rp0
rtr r1
nor rp0, r1
nor rp0, rp0
rtr r1
nor rp0, r1
nor rp0, rp0
rtr r1
nor rp0, r1
nor rp0, rp0
rtr r1
nor rp0, r1
nor rp0, rp0
rtr r1
nor rp0, r1
rtr r1
; pointer
inr rp1
rtr rp1
rtr rp1
rtr rp1
rtr rp1
rtr rp1
zro r2
zro r2
zro r2
; print
prt r1
; jump
jmp
What is 10IPL?
10IPL, short for 10 Instruction Programming Language, is a simple compiled language I made for use in a computer I'm building in Minecraft. I made an online interpreter for it (with a few extra features), since I think it's a neat language.
How does this work?
This program consists of a few parts:
- Take input
- Set
rp0(the upper 8 bits of a pointer) to either00000000(if the input is truthy) or11111111(if the input is falsy) - Set
rp1(the lower 8 bits of the pointer) to point to theprtinstruction after it - Print the inputted value
- Jump to the pointer
This will jump into a few KiB of zeroed out RAM if the input is 00000000, then terminate. Otherwise, it keep going forever. Don't try it online.
dotcomma, 8 bytes
[,].[.,]
Dotcomma is a language I recently invented, designed to do things in an interesting way with as few instructions as possible. In order to accomplish this, there are two operators (predictably . and ,) which can do entirely different things depending on context. This answer's explanation will be very introductory. To see some more complicated code, check out the examples in the page linked in the title.
This program is actually a pretty neat showcase of some of the more interesting features of dotcomma. You'll notice it's divides into two main parts, [,] and [.,], separated by a .. These are called blocks. Every block and operator has a return value.
The way dotcomma manages to do so many different things with each operator is by changing what they do based on what precedes and follows them. Take the , in the first block. Because it is at the start of a block, its return value will be a value taken from input. Because it is at the end of a block, it will also output this value and use it as the block's return value. Surprisingly compact for a language with four valid characters!
As for the first ., because it is preceded by a block, it will take the block's return value and use it as its own. It is followed by another block, so it will do one two things: if its return value is 0, the block will be skipped. Thus, only 0 will be outputted and the program will terminate.
However, if its return value is 1, the block will be looped. Within the block are two operators: .,. The . will have a return value of 1, as it follows the beginning of a block. The , will behave similarly to the first one, but instead of taking the number to be outputted from input, it will take it from the . (which will always be 1). The loop will run forever because the , will always set the looped block's return value to 1.
Hopefully this explanation isn't too confusing!
Desmos, 33 bytes
n->ni+1,o->[1...n]0+i
i=0
o=0
n=0
The top line goes in a ticker, while the other lines are regular equations.
The input goes in variable i, while the output is shown in variable o.
Press the ticker (metronome icon) to start running the code.
Explanation
n->ni+1: If i=0, it becomes n->1, so n will always stay at 1. If i=1, it becomes n->n+1, so n will infinitely increment by 1.
o->[1...n]0+i: [1...n]0 creates a list of zeroes with length n. As shown with n->ni+1, if i=0, the length will always stay at 1; otherwise, it will keep increasing. +i simply converts the list of zeroes to a list of i's. So in summary, if i=0, then the list stays at length 1 and is populated with 0's. If i=1, then the list length is always increasing and is populated with 1's.
The rest of the code: It is simply to define the variables used in the actions above.
AHHH, 24 bytes
AHHHHhHHhhHHHHHHhhHHhhhh
AHHH is a somewhat more capable BF derivative in which every program consists of screaming.
Explanation
AHHH Begin program
HhHH Read int into current cell
hhHH Write current cell's value as int
HHHH Loop while current cell is not zero
hhHH Write current cell's value as int
hhhh End loop
APOL, 34 16 bytes
My original version was written back when I first made APOL and used none of the newer convenience instructions.
¿(⧣ w(T p(1)) 0)
Explanation
¿( Returning if
⧣ Integer input (used as condition, 0 evaluates to false)
w(T While true (true condition)
p(1) Print 1
)
0 A literal 0 (false condition)
)
Implicit print (¿ returns 0 if input is 0)
Batch, 28 bytes
:1
@Echo(%1&Goto:%1
:0
uses input as output and script flow controller.
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:
,.[->+>+<<]>[-[<<]>[.]>-]
,.[->+>+<<]>[-[>>]>[.]<<<-]
INTERCAL, 41 bytes
Based on answer by @unrelatedstring. If you don't care for errors, won't you guys golf off the program easily?
DOWRITEIN.1DOCOMEFROM.1(1)PLEASEREADOUT.1
BASH
read a; [ $a -eq 0 ] && echo 0 || ( [ $a -eq 1 ] && while true; do echo 1; done )
Pure Bash, 32 + 1 = 33 bytes
The 1-byte penalty is for filename specification; the following program must be saved as x.
((x))||read x
echo $x
((x))&&. x
Tracing how it works
- The variable x is not initialized.
((x))evaluates to((0)): command is failure.- So
read xis done. - Then
echo $x. - Final line is for branching.
- If
xis zero, the program ends. - If
xis one,. xis done.- It loads the file
x: the program itself. - First command evaluates to
((1))so no morereading. - Then rest two lines are executed and it loops forever.
- It loads the file
- If
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.
Pure CPython 3.10 bytecode, 6 bytes
"Pure" means no constants and no names are allowed. As a result, the only method of input is by starting with values on the stack.
...and Python bytecode's only way to jump backwards (and therefore the only way to loop) uses "absolute" addressing, so my code assumes it is placed starting at instruction offset 3 (byte offset 6).
Hex of code: 04 00 46 00 70 03
Disassembly of code:
>> 6 DUP_TOP
8 PRINT_EXPR
10 JUMP_IF_TRUE_OR_POP 3 (to 6)
Takes an integer on the stack. The easiest way to put 0 or 1 on the stack is:
0 LOAD_ASSERTION_ERROR
2 BUILD_TUPLE X
4 GET_LEN
Change X to 0 or 1. In hex, this is 4a 00 66 00 1e 00 (for 1) or 4a 00 66 01 1e 00 (for 0).
This will crash the interpreter for an input of 0 due to a buffer overflow. If this is not acceptable, add 2 bytes (append 53 00 (RETURN_VALUE)).
I'm going to use this opportunity to explain how CPython bytecode works. It's just an array of bytes, which are in opcode, oparg pairs.
For example, (hex) 01 02 03 04 is instruction_01(arg=02); instruction_03(arg=04).
The list of instructions is given in the documentation for the standard library dis module, although you sometimes need to dig about in Python's ceval.c to see exactly how they work.
In Python, bytecode is contained in a code object, which carries some metadata like source file lines, but the most important things are an array of constants (co_consts) and an array of names (co_names). In order to load a literal value, it must be loaded from co_consts; in order to lookup a global variable, its name must be in co_names. When I said I'm using "pure" bytecode, I mean that these arrays are both empty - so I can't use any literals (integers, strings, tuples, etc.), and I can't use any global variables, builtins, imports, or even look up any attributes. This allows an extremely minimal wrapper script (see the ATO link).
This leaves me with only PRINT_EXPR for output (or leaving a value on the stack), and no input at all other than taking a value already on the stack.
The truth machine is actually the easy part of this code, to be honest: it's essentially do { print x } while (x).
Loading an integer is a bit more involved: first I use LOAD_ASSERTION_ERROR to put a value on the stack. What value it is doesn't particularly matter, but this is one of only a few instructions I'm aware of that can load an object without any consts.
Then I use BUILD_TUPLE(1) to make the tuple (AssertionError,), and take its length with GET_LEN which is 1. To load 0 is a bit simpler: you only need
0 BUILD_TUPLE 0
2 GET_LEN
Although you can perfectly well leave the LOAD_ASSERTION_ERROR before that, to conveniently switch between loading 0 and 1.
Sidenote
GET_LEN is new in Python 3.10, so a historic method would have had to involve boolean <-> integer conversion, which is a bit more interesting IMO:
0 LOAD_ASSERTION_ERROR
2 DUP_TOP
4 IS_OP 0
6 DUP_TOP
8 BINARY_MULTIPLY
10 PRINT_EXPR
This performs AssertionError is AssertionError, which is True. Then it does True * True to get the integer 1.
IS_OP(0) can be replaced with IS_OP(1) to do AssertionError is not AssertionError, which gives False, which gives 0.
Hello Hell, 34 bytes
[+^-/>]!*/*/>[+^>][+-/<]-/<[{*+}/]
The first program in my new language - Hello Hell! For information on the commands, memory model, etc. check out the repo.
Explanation:
[+^-/>] # Set the first 6 cells to 0
! # Input
*/*/ # Set the cell to 0 or 49 depending on input
>[+^>] # Move to the 13th cell
[+-/<]-/< # Set cells 8-13 to 0
[{*+} ] # If 1, loop forever,
/ # otherwise print 0
Python 3, 35 34 bytes
def l(i):
if i:print(i);l(int(i))
Older python 3.8 only code
i=input()
while i:print(i:=int(i))
Explination:
While this ties the best python 3 answer thanks xnor for saving me a byte
This uses a few interesting properties to achieve what it does:
The input received is always a string when from a user input, thus the while-loop will start regardless if its a 1 or 0
Inside the loop, we print the number for the first time, and simultaneously using the walrus operator which was introduced in python 3.8, we assign the integer value to i.Using recursion, this code can now work in all versions of python 3, while it isn't a major improvement in bytes count, I'd still count making the code work in more versions an improvement!Now, the value, if zero, is now converted from "0" to 0, meaning the loop will exit, otherwise if its 1, it keeps going!
I have tried hard to get lambdas to work, but every attempt ended up with more lines due to having to use recursion, if anyone has any ideas I am all ears! Meanwhile I will try to keep pushing this, the new version feels like it has more that can be pushed
Clam, 11 8 bytes
p=QrwQpQ
-3 bytes thanks to the Q global variable
Storing variables is a tad verbose in Clam...
Explanation
p=QrwQpQ
p Print..
= Assignment..
Q Global variable Q
r Read next line of STDIN (automatically parsed to int if possible)
w While..
Q Q is truthy
pQ Print Q
Resulting JS code:
console.log(Q = arguments[0]);
while(Q) {
console.log(Q);
}
Braingolf, 5 bytes
[!_];
Explanation
[!_]; Implicit input
[..] Do-while, run once and loop while top of stack is >0
!_ Print top of stack without popping
; Prevent implicit output
Arduino, 133 129 117 bytes
Thanks to @tail spark rabbit ear for shaving off 12 bytes!
#define S Serial
int x=0;void setup(){S.begin(300);}void loop(){S.available()&&S.print(x=S.read()-48);x&&S.print(1);}
Arduino is basically C++, but with this bit implied:
int main() {
setup();
while (true) {
loop();
}
return 0; // to make the compiler happy, I guess
}
The setup() and loop() functions must be implemented.
Explanation:
#define S Serial /* macro to make referencing the Serial monitor shorter */
int x = 0; // must either be global, or declared `static` inside `loop()`
void setup() {
S.begin(300);
// The argument to Serial.begin() is the baud rate
// 300 is the slowest supported option, but therefore takes the fewest bytes
}
void loop() {
S.available() &&
// Serial.available() returns truthy when there are unread bytes from the serial input
// Using && as a shortcut for an if statement (like minified JS)
S.print(
x = S.read() - 48
);
// Serial.read() dequeues the next byte from the input
// 48 is ASCII '0'
// Serial.print() converts 0 back to "0"; Serial.write() wouldn't
x &&
S.print(1);
}
As loop() is called indefinitely, it's impossible to terminate, so inputting "0" settles into a loop that prints nothing until something else is input.
Original:
int x=0;void setup(){Serial.begin(300);}void loop(){if(Serial.available()){x=Serial.read()-48;Serial.print(x);}if(x)Serial.print(1);}
Perl -p, with the following restrictions ppencode, 15 bytes.
-p, with the following restrictionsUse only keywords with lowercase alphabets onlySeparate each of them with just a space
print while sin
How it works
sin(0)is zerosin(1)is not zero-pis for implicit I/O for line by line
Alternatives
sin can be replaced with one of following keywords:
abs int oct hex
Nim-Lang, 72, 64, 49, 41 (credits to @hyper-neutrino and @Jo King) bytes
var a=readChar(stdin)
while a=='1':echo 1
echo 0
Version with if-statement, with suggested edits:
if readChar(stdin)=='0':echo 0
else:
while true:echo 1
Mascarpone, 18.125 bytes
['1.:!]v*['0.]v*1[:!]v*'1<,>!
I'm surprised to see so few Mascarpone answers even on the big questions like this. It's a shame, it's such a beautiful language even if it is a bit of a tarpit.
Dis, 49 bytes.
}{*|*^__________!||_^_____________*{___^___****!*
Usage
- Input from STDIN, as an ASCII number character.
- Output to STDOUT, in ASCII.
With comments
(
0: }{*|*^
'*'+1: ****!*
'*'+1: * changed to 48-42or49-42 by |:
12 10t - 11 20t is 01 20t is 15
12 11t - 11 20t is 01 21t is 16
'*'+2: * for * command
'*'+1: 15or16 for ^
15+1: ! reaches when zero
16+1: ||^ reaches when one
obtw '*'+3: * and '*'+4: * are for | to have the register A have 49 again
'*'+5: ! for ^
After that '*'+4: '1' BUT whatever
'!'+1: *{___^ repeatedly output one
* 42 ! 33
)
(
0123456789 0123456789 0123456789 0123456789
)
}{*|*^____ ______!||_ ^_________ ____*{___^
(
0123456789 0123456789 0123456789 0123456789
)
___****!*
yuno, 4 bytes
ᴀ_¹¿
Or, using the flag to disable implicit output:
yuno d, 3 bytes
ᴀ_¿
Explanation
The W flag caps output at 10,000 characters just so it doesn't freeze your browser window for too long.
ᴀ_¹¿ Main Link
¿ While
¹ The element is truthy
ᴀ_ Output it
<Implicitly output the value>
ᴀ_¿ Main Link
¿ While
ᴀ_ Output the element, then assess if it's truthy
<d flag disables implicit output>
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.
Squire, 47 bytes
x=inquire()whence l proclaim(x+" ")if"0"!=x{l:}
Whilst some languages have a goto keyword, Squire useth whence, the opposite. One might call it a comefrom. Squire also containeth a normal loop with whilst, but alas, it is impossible to useth this without enscribing proclaim twice.
If we accompany whence with if, we can create a loop that some call do-whilst.
Ungolfeth:
# Inquire a line from ye standard input
x = inquire()
# Set a whence point
whence loop
# Proclaim x, followed by a space, to ye standard output
proclaim(x + " ")
# If x is not "0"
if "0" != x {
# Loopeth ad infinitum
loop:
}
Methinks this language is ridiculous. 😂
Ocaml, 46 bytes
let a=read_int()in while print_int a;a=1 do 0
urk the functions name and the control flow takes a lot of chars. The trick since there is no do-while is to put the print directly in the condition (sometime ago when I did that in a course lab, the teach called me a "connoisseur of monstrosities" (approx tl))
The 0 in the end causes a warning, so you need to disable werror.
Red, 28 bytes
func[a][until[prin a a = 0]]
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.
Piet, 12 codels
Codel size 16:
Instructions:
INN
DUP (start)
DUP
OUTN
PTR (back to start if 1; continue if 0)
POP
It has the following behavior for other values:
- if
n % 4 == 1, print n forever - else, print n once and terminate
if n % 4 == 2, there will be a stack underflow error, as the code path is as follows:
INN
DUP
DUP
OUTN
PTR
SWITCH (empties the stack)
PTR (error)
POP (error)
2D Deadfish, 7 bytes
(o^)>o<
It is a new 2D esolang based on Deadfish~ I made recently. Read more on it in the link in header.
Explanation
IP starts at the beginning with direction right. Statements inside parentheses is only executed if accumulator is 0. And input is set to the accumulator, or else 0.
So if you give input 0,
- Parentheses block will start
owill output accumulator (which is 0)^will change direction to up- It will eventually hit EOF token
- And terminate soon!
And for input 1,
- Skip the parentheses and jump to
> >changes direction to right (It keeps moving right)ooutputs accumulator (which is 1)<changes direction to left (back)ooutputs 1 again>changes direction to right- IP dances and repeats outputting 1
How to run it?
No online interpreter for now. but coming soon.
Until then clone the repo, and run interpreter.py. It will prompt you for the program first. When done typing program, hit CTRL+D (linux) or CTRL+Z (windows). And provide your input (if you don't want to give keep it blank) and hit enter. The program will start to run.
Barrel, 10 bytes
This makes use of the fact that the input will be only 0 or 1:
λn?a:#∞n
Explanation:
λ // input into the accumulator
n // print the accumulator
? : // if-else statement (auto-closes to '?a:#∞n::')
a // if the accumulator evaluates to truthy (i.e. non-zero)...
#∞ // ...loop forever...
n // ...implicitly print the accumulator...
// ...else do nothing
In other news, I really should make a custom charmap for barrel. With a custom charmap, I could shave off 3 bytes.
Knight, 13 11 bytes
New method with suggestions from the language's author:
I+0P W1O1O0
# Read a string, coerce to number by adding 0, and check if non-zero
: IF (+ 0 PROMPT) {
# if it was non-zero, loop printing 1 forever
: WHILE 1 {
: OUTPUT 1
}
# else output 0 and exit.
{
: OUTPUT 0
}
Old version which I wrote on my own:
;=wP;W+0wO1O0
There are a few ways to do this. Decided this way because of a certain theme.
Ungolfed version:
# Read string into input
; = input PROMPT
# Coerce input to a number by adding 0, and loop while not 0
; WHILE (+ 0 input) {
# Output 1 and a new line
: OUTPUT 1
# this is an infinite loop
}
# Otherwise, output 0 and a new line, and quit
: OUTPUT 0
If we allow excess newlines, this is an arguably superior program:
;=wP;W+0wOwOw
However, this prints two new lines because PROMPT includes the trailing newline. 😔
Stax, 4 bytes
Wq|c
W - loop over rest of program forever
q - print without popping, with no newline
|c - exit if value at the top of stack is truthy without popping
Subleq (8-bit), 15 bytes
-1 15 3
15 16 6
15 -1 -48
16 8 -1
15 8 6
Explanation
0: -1 15 3Input character to 15:, goto 33: 15 16 616: = 16: - 15: (16: = -15), goto 66: 15 -1 -48Output 15: (-48 is unused in instruction and used for memory)9: 16 8 -18: = 8: - 16: , if 8: <= 0 exit; exit for all characters "0" and before12: 15 8 68: = 8: - 15: (back to -48), if 8: <= 0 goto 6
Starry, 16 bytes
, +'. '` +. +' `
Pretty simple, it reads the input onto the stack, if it's zero, it prints it, and if it's non-zero, prints it forever.
Duocentehexaquinquagesimal, 2 bytes
RÃ
Try it online! Takes input as a character, and outputs in unary using characters.
Pxem, 0 bytes (content) + 13 bytes (filename).
Filename is:
._.c.n.w1.o.a
As verbose pseudocode
push numeircal integer input
dup
unless empty: printf "%d", $(pop)
while one of
1. empty
2. $(pop) != 0
do
push "1", a character
unless empty: printf "%c", $(pop)
done
CASL II, 72 bytes.
A START
IN B,1
D OUT B,1
LAD GR1,48
XOR GR1,B
JNZ D
RET
B DS 1
END
If you are familiar with assembly languages, you would get it well. It uses standard i/o. It uses ASCII-compatible encoding.
CSASM v2.3.1, 54 bytes
func main:
in ""
conv i32
.lbl a
dup
dup
print
brtrue a
ret
end
Explanation:
func main:
; Get the input and convert it to an integer
in ""
conv i32
.lbl a
; Duplicate the input twice
; Both the "print" and "brtrue" instructions pop a value from the stack
; so this is necessary to keep a 1 on the stack when looping
dup
dup
print
; Truthy values are a non-zero integer or a non-null object
brtrue a
ret
end
Pinecone, 41 bytes
n:"".input;n="1"?(tru@print:1)|(print:0)
V (vim), 18 13 bytes
xqqp/1
@qq@qx
Somehow, there was no existing vim answer for this. I was happy to oblige.
-5 bytes from Aaron Miller.
Explanation
xqqp/1
x delete the input char
qq start macro q
p paste the input
/1 find 1 (exits if 0 isn't matched)
@qq@qx
@q recursively call macro q
q end macro q
@q call macro q
x delete last char (never gets executed in the case of 1)
Grok, 10 bytes
:}1j
z}zhq
Explanation:
:} # If input is 0, goes down and to the left, outputs 0,
z} q wraps to the right, and terminates.
:}1j # If input is non-zero, goes to the right, pushes 1,
}zh prints 1, and loops indefinitely.
Python - 40 bytes
a=int(input())
while a:
print(a)
print(a)
This is simple but effective. A fun thing about this is that while we could put a condition that a==1 in, this is more fun because it reuses a, and a will be 1 causing the loop to run forever (works with any a != 0)
x86_16 machine code - 20 bytes
3E A0 82 00 MOV AL, DS:[82H]
8A D0 MOV DL, AL
_LOOP:
B4 02 MOV AH, 02H
CD 21 INT 21H
80 FA 31 CMP DL, "1"
74 F7 JZ _LOOP
B8 00 4C MOV AX, 4C00H
CD 21 INT 21H
Tested in DOSBox :
Input 0
Input 1
If input 1 gives infinite loop
Python 3, 47 bytes
Not a winner, but I like the method.
set(iter(lambda x=input():(print(x),x)[1],'0'))
Built-out, 5 bytes
truth
Yay, built-ins! ...just kidding.
Before running: push input to stack 2
truth
t - not last 't': swap stacks 1 and 2
r - convert character (1-9) at top of stack 1 to integer
u - toggle EOF loop if top item of stack 1 is falsy (0)
h - duplicate top of stack 1
- implicit: pop item of stack 1 if not empty, then go to previous 't' if stack 1 is still not empty AND 'u' did not toggle it off, terminate otherwise
t - last 't': return here if stack 1 is not empty
Try it online! (fork the project)
v³, 6 bytes
;@=.$#
Unwrapped:
;
@ = . $
#
The IP starts at the top cell. ; takes the input as a numeric value. The IP then falls to =, printing the value. It hits ground (#) and starts moving to the right. . is a no-op. $ ignores the next command if the value is not zero. The IP wraps around to @, which terminates the program. The program repeats from = if it hasn't terminated.
convey, 10 bytes
{,!"}
>"^
There's a few ten-byters i've found, but I can't see any way to get lower. I was thinking of this. but unfortunately that doesn't parse.
BRASCA, 11 bytes
x48S-:n[:n]
Explanation
<implicit input> - Take input from STDIN
x - Clean up the linefeed from STDIN
48S- - Remove 48 from the digit's ascii code
:n - Output the number
[:n] - While non-zero: Output the number
Language Link
Python 3, 35 bytes
n=input()
while 1:print(n);0/int(n)
05AB1E, 3 bytes
i[?
i[? # full program
i # if...
# implicit input...
i # is 1...
? # output...
# implicit output...
? # without trailing newline...
[ # forever
# implicit end loop
# implicit end if
# implicit output
Fugue, 120 bytes
00000000: 4d54 6864 0000 0006 0001 0002 0001 4d54 MThd..........MT
00000010: 726b 0000 002b 0090 4040 0290 3e40 0190 rk...+..@@..>@..
00000020: 3a40 0090 4040 0190 4740 0190 4340 0090 :@..@@..G@..C@..
00000030: 4440 0190 3e40 0190 3740 0190 3740 00ff D@..>@..7@..7@..
00000040: 2f4d 5472 6b00 0000 2f00 9040 4001 9037 /MTrk.../..@@..7
00000050: 4001 903f 4001 9040 4002 903c 4000 9044 @..?@..@@..<@..D
00000060: 4001 903e 4002 9045 4001 9046 4001 904e @..>@..E@..F@..N
00000070: 4001 9047 4000 ff2f @..G@../
Since the Fugue compiler does not support voice wrapping, a direct translation of Martin Ender's Prelude answer turns out to not be the shortest possible solution. This program is equivalent to the Prelude program:
v6(1-)#
?!^ 8- (^!)
See my Hello World answer for more information on how to use the compiler. Finally, here's a valid MIDI version of the program:
00000000: 4d54 6864 0000 0006 0001 0002 0001 4d54 MThd..........MT
00000010: 726b 0000 002c 0090 4040 0290 3e40 0190 rk...,..@@..>@..
00000020: 3a40 0090 4040 0190 4740 0190 4340 0090 :@..@@..G@..C@..
00000030: 4440 0190 3e40 0190 3740 0190 3740 00ff D@..>@..7@..7@..
00000040: 2f00 4d54 726b 0000 0030 0090 4040 0190 /.MTrk...0..@@..
00000050: 3740 0190 3f40 0190 4040 0290 3c40 0090 7@..?@..@@..<@..
00000060: 4440 0190 3e40 0290 4540 0190 4640 0190 D@..>@..E@..F@..
00000070: 4e40 0190 4740 00ff 2f00 N@..G@../.
Prelude, 6 bytes
Prelude is a bit tricky here. The language specification says I/O is via characters' byte values. That's what the C implementation does. Then there's the Python interpreter, which uses bytes for input but prints decimal integers. And then there's my own fork of that interpreter which does both input and output numerically (which I've published a few months ago). Since languages on PPCG are defined by their implementations, all of these constitute valid Prelude variants.
My fork gives the shortest solution at 6 bytes:
?(1!)!
? pushes the input. (...) is a Brainfuck-style while loop, which is skipped for 0 input. Then ! prints the zero. If the input was 1, we enter the loop, push another 1 and print that with ! (we need to push a new 1, because ! pops the top of the stack).
Next up is the original Python interpreter at 14 bytes:
?6^+^+^+-(1!)!
Since output is the same as in my fork, all we need to do is map the character codes to 0 or 1 which we do by subtracting 48. There are several ways to get 48 in 7 bytes, but I don't think it's possible to do it in less. This one pushes 6 and then doubles it 3 times, by duplicating it with ^ and adding the two copies with +.
Finally, the solution that works with the original C interpreter needs 16 bytes:
?^(#^!^6^+^+^+-)
This one has a slightly different structure. Since we also need to output 48 or 49 respectively, we now remember the input and obtain the 0 or 1 only for the loop condition. This also let's us get a way with a single ! because we can easily turn the loop into do-while. Again, ? reads the input and ^ makes a copy which we only need because the first thing in the loop is #, which discards the top of the stack (we need this to discard the condition from a previous iteration). Now ^! prints a copy of the input. Then ^6^+^+^+- computes input - 48 as before. If that is 0, we leave the loop immediately and exit after printing a single number. Otherwise, the loop will keep going, printing the input 49 each time.
NDBall, 57 chars, 8 cells in 2 dimentions
(0)>0
(1)%
(2)Y[1,>0,>1]
(3)P
(4)E
(2,1)>1
(2,2)P
(2,3)<1
Visual representation of code (hand made by me)
Checked in NDBallSim V1.0.1
MarioLang, 25 bytes
>:<
"==
;[!:
===#=
Acrostic, 89 45 bytes
-44 bytes by running the initial input command backwards to output the zero (thanks Jo King for the idea!).
R
DOUBLE
N A
PROVIDED
R
I
NIL
T
END
D
Try it online...? (This esolang has no official online interpreter; that link takes you to a repl.it link with my own unofficial Python interpreter loaded in, complete with the truth machine program. If I can find/make a more proper online interpreter, I'll link that instead.)
Acrostic is an esolang designed by Mercerenies for which programs take the form of crosswords, which are traversed word-by-word during program execution.
First, END is run backwards, which starts the program. PRINTED is then run backwards, which will take a numerical input and push it onto the stack. If the top of the stack is 0, the PROVIDED branch is not taken, and instead NIL is run (which does nothing). Because there are no other words to run from there, PRINTED is executed forwards, and then END is executed, ending the program. If, however, the top of the stack is nonzero, the PROVIDED branch is taken, READ is run backwards (outputting the number), DOUBLE is executed backwards (pushing -2), UNO is executed forwards (pushing 1), and PROVIDED is executed (because the top of the stack is nonzero), looping this section forever.
It took me much trial and error to get an Acrostic truth machine this short, though IMHO it is a very clean and compact example. If only this language were easier to golf...
Poetic, 137 bytes
TRUTHFUL MACHINE
A:I=true,O=false
B:get a number or get a value
C:if falsy,a zero
D:if truthy,a one
D.a:repeat it if value=I
E:suspend it
sed 4.2.2, 8 bytes
Uses the -n flag to suppress printing without an explicit p command.
:
p
/1/b
Commented:
#create an unnamed label
:
#print pattern space
p
#If pattern space contains 1, branch to beginning
/1/b
Arn, 4 bytes
“l○|
Explained
Unpacked: &&[{1
Takes advantage of the fact that Arn's interpreter is written in Javascript. This means the && and || operator can be used as control flow.
_ % Variable initialized to STDIN. Implied
&& % Boolean AND
[ % Sequence
{ % Block; used to calculate future entries in a sequence
1 % Literal one
} % End block. Implied
] % End sequence. Implied
1+, 10 bytes
."#:[#":1#
Yay for comment abuse in a normal challenge (instead of a source-layout or polyglot one)! In 1+, the [ character that begins a comment is actually an instruction so it can be skipped with the goto command #.
For input 0:
. Take input
"# Jump to the 0th hash tag
: Output 0
[ Comment the rest of the program out
For input 1:
. Take input
"# Jump to the 1th hash tag
# The 1th hash tag
": Duplicate and output
1# Jump to the 1th hash tag
I can replace the 1 with " as well so that we get a 1+ program without a 1 instruction... Wow!
Naive solution, 14 bytes
.1##":"1+1<1+#
A simple do-while loop.
RAKIAC machine language, 6 bytes (34 real for asm)
00000100
00000011
00110100
00100001
00000001
00000010
Representing the assembly:
in
s: out
jez v
jmp s
v: hlt
end
Tried out one of my things for fun (definitely not made for golf).
Python3, 40Bytes
a=input()
while int(a):print(a)
print(a)
- If input is 0 it will be printed once.
- If input is 1 it will be printed forever.
Comp, 6 or 8 bytes
The first golfing language (sort of :) ) from 2020!
;{^&}&
That could be a mistake. An alternative program is:
;{^£}£
Explanation
; Take an input from the console as an integer
{^£} While that's nonzero, duplicate & print
£ If that's zero, directly print
Wren, 55 bytes
Fn.new{|x|
while(x){
System.print(x)
if(x==0)Fn.x()
}
}
Explanation
Fn.new{|x| // As usual, new anonymous function x
// Newline as we are entering statements, not an expression
while(x){ // While the input x is true:
// (Everything other than false, the null string, and the
// empty list is true)
System.print(x) // Output x to the console with a newline
if(x==0)Fn.x() // If the input is 0 then exit the program
}
}
Shakespeare Programming Language, 123 120 bytes
(Whitespace added for readability)
T.Ajax,.Puck,.Act I:.Scene I:.[Exeunt][Enter Ajax and Puck]
Ajax:Listen tothy.Open heart.
Am I worse you?If solet usAct I.
I make use of a trick to reuse Scene I. For some reason, it doesn’t error to keep taking input, so I do that. Then I just compare the input to zero, and loop if it’s greater. Saved 3 bytes by comparing to I instead of zero because characters initialize to zero—thanks Robin Ryder!
JavaScript, 39 32 Bytes
x=+prompt();do{alert(x)}while(x)
x=+prompt() gets input from user, and transforms it from a string to a number
do{alert(x)}while(x) is a post test loop, so it always alerts X, then executes again if x not = 0
W s, 1 byte
The s flag forces a read from STDIN. This flag can be appended to the end of the command-line.
w
No, I didn't just make a built-in for the question.
Here is the expanded program (because w requires two inputs)
aaw
This decodes into:
mywhile(a[0],'a[0]',a)
Which means:
while a[0]:
print(a[0])
The print is implicit in every while iteration. Since a[0] is always 1 once it is defined as 1, this will print 1 forever (the body is the same as the condition).
So you might say that this prints nothing if the input is 0. You are wrong, the w instruction returns the condition 0 after the while statement is done. Therefore it gets returned and gets outputted.
W s, 4 bytes
W was designed to be very powerful so that while loops are unneccecary. This program avoids this at the cost of being significantly longer. (Please don't use the while loop (which is simply for presentation purposes) in your W programs. Thank you.)
ibE&
Explanation
& % Perform logical AND between the input and the code block.
% If the input is 1, execute the following code block:
i E % Count to infinity,
b % Printing the input in every iteration
% Otherwise (part of the AND logic):
% Return 0, exit the program.
Python 3, 35 bytes
a=input()
while a:a=int(a);print(a)
This is the best I can do, don't know if it's the optimal solution though.
Explanation
In Python 3, input() stores the input as a string, so even if the user types 0, it will be stored as '0', which is truthy. This allows me to make a kind of do-while loop, which will always run at least once since '0' and '1' are both truthy. However, I then convert a to an integer ('0' becomes 0 and '1' becomes 1). Now, if the user typed 0, it will not run again since the while loop is now while 0 and 0 is falsy. However, if the user typed 1, it will run forever since the while loop is now while 1 and 1 is truthy.
Keg, 12 8 7 4 bytes
{:|④
Explanation
# Implicit input
{:| # While the duplicated item is nonzero:
④ # Output the item without popping
# After that, Output the item remaining on the stack and stop the program
Gaia, 3 bytes
:p↺
Explanation
↺ While...
: Duplicating the top of stack leaves a true value on top:
p Print the top of the stack
Input is taken implicitly in Gaia. Every iteration leaves the stack empty, but if there is no input left when it attempts to grab some, it simply takes the most recently given input again.
Jasmin, 355 321 bytes
As with the other answers I've written in Jasmin, there isn't a whole lot of golf going on here. This code is (almost) exactly the code obtained from running javap on the class file generated by intrepidcoder's java submission. The one neat golfing trick I found was avoiding the usual .limit locals line by reusing local variable 0.
Some code golf four years later
- Shorten the invocation of
printby extendingPrintStream ldc 2is shorter thaniconst_2- Manipulating the stack with
dupandswapis shorter than using locals variables withiload_0andistore_0.
After these changes, the compiled class file needs to be executed with java -noverify.
.class L
.super java/io/PrintStream
.method public static main([Ljava/lang/String;)V
.limit stack 4
getstatic java/lang/System/out Ljava/io/PrintStream;
getstatic java/lang/System/in Ljava/io/InputStream;
invokevirtual java/io/InputStream/read()I
ldc 2
irem
dup2
invokevirtual L/print(I)V
dup
ifgt $-5
return
.end method
MathGolf, 5 4 3 2 bytes
-1 for dropping block marker
q▲
Explanation
Implicit input
Starts a block
q Output TOS without a newline.
▲ Execute the code block while the TOS is true. Executes at least once.
Implicit output
Cascade, 10 bytes
?1/
#?
&#|
My first submission with my new language Cascade! Cascade is a tree-like esolang, similar to Pyramid Scheme, but a bit terser and with wrapping boundaries. Ungolfed, this looks more like:
@ |
? /
#|
&|
^
# |
1 |
First, the ? checks if the printed (#) input (&) is positive. If not, it goes left and terminates since it finds no more instructions. If so, it goes right to the ^, which first executes the left (#1, print 1), then goes to the right, which wraps around back to the ^ for an infinite loop. In the golfed code we use another ? which does a similar thing except with the center and the right, since we know the return value of # is always positive.
Verbosity v2, 290 bytes
IncludeTypePackage<OutputSystem>
IncludeTypePackage<InputSystem>
IncludeStructurePackage<Loops>
input=InputSystem:NewInput<DEFAULT>
outpu=OutputSystem:NewOutput<DEFAULT>
condi=InputSystem:ReadEvaluatedLineOfInput<input>
Loops:ConstructLoop<Do;condi>[OutputSystem:DisplayAsText<outpu;condi>]
First non-trivial Verbosity v2 answer! Although how it works is very trivial, as you can see from the ungolfed version:
IncludeTypePackage<OutputSystem>
IncludeTypePackage<InputSystem>
IncludeStructurePackage<Loops>
input = InputSystem:NewInput<DEFAULT>
output = OutputSystem:NewOutput<DEFAULT>
condition = InputSystem:ReadEvaluatedLineOfInput<input>
Loops:ConstructLoop<Do; condition> [
OutputSystem:DisplayAsText<output; condition>
]
Simply enter a do...while loop, which prints the input at least once, then terminates if it's falsey (i.e. 0).
Rust compiler (nightly), 86 bytes
#![feature(log_syntax)]macro_rules!t{(0)=>{log_syntax!{0}};(1)=>{log_syntax!{1}t!{1}}}
Readable version:
#![feature(log_syntax)]
macro_rules! truth_machine {
(0) => {
log_syntax!(0);
};
(1) => {
log_syntax!(1);
truth_machine!(1);
};
}
truth_machine!(0);
truth_machine!(1);
Explanation
As the only way to iterate over anything other than the inputs of a macro is recursion, an infinite loop will always end in a stack overflow. I'm considering this error message "constant output of your language's interpreter that cannot be suppressed," as there's no other way to "infinitely" loop. The time for this to occur is dependent on the stack size, and thus most real-world macros will attempt to perform multiple operations per iteration to avoid this. Since this takes more space, I didn't do this. The only ways for a macro to give output are:
compile_error!, a builtin which will immediately terminate compilation with a message, and is thus not valid for this challengelog_syntax!, an unstable builtin which will print its input to the compiler's stdout, with a newline appended- Returning a value from the macro directly, which directly conflicts with the concept of an infinite loop
I chose to use log_syntax!, as I decided it was the only option that would follow the rules of the challenge. However, it requires a nightly compiler, and 23 additional characters in the source to enable. The syntax of macros is pretty fixed, but one trick I found is that macros called with macro!{} instead of macro!(); do not require a semicolon after, and are thus one character shorter.
Unsuspected-hangul, 187 bytes
ㅀㄱ ㄱㅇㄱ ㅅㅅㅎㄴ ㄳㅎㄴㅎ ㄱㅀㄷ ㄱㅇㄱ ㅁㅈㅎㄴ ㅈㅀㄴ ㄱㅇㄴ ㄴㅇㅎㄴ ㅂㄱㅎㄱ ㄳㅎㄴ ㄱㅇㄴ ㄴ ㄴㅎㄷㅎㄷㅎ ㄱㅀㄷㅎ ㄱㅀㄷ
Note that it use pop-up for standard output, and you have to close tap to terminate the program.
How does it work?
ㄹ ㅎㄱ [ㄱㅇㄱ ㅅㅅㅎㄴ ㄱㅅㅎㄴ ㅎ] ㄱㄹㅎㄷ bind(input(), int)
[def print_and_recursion(x) num -> IO(nil)
ㄱㅇㄱ ㅁㅈㅎㄴ ㅈㄹㅎㄴ print(str(x))
[def recursion_part(not_used) nil -> IO(nil)
(ㄱㅇㄴ ㄴㅇ ㅎㄴ) print_and_recursion(x)
(ㅂㄱㅎㄱ ㄱㅅㅎㄴ) IO(nil)
(ㄱㅇㄴ ㄴ ㄴㅎㄷ) ㅎㄷ if(x == 1) then... else...
ㅎ]
ㄱㄹㅎㄷ bind(print(str(x)), recursion_part)
ㅎ]
ㄱㄹㅎㄷ bind(bind(input(), int), print_and_recursion)
Unsuspected-hangul(평범한 한글) is Korean character-based functional esolang.
JavaScript, 32 bytes
do{alert(x=x||prompt())}while(x)
Befunge, 4 bytes
&:.%
Please note: this answer is no longer valid with this particular interpreter. At the time of writing, the interpreter used had a quirk where trying to read more integers when there weren’t any would return the last integer. I believe that this was “fixed” in some interpreter update. (Thanks to @osuka_ for realizing that this answer no longer works)
Explanation:
& Take number input
:. Duplicate and print input
% Mods the second from-the-top with the top number in the stack
This means that if the top is 1, it will yield 0 % 1 = 0,
But if it is a 0, it errors out and stops execution because you are
trying to divide by 0
& The program wraps back around if it didn't error, and the & takes
the last number in the input if it has already taken them all, yielding
the original 1 or 0
Coincidentally, this doesn't also work for /, because it strangely asks you what you want the answer to be.
Runic Enchantments, 6 bytes
i:?@:$
? is a conditional jump command that skips n instructions where n is a value popped from the top of the stack. If that value is 0, we dump the stack and terminate. If its 1 we skip that instruction and print the value, leaving a copy on the stack, then loop. i does nothing if there is no more input to read.
Befunge-93, 7 bytes
&>:.:_@
_ is the horizontal if in befunge - conveniently, it sends the IP right if the top of the stack is 0 (so it hits @ to end the program), and left if the top of the stack is nonzero (which puts it in an infinite loop).
33, 4 bytes
O[o]
Explanation:
0 input:
O | Get input
o | Print it
[ ] | Loop ends because accumulator is 0
1 input:
O | Get input
[ ] | While the accumulator is 1 (forever)
o | Print it
Pip, 7 bytes
IqW1P1i
explanation:
If(q) // q is input
While(1) {
print(1);
}
output 0 // i is initialized to 0, but this stops it from being confused for "10"
Pyramid Scheme, 166 156 131 123 bytes
Saved 10 bytes thanks to Pavel! Saved 25 33 bytes thanks to Khuldraeseth na'Barya!
^ ^
/ \ / \
/set\ /do \
^-----^ ^-----^
- ^- -^ / \
/l\ /#\ /out\
/ine\---^-----
----- -
Old answer and explanation (functionally equivalent)
^ ^
/ \ / \
/set\ /do \
^-----^ ^-----^
/a\ /#\/a\ / \
--- ^------ /out\
/l\ ^-----
/ine\ /a\
----- ---
Hehe. I love this language.
Explanation
There are two pyramid chains. The first is:
^
/ \
/set\
^-----^
/a\ /#\
--- ^---
/l\
/ine\
-----
This sets variable a to line (a line read from STDIN), as a value (#).
The second:
^
/ \
/do \
^-----^
/a\ / \
--- /out\
^-----
/a\
---
This is a do while loop, with the left pyramid being the condition, and the right one being the body. Equivalent to:
do {
out(a);
} while(a);
which is what we want.
Enterprise, 128 bytes
/©©//NDANDA/final disruptive class fdcBit{final immutable void main(){var Money i=read();;;write(i);;;while(i==1){write(i);;;}}}
It's really annoying how the specification isn't very clear, so I had to guess a lot of things.
EZLang, 105 bytes
MEM(0)
SET(-1)
MEM(1)
GET()
SET(-1, 1)
JLZ(12)
SET(1, 1)
MEM(1)
PRT()
MEM(0)
JLZ(8)
SET(1, 1)
PRT()
HLT()
Self-made esolatic language.
Aheui, 28 bytes
붕박누망홰
차봇멍보
Additionally, I found bug of TIO with Aheui : Aheui is befunge-like, but initial direction is up-to-down, but TIO's initial direction is right-to-left, so my original code got error.
Ruby + -np, 16 12 bytes
p 1while~/1/
~/1/ matches the last line of input to the regular expression /1/
Edit: replaced ;p 0 with the -p flag making the answer -np complete, thanks to @ValueInk
GolfScript, 13 bytes
~{.}{.p}while
Explanation
~ # convert STDIN to an integer
{.} # while loop condition: remains the same--the input
{.p} # while loop body: print the input
while
This is one of my first golfs!
NuStack, 82 bytes
putchar(c:char):int;f(i:int):int{if(i>0)putchar('1');else while(1>0)putchar('0');}
Been working on this compiler for a month and a half. Still very much a WIP, but finally at a point where I can do some PPCG with it :D
Unlike all of my other languages, this isn't some toy, esoteric, interpreted language.
It's a serious language that compiles directly to assembly (nasm syntax).
I'll probably opt to get NuStack on TIO once it's notably more feature-complete than it currently is.
Explanation:
Ungolfed version:
putchar(c: char): int;
f(i: int): int {
if(i > 0)
putchar('1');
else
while(1 > 0)
putchar('0');
}
The first line is a function prototype that allows you to call a function defined elsewhere (think C header files)
putchar in particular is currently the only function in libns, the language's standard library. It takes a single char, and outputs it to stdout. libns is currently available for 64bit linux, so it just makes a syscall using sys_write(), and 32bit "raw", ie not running on a kernel or operating system, where putchar will use the int 0x10 interrupt to print the character in TTY mode
NuStack uses post-fix types, similar to TypeScript, and there is no type inference, so types must always be explicitly declared.
NuStack also doesn't have type casts yet, or do..while loops, so this is, as far as I know, the golfiest way to do it.
VSL, 36 32 bytes
fn main(){do{print(i)}while i>0}
This is probably familiar to anyone who knows any C-esque language but this takes input using a global variable i.
Malbolge, 257 bytes
(aONMLKJIHGFEDCBA@?>=<;:98765FD21dd!-,O*)y'&v5#"!DC|Qzf,*vutsrqpF!Clk|ih
gfed9(T&6KoOHZYXWVUTSRQPONM]KJIHGFEDCBA@?>=<;:9876"'~g|edybav_zyxwvotsrq
pSnPlOjibKfedcba`_XA??ZYRW:UTSLQ3ONMLK.IHGFE>CBA@?"=<;:38765432s0/.n,+*)
j!&%f{"!~}|_zyxZvYnsrqpRnmlkjML:f_^GF!
From esolangs.org
Quite the abomination, isn't it?
In fact, this language is so horrible, I don't think anyone "programmed" this in the traditional sense. If I'm remembering correctly, this was found by a search program that basically brute-forced for possible Malbolge programs that worked as a truth machine.
INTERCAL, 89 bytes
DOWRITEIN.1PLEASE.3<-#1$.1DOCOMEFROM(2)DOREADOUT.1(2)PLEASE(1)NEXT(1)DO(1022)NEXTDOGIVEUP
Looking at some answers to this challenge, I noticed that the current INTERCAL answer was barely golfed at all, with 141 bytes 30 of which are whitespace. Not hard to outdo!
Uses native INTERCAL-72 integer I/O, that is, the input is ZERO or ONE (or some translation thereof) with a trailing newline, and the output is in "butchered Roman numerals".
Explanation:
DO WRITE IN .1
Inputs a number to the 16-bit variable .1.
PLEASE .3 <- #1 $ .1
Sets .3's value to 1 mingled with .1's value. Since .1 holds either 0 or 1, .3 is set to either 2 or 3.
DO COME FROM (2)
If execution would move on normally from statement (2), it goes here instead.
DO READ OUT .1
Prints the value in .1.
(2) PLEASE (1) NEXT
This is statement (2). It places itself on the NEXT stack and moves execution to statement (1). It does not trigger the COME FROM unless RESUMEd to.
(1) DO (1022) NEXT
This is statement (1). It NEXTS to statement (1022) in syslib, which then itself NEXTS to statement (1023) in syslib, which reads PLEASE RESUME .3. This pops a non-zero number of entries equal to .3 off the NEXT stack and resumes execution at the last one popped. Since there are at this point three entries on the NEXT stack, corresponding to (2), (1), and (1022) (RESUME works just fine without labels, it just so happens that all of the NEXTs here have them), and .3 is 2 or 3 depending on whether .1 is 0 or 1, this goes to and moves on from either (1) if .1 is 0, or (2) if .1 is 1. If this RESUMEs to (2), the COME FROM takes effect and begins an infinite loop (and since this outcome leaves the NEXT stack empty, the program does not disappear into the black lagoon after 80 loops).
DO GIVE UP
If (1) was RESUMEd to, execution moves here, and this terminates the program without an error.
(I'll edit in a version with Turing Tape string I/O some time later.)
AlgiX with -x, 3 bytes
[.]
Explanation
AlgiX takes each character of input (converts it to charcode if it's not a digit) and runs the entire code for each value, initializing the accumulator to that value each run.
In this case, there's only 1 input, a 1 or a 0, so the code runs once.
[.] - Implicit a = input
[ - If a == 0, skip to ]
. - Print value of a
] - If a != 0, jump back to [
- Implicit output value of a
Normally, the implicit output after each run would output a as a character, however the -x flag overrides that and outputs its value instead.
VTL-2, 25 bytes
1 A=?
2 ?=A
3 #=4-2*A
Line numbers always take up two bytes in VTL, hence the byte count discrepancy.
This should work in VTL-1 as well, but I don't have an interpreter to ensure that is the case. I've tested this under a VTL-2 interpreter running on an Altair 8800 simulator, both sourced from here. Here's a PDF manual for VTL-2.
VTL was a small (<800 bytes!) and simple language for the Altair 8800 and 680 machines. Its creative use of system variables helped to keep it small. ? represents both input and output. Note that this truth machine outputs no line breaks, as those always need to be manually printed (by printing an empty string, ?=""). # represents line number, and can be used to retrieve the current line number or assigned to form a goto. That should be enough to make this truth machine make sense...
1 A=? ) Put input into variable A
2 ?=A ) Print the contents of variable A
3 #=4-2*A ) Goto 4-(2*A)... So, (nonexistent) line 4 if input was 0
) Or back to line 2 if input was 1. Yes, `)` is the comment character.
C++ (gcc), 65 bytes
#include<cstdio>
int main(){for(int c=getchar();putchar(c)-48;);}
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 your heart is not empty
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
While X
Say X
C (gcc), 52 bytes
main(i){for(scanf("%d",&i);i;)puts("1");puts("0");}
-27 bytes thanks to JoKing
-2 bytes thanks to Jonathan Frech
Try it online!
I though I'd try something other than my primary language (Java).
Tamsin, 19 bytes
main="0"|{print 1}.
Explanation
The main production first tries to read a 0. If it succeeds, it is returned, and, because this is the main production, printed.
Otherwise, it ignores the input and tries the alternative, which is {print 1}. The { } brackets denote a loop that continues running as long as its content succeeds, and a print statement always succeeds, so this loops forever.
Deoxyribose, 18 bytes
Updated for the new v3 spec
ATGGAGAAGAGCATAAAT
Explanation:
ATG ATA (*)
GAG Glu Dupe TGG Trp Power
AAG Lys Pop AGA Arg Unipop
AGC Ser Jump if <= 0 AGA Arg Unipop
ATA * GCA Ala Modulo
AAT Asn Loop TAA End
- Execution starts at the initial ATG.
- The top element of the main stack is duplicated & printed, then If the value is less than or equal to zero, jump to the ATA formed by the Asn and the start codon (remember, the code is circular), then run through a series of no-ops, including printing some non-printable characters. If the value is greater than 0, loop back to the start.
If you don't like the ugly sequence of no-ops, adding ATG to the end to make the loop target explicit results in a clean termination immediately after the jump, for three more bytes.
Deoxyribose 2, 21 bytes
ATGTGAGAAAAATCTAACTTA
Explanation:
ATG Start TAA Stop ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┐
TGA Block size = 56 ┏ TGT Cys Destination of Asn ┆
GAA Glu Duplicate ┃ GAG Glu Duplicate ┆
AAA Lys Pop as int ┃ AAA Lys Pop as int ┆
TCT Ser If >= 0, jump to Thr ┐┞ AAT Asn Jump back to Cys ┆
AAC Asn Jump back to Cys ────┼┘ ┆
TTA └─ ACT Thr Destination of Ser ┆
└┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┘
This is the first challenge on this site ever answered in this language (since it's only a week old), but I think it's a good showcase of what the language can do so I'll provide a bit of an explanation of what's going on. If you happen to be really interested, the spec, a Python-based interpreter, and additional (less golfed) examples are on GitHub.
Deoxyribose is a stack-based language with a small instruction set and a syntax based on DNA. Execution takes place on a circular stretch of DNA, translating 3-digit "codons" into proteins, each of which corresponds to either
- an operation on one or both of the stacks, or
- a (perhaps conditional) jump to a particular sequence elsewhere in the code.
These jumps can lead to frameshifts, where the read head is moved a non-integer number of codons and the same bit of code ends up doing two totally different things at different times. The degenerate nature of the genetic code makes it possible (and fun!) to use this to your advantage.
Alchemist, 24 bytes
_->In_a+Out_a
a->a+Out_a
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
Turing Machine But Way Worse, 139 bytes
0 0 0 1 1 0 0
0 1 0 1 2 0 0
1 2 1 1 3 0 0
1 3 1 1 4 0 0
0 4 0 1 5 0 0
0 5 0 1 6 0 0
0 6 0 1 7 0 0
0 7 0 1 8 1 1
1 7 1 0 8 1 0
0 8 0 1 7 1 0
bitch, 5 bytes
This infinitely outputs 1 for an input of 1 and outputs 0 once for an input of 0.
\>/;<Try it online!
Explanation
\ Input of an integer (restricted by challenge to 0 or 1)
> Loop marker #1
/ Output
;< If not equal to 0, jump to loop marker #1
(Implicit end of program)
!@#$%^&*()_+, 10 bytes
*0_+!#(!#)
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
brainfuck (portable), 29 28 bytes
>>>,.[[->+<<+>]>-]<+[<<]>[.]
(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.
brainfuck, 28 bytes
>>,.[[>]+<[-<]<+>>]>[<]<<[.]
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
Backhand, 9 bytes
{I>{@:1O_
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
Little Man Computer, 19 bytes (4 instructions)
INP OUT BRZ 4 BRA 1
Which, when assembled into RAM, is:
901 902 704 601
Annoyingly, BRP means branch if positive or zero, making it useless for distinguishing between the two possible inputs. Therefore we have to use two seperate branching commands: BRZ (branch if zero) to escape the program, followed by a BRA (branch always) to continue the loop if the number is non-zero.
An online interactive interpreter can be found here.
Assembly (nasm, x64, Linux), 119 bytes
mov eax,3
mov ebx,0
mov ecx,i
mov edx,1
int 80h
l:mov eax,4
mov ebx,1
int 80h
cmp byte [i],49
je l
section .data
i:db 0
I was surprised that, while there is a 128 byte submission in as, there isn't a nasm submission, despite it being shorter!
Literally a port of the as submission into nasm.
Z80Golf, 9 bytes
00000000: cd03 80ff fe30 20fb 76 .....0 .v
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
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
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 thenputcharis executed. - The
putcharhas aretinstruction, sospbecomes 2 and execution is returned to the address$03cd. - Then
putcharis executed again.spbecomes 4,pcis$b880. - Now
pcwraps around and comes to$0000, the start of the program. call $8003is run, which overwrites the program so$80b8becomes$0300.getcharsets the carry flag, but we don't care anyway. EOF is hit soais untouched.- Now
cp bbecamenop, butjr nz, infinityis intact. Againputcharis run,spbecomes 6,pcis$0220.putcharagain,sp = 8,pcis$76ff,putcharagain,sp = 10 = $000a,pc = $0000. - The
call $8003becamecall $0303, which now effectively callsputcharinstead. No problem, now one loop just printsatwice. Note that acallleaves$0300to the memory, but fortunately$00is NOP and$03isinc bc, which does not affect the program's logic. (Single-byteincdoes affect the flags, but double-byte ones don't, sojr nzisn't affected either.) - The
callis now a heat wave filling the memory with$0300. Eventually,spwraps around to$0002again, and finally overwrites$cd03into$0300, deleting thecall.
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.
Acc! - 54 50 48 49 Bytes
N
Write _
Count q while _-48 {
Write _
}
Self-modifying Brainfuck, 30 19 bytes
Similar method to my BF answer. Input and print, subtract the 0 (the source's last byte) from the input, so cell is 0 or 1. Loop printing if input cell is 1. Tested on my Python interpreter.
,.<[->-<]>[<<.>>]10
You can also run it on TIO.
Pepe, 15 bytes
REeErEErReEEree
Explanation:
REeErEErReEEree # Full program
REeE # Take input as number
rEE # Create label 0
rReEE # Output number -r (preserve)
ree # Goto label 0 if [input] != 0
Python 2.7, 45 bytes
I just had the Eureka of this code:
x=int(raw_input())
print x
while x: print 1
I am proud of this one, though it may not look very impressive.
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.
MATL, 4 bytes
`GtD
Relevant MATL features *
To explain the code, the following MATL features need to be presented first.
`...]is a "do ...while" loop. The top of the stack is consumed at the end of each iteration, and used to decide whether to go on with a new iteration or not. The last]can be omitted if it's at the end of the program (loops are implicitly closed).Gworks as follows:- When there has been no user-input it does nothing;
- When there has been one user-input it pushes it onto the stack
- When there has been more than one user-input it takes a numeric argrument and pushes one of those user-inputs onto the stack
tby default duplicates the top element of the stackDby default displays the top element of the stack, and consumes it.- If a function requires more inputs than currently are in the stack, user-input is implicitly triggered. The entered elements are placed below the current bottom of the stack.
Code explanation
` enters the loop. At the first iteration, G does nothing. t implicitly asks for user input and duplicates it. D displays and consumes the duplicate, leaving the original input on the stack. If this input is 0 the loop is exited and the program finishes (a single 0 has been displayed). If the input is 1, control goes to the beginning of the loop again. Now G pastes the input, t duplicates it, D displays and consumes that duplicate, and again there's a 1 to be used as loop condition, so the loop begins again, indefinitely (an infinite number of 1 is displayed).
* at the time of writing. The behaviour of G has changed since then: G now triggers implicit input when there has been no user-input yet. However, this doesn't affect the code, which works the same. The only difference is that in the first iteration the implicit input is now triggered by G, not by t.
2DFuck, 32 30 bytes
,.,.,.,.,.,.,.,.[!..!..!...!.]
Explanation:
,.,.,.,.,.,.,.,. Read and print a byte, accumulator is last bit = 0 or 1
[!..!..!...!.] While the accumulator is 1, print 1
ABAP, 61 bytes
Hardcoded VALUE 1 for variable i, replace with 0 to not trigger the infinite loop.
DATA x TYPE I VALUE 1.
WHILE i=1.
WRITE i.
ENDWHILE.
WRITE i.
Rust, 90 bytes
use std::io::*;fn main(){let
b=&mut[0];stdin().read(b);while{stdout().write(b);b==b"1"}{}}
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
Charm, 42 bytes
getline " 1 " eq put [ dup ] [ put ] while
You strangely can't cast to an integer in Charm, so I had to check for equality with 1 instead.
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.
,.[[<+>->+<]>-]<+[<<]>[.]
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):
,.+++[->+>+++++<<]>--->+[<.>]
,.[->+>+>--[<+>--]<<<]>>[<.>]
TIS -n 1 1, 29 bytes
@0
ADD UP
L:MOV ACC ANY
JGZ L
ADD UP is a shorter form of MOV UP ACC, since the accumulator starts at zero, and we only ever see one value on the input (if that is not desired +4 bytes to add HCF after the last line).
MOV ACC ANY simply does the output. This line is also labelled L.
JGZ L jumps to L if the accumulator is greater than zero. (JNZ L, jump if non-zero, would work identically here.)
In the case where we have a zero for input, we do not jump, but instead wrap around to the first line (ADD UP). Since there is no more data to be had, the system goes quiescent.
In the case of a one, we will endlessly jump to L, outputting a 1 on every third cycle (writing to a neighbor actually takes two cycles in TIS).
Whitespace, 46 37 bytes
Thanks to Kevin Cruijssen for golfing 1 byte off the first instruction, and 8 bytes by removing the last 2 instructions, which makes the program jumps to non-existent label and terminates with error but still output correctly in the output stream.
SS SL # push 0
SLS # dup
TLTT # readn
TTT # load
LSS L # label L
SLS # dup
SLS # dup
TLST # prtn
LTS TL # jmpz TL
LSL L # jmp L
Previous safe version of the program which terminates normally has a proper label and the standard triple new line to end the program:
LSS TL # label TL
LLL # end
Notation explanation:
#starts commentLis newlineSis spaceTis tab
I used this interpreter to develop the program and generate the comments.
Didn't expect the code to be this long. Whitespace requires the input to be read into heap, heap instructions consumes stack, printing instruction consumes the stack and even jump instruction consumes the stack, so it bloats the code with all the "duplicate top stack" instructions.
Quarterstaff, 12
49-?{49!}49!
explanation
(value = 0 to start)
49 - add 49 to value
- - invert value (value = -49 now)
? - take a character of input (49 for "1", 48 for "0"), and add it to the value (value = 0 or -1 now)
{ - begin while not loop. will only be entered if input is 1 or starts with 1 (it should only start with 1 if it is 1).
49 - add 49 to value. value is now 49
! - print value, set value to 0.
} - end while not loop.
49 - add 49 to value (which was -1). value is now 48
! - print value, set value to 0 (not relevant to the program, but all ! do this)
it looks like it could be golfed by assigning 49 to something, but it would take 2 more bytes to assign it, then 2 more bytes to use it in the first part, then only byte saving of 2 for the other two occurences of 49
Previous version of Quarterstaff, 11
I removed %, so this isn't valid in the new version
?1%{49!}47!
? - input a character (49 for "1", 48 for "0") add to value
1 - add 1 (value is 50 or 49 now)
% - value = value %2 (0 if "1" was inputted, 1 if "0" was inputted)
{ - begin while not value loop
49 - add 49 to value
! - print value, value = 0
} - end while not value loop
47 - add 47 to value
! - print value, value = 0
Momema, 9 bytes
i0-8_Ii_I
Try it online! Requires the -i interpreter flag.
The provided Momema interpreter has a -i flag which enables interactive mode. In interactive mode, expressions can have holes, which evaluate to a value read from STDIN. Normally, this would just be equivalent to *-8, but it also allows holes to be named with a string of capital letters. When a named hole is evaluated, its value is cached, and when a hole with the same name is evaluated again it is reused. This is intended to be for debugging purposes, but it also means that we can refer to input without having to assign it.
Explanation:
# i = input num
i 0 # label i0: jump past label i0 (no-op) # do {
-8 _I # output num _I # print num i
i _I # label i1: jump past label i(_I) # } while i
QUARK, 11 bytes
This is 6.75 bytes in QUARK's encoding, but that's not finished yet (no encoder), so I'll score this in UTF8 until then.
i‶{p}⟲
As QUARK became capable of doing a truth machine (implementation wise) less than a minute ago (from when I started writing this answer), it obviously needs an explanation, so here you go:
i Get input from the user (as a number)
‶ Pin the input to the stack (Pinning is QUARK's way of avoiding a million and one dupes, by simply making the value undeletable until you run the pin command on it again.)
{ Begin a block
p Print a value off the stack. Because the input is pinned, it's not consumed.
} End the block, and push it to the stack (when the program reaches this point)
⟲ Execute the block. If the top of the stack is not after the first execute 0, execute the block until it is. As the input is pinned, it will always be either 0 or 1. So the block either executes once, or infinitely.
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".
Python 2, 59 51 49 33 bytes
i=input()
while i:print 1
print 0
Explanation:
input() # take input from STDIN
while i:print 1 # print 1 if the argument is anything other than 0... input() evaluates the string and returns a value
print 0 # print 0 and exit if input() returns 0
EDIT: Saved 8 bytes thanks to @EsolangingFruit
EDIT 2: Coupla more bytes thanks to @HyperNeutrino
EDIT 3: Saved 16 bytes thanks to @HyperNeurtrino
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
Yabasic, 36 bytes
Another basic answer that takes input as integer, n and outputs to the console.
Input""n
If n Then Do?1Loop Else?0Fi
Reflections, 26 bytes
_:#_: _<
/#_v /
\: /
Explanation:
The _ at position (2|0) reads a line from input, : doubles the first character. Then, # redefines zero and _ at (1|0) prints that character.
: doubles the first character again, _ at (4|0) converts a digit to a number. < tests this number, if it's 0, the IP is directed upwards (out of the program). Else it's directed downwards, then left by the /, and down again by the v, left by the /. The : doubles the character again. Then, the \ reflects the IP upwards and the / right again, where # redefines zero and the _ at (1|0) prints the character. The v then directs it down into the loop again.
Stax, 5 4 3 bytes
wQc
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.
R, 29 27 bytes
2 bytes brilliantly saved by @Giuseppe
x=scan();while({cat(x);x})1
Kotlin Script, 41 bytes
readLine().let{while(it=="1")print("1")}
Pretty Printed:
readLine()
.let{
while(it=="1")
print("1")
}
Brachylog, 4 bytes
Thanks to Fatalize for saving 1 byte.
w?1↰
Explanation
w Write the input to STDOUT.
?1 Check whether the input equals 1.
↰ If so, recursively call the main predicate with 1 again.
Aheui, 33 bytes
방챵뱍벅나명희멍터벅벅
You can test it with jsaheui, or rpaheui.
How does it works?
// When input is 0
방챵뱍벅나명희멍터벅벅
ⓐⓑ ⓖⓕⓔⓓⓒ
// When input is 1
방챵뱍벅나명희멍터벅벅
ⓐⓑⓓⓒⓔⓕ
ⓖ
ORK, 395 bytes
There is such a thing as a m.
A m can p a word.
When a m is to p a word:
I have a scribe called W.
W is to write the word.
I have a linguist called C.
C's first operand is the word.
C's second operand is "1".
C is to compare.
If C says it's equal then I am to loop.
When this program starts:
I have a inputter called R.
I have a word called N.
R is to read N.
I have a m called M.
M is to p N.
Here's the ungolfed version, which is not a whole lot different:
There is such a thing as a truth machine.
A truth machine can process a word.
When a truth machine is to process a word:
There is a scribe called Keymaker.
Keymaker is to write the word.
There is a linguist called Chomsky.
Chomsky's first operand is the word.
Chomsky's second operand is "1".
Chomsky is to compare.
If Chomsky says it's equal then I am to loop.
When this program starts:
I have an inputter called Dave.
I have a word called Input.
Dave is to read Input.
I have a truth machine called Hal.
Hal is to process Input.
The first paragraph defines a truth machine class with one member function, process, which takes a string (i.e. word).
The second paragraph defines process: write the string out, and then compare it against "1". If it's equal, loop.
The third paragraph defines our main function: read a string in, instantiate a truth machine, and have the machine process the string.
Simple, really.
Draw, 21 bytes
start 0 1 start start
This is the version of the program where 1 is input. To change the input to 0, replace the 1 with a 0. The program where the 1 is there will produce an infinite line of marked squares towards y=+∞ starting at x=0, y=1; if the 1 was replaced, there will be only one marked square, at x=0, y=0.
Zephyr, 41 bytes
input n
print n
while"1"=n
print n
repeat
A main design goal of Zephyr was that code should be readable and understandable. Looks like this holds true even when the code is maximally golfed. Mission accomplished.
Forked, 22 21 bytes
-1 thanks to BMO
v >%&
$ |
>-:
|
%<
The IP path looks like this if the inputted integer is truthy:
v
|
>-v
|
%<
Upon hitting % (print as integer), it goes off the edge of the playing field and wraps around, running >% infinitely.
It takes this path if the inputted integer is falsy:
v >%&
| |
>-^
It prints % 0 and then exits &.
Wumpus, 6 bytes
Iv=O=:
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.
Forte, 49 60 bytes
3LET5=5+(0*4)
4INPUT0:LET6=6-(0*4)
5PRINT0:LET3=3+(0*4)
6END
Forte is a weird and wonderful language with BASIC-like syntax and an execution model based on redefining integers. It has no conditional or looping constructs; to get conditional or looping behavior, you have to redefine the line numbers your program uses.
How?
Here's the code with better spacing:
3 LET 5=5+(0*4)
4 INPUT 0 : LET 6=6-(0*4)
5 PRINT 0 : LET 3=3+(0*4)
6 END
If the user inputs a zero to this program, the three LET statements don't change anything, and the program boils down to PRINT 0 : END.
If the user inputs a one... it gets interesting.
3 LET 5=5+(0*4)
The first time around, no numbers have been redefined yet; this line calculates 5+(0*4) and assigns that to 5. Nothing changes.
4 INPUT 0 : LET 6=6-(0*4)
INPUT 0 reads a number from the user and redefines 0 as that number. Suppose the user enters a 1. Every time 0, or a value of zero, occurs from now on, it will be changed to 1. For instance: LET 6=6-(0*4) now is calculated as LET 6=6-(1*4), which redefines 6 to be 2. This changes the END statement's line number to 2, which moves it out of the way of the program, allowing an infinite loop.
Redefinitions: 0->1; 6->2
5 PRINT 0 : LET 3=3+(0*4)
First, this line prints 1 (the value that 0 now represents). Then, 0*4 is now 1*4, so we have LET 3=7.
Redefinitions: 0->1; 6->2; 3->7
Next, we increment the instruction pointer and execute the command on line 3 7:
3 LET 5=5+(0*4)
which redefines 5 to be 5+4...
Redefinitions: 0->1; 6->2; 3->7; 5->9
... and we execute line 5 9:
5 PRINT 0 : LET 3=3+(0*4)
which should be read (with substitutions) as 9 PRINT 1 : LET 7=7+(1*4). We print another 1 and change 7 to 11, which means we execute the original line 3 again, and so forth.
For those who are still confused, read the Esolangs article or ping ais523 (the language's inventor!) in chat.
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.
FALSE, 12 11 bytes
^'0-[$.$]$#
Dreaderef, 11 bytes
5*1 1 5?8-1
Takes input from the command-line arguments. Try it online!
Explanation
This program consists of eight numbers. These numbers are grouped into instructions; each instruction consists of a label, which is the first number, and zero or more arguments, which follow the label. Instructions with different labels can have different numbers of arguments, but the parsing of instructions happens at execution time (which allows self-modification). The numbers in the program are written to the tape from position 0 at the beginning of the program; each label and argument occupies its own cell, and the instruction pointer occupies the cell at location -1.
5 *
1 1 5
? 8 -1
Dreaderef's preprocessor allows you to write aliases that stand in for numbers representing instruction labels. Using aliases makes the program look like this:
0. numo *
2. deref 1 5
5. ? 8 -1
(The leading numbers are position labels and are treated as comments.) Before the program executes, * is replaced with the input integer.
0. numo *
The first instruction is numo, which outputs its argument (either 0 or 1) in decimal without a trailing newline.
2. deref 1 5
deref reads the tape at the position indicated by its first argument. It then writes that value to the tape at the position indicated by its second argument. This means that here deref copies cell 1 (the input integer and argument to numo) to cell 5 (part of the next instruction).
5. ? 8 -1
This instruction is interesting in that the label is dynamically generated by the previous instruction (? is an alias for 0 in Dreaderef, but it is intended to convey that a given cell is uninitialized and will not be read until it is written to). During execution, it will be set to either 1 or 0 depending on the input integer. Proceeding from here requires some knowledge about what labels map to what instructions:
- The instruction with label 0 is
end, which terminates execution. - The instruction with label 1 is
deref.
If the input integer was 0, the end instruction causes the program to terminate, and the other two numbers are ignored.
If the input integer was 1, the instruction looks like this:
5. deref 8 -1
Cell 8 is past the end of the program, meaning that its value defaults to 0. The 0 is copied into cell -1, which is Dreaderef's instruction pointer. This means that execution jumps back to position 0, which is the start of the program. Because * is read before execution of the program, the same input (1) is reused, and the program outputs and loops again.
Retina, 9 7 bytes
/1/+>G`
Explanation
The stage G` itself is really a no-op (it's a Grep stage with an empty regex, which always matches). So it's all in the configuration. > prints the result of this stage (which is just the input) and /1/+ wraps it in a loop which runs as long as the string contains a 1. There's also implicit output at the end of the program. So we go through these two possibilities:
- If the input is
0, the/1/condition fails, so the loop is never run. Instead, the program terminates, and the0is printed at the end. - If the input is
1, the/1/condition matches, so the loop gets executed. The loop iteration itself does nothing but print that1, so the string's value won't change and the loop will continue indefinitely.
Acc!!, 39 37 bytes
N
Count i while _%2-i%2+1 {
Write _
}
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 _
}
;#+, 28 bytes
;;;;;;;;~*~-(;~;;;;;;~)~p(p)
;;;;;;;;~*~-(;~;;;;;;~)~p(p)
;;;;;;;; set acc0 = 8
~*~ set acc1 = input
-(; ) while(acc0--)
~;;;;;;~ acc1 -= 6
this leaves us with a `0` or `1` values for character input
~p print acc1
( ) while(acc1)
p print acc1
Pyt, 5 bytes
`Đƥłŕ
Explanation:
` ł (Do ... while top of stack is true)
Đ Duplicate top of stack
ƥ Print top of stack
ŕ Pop top of stack and discard
SNOBOL4 (CSNOBOL4), 38 bytes
N =INPUT
L OUTPUT =N
GT(N) :S(L)
END
N =INPUT ;* read input as n
L OUTPUT =N ;* print input
GT(N) :S(L) ;* if n > 0, goto L
END
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
JavaScript, 26 bytes - Variation of Solomon Ucko's answer
I find it weird how I can't comment, but I can edit his answer...
for(;alert(i=prompt())|i;)
Swift, 55 bytes, 54 bytes, 53 bytes
if readLine()=="1"{while 1>0{print(1)}}else{print(0)}
I tried to use ternary for a while but couldn't get it compiling. Maybe someone else will or it is just impossible. I'm open for tips or advice :)
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.
Husk, 5 bytes
¶?∞;I
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!
><>, 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.
Bitwise, 52 46 38 bytes
Oh, that's right, I made the interpreter not care about the return value for I/O. It was definitely not for code golf.
IN 1 &1
OUT 1 &1
XOR 1 &48 2
JMP &-3 2
Translated to C (labels added instead of literal jumps for clarity):
IN 1 &1 mem[1] = getchar();
LABEL &1 label_1:
OUT 1 &1 putchar(mem[1]);
XOR 1 &48 2 mem[2] = (mem[1] ^ 48); // ^ is equivalent to !=
JMP @1 2 if (mem[2]) goto label_1;
JavaScript (ES5), 40 bytes
function(x){x?while(1)alert(1):alert(0)}
Java, 126 bytes
public static void main(String[]a){int n=new Scanner(System.in).nextInt();while(n==1)System.out.print(n);System.out.print(n);}
Ungolfed (+ comments with explanation)
public static void main(String[]a){
int n=new Scanner(System.in).nextInt();//Create the scanner and get the next integer input
while(n==1)System.out.print(n);//if n == 1, print 1
//else exit. If there is nothing that happens the java program automatically exits
System.out.print(n);//But first print out 0
}
The reason behind using a scanner is me not being able to get the desired behaviour using System.in.read(). Typing 1 exited the program as if it was something else being typed. System.in.read() returns an int as 0-255 representing the byte it received, meaning 1 != 1 with that method.
Duck Duck Goose, 911 bytes
duck duck duck goose
duck
duck duck duck duck duck duck goose
duck
duck duck duck duck duck duck
duck duck duck duck duck duck duck duck duck duck duck goose
duck
duck duck duck duck duck duck duck duck
duck duck duck duck duck duck duck duck duck duck duck goose
duck duck
duck duck duck
duck duck duck duck goose
duck duck duck
duck duck
duck duck duck goose
duck
duck duck duck duck duck duck duck duck duck goose
duck duck
duck
duck duck duck duck duck duck duck duck duck duck duck goose
duck duck duck
duck duck
duck duck duck goose
duck
duck
duck duck duck duck duck duck duck duck duck goose
duck
duck duck duck duck duck duck duck duck duck duck goose
duck
duck duck duck
duck duck goose
duck duck duck
duck
duck duck goose
duck
duck goose
duck duck duck duck duck duck duck duck duck duck goose
duck
duck duck
duck duck goose
duck duck duck
duck goose
Includes 2 trailing newlines. I can't remove the newlines, they are instructions.
Implicit, 5 4 bytes
$(%)
Try it online! Prints 00, which is equal to 0 Pretty simple:
$(%)
$ « integer input »;
(.) « do..while top of stack true »;
% « print top of stack »;
« implicit integer output »;
Java (OpenJDK 8), 103 bytes
interface J{static void main(String[]a){int n=Integer.decode(a[0]);do System.out.print(n);while(n>0);}}
ungolfed (although Java doesn't need it that much):
interface J{
static void main(String[]a){
int n=Integer.decode(a[0]);
do System.out.print(n);
while(n>0);
}
}
Using Interface, as since Java 8 interfaces can have function bodies. Because they are always public we are saving some chars. The question states
take input from STDIN or an acceptable alternative
and for me the run arguments are an acceptable alternative.
Note that Integer.decode() throws a NumberFormatException, but input will always only be 0 or 1.
Python 2, 50 39 bytes
Don't know why nobody mentioned I could just write input()
i=input()
while(int(i)):print 1
print 0
Very simple, if the input is 1, will continuously print 1 and cannot reach the print 0. If it is 0, the while will never fire.
JavaScript, 62 34 33 31 bytes
Golfed:
i=prompt();do{alert(i)}while(i)
Ungolfed:
input=prompt();
do {
alert(i);
} while(i);
-1 byte thanks to JimmyJazzx's answer
-2 bytes and bug fix thanks to kamoroso94's comment
MATLAB, 39 37 bytes
Two years later, two bytes golfed off.
disp(input('')),while ans disp(1),end
This was a bit shorter than the original one, since it avoid having anything after end, thus saving a comma or semicolon, and it saves one more byte by avoiding the separate call to disp(0).
CMD, 30 bytes
:a
echo %1
if %1==1 (goto a)
Pretty straight-forward
4, 28 bytes
3.61448701501132011483250194
Explanation:
3. Start Program
6 14 48 Set the value of memory cell 14 to 48 (the ASCII code of '0')
7 01 Read in one byte to memory cell 01
5 01 Print byte from memory cell 01
1 32 01 14 Set the value of memory cell 32 to cell 01 - cell 14
8 32 Start loop: if cell 32=0, skip to the end
5 01 Print byte from memory cell 01
9 End loop
4 End program
INTERCAL, 141 bytes
PLEASE WRITE IN .1
DO (1020) NEXT
DO (1) NEXT
DO COME FROM (3)
(3)DO READ OUT #1
(2)PLEASE RESUME .1
(1)DO (2) NEXT
DO READ OUT #0
DO GIVE UP
Pyth, 5 bytes
Like my Python answer, but in Pyth
WQ1)0
Explanation:
WQ1) While Q, print 1. 1 = true, 0 = false; end While
0 Print 0
If input is 1, 0 is never reached, if input is 0, 1 is never reached.
Thotpatrol, 311 219 bytes
Credit to @MickyT for shaving 92 bytes off
📡JACKING IN📡
💦DM💦 THAUGHTY JO
🕵 📧🍆 JO
🕵 🍑📧 JO
❤PRIME ASSETS❤ JO INTERROGATE ©1©
🕵 🍑📧 JO
🎧INTERCEPT MALIGNANT COMMUNICATIONS🎧
🇺🇸REPORT UNPATRIOTIC ACTIVITY🇺🇸
This is a fairly uninteresting truth machine the core structure is as follows:
input a
print a
while a == 1
print a
end while
Here is a link to an implementation in Java: https://github.com/MindyGalveston/thotpatrol-
Whitespace, 40 bytes
Note that the only valid characters are space, tab, and linefeed, so they are represented here with S, T, and L, respectively. Comments are also given.
I used this interpreter to write and test this program (warning: crashes browser window upon input of 1).
SS L # push 0
SLS # duplicate
TLTT # readi
TTT # retrieve
LSS L #label "" (blank label name, why not?)
SLS # duplicate
SLS # duplicate
TLST # printi
SS STL # push 1
TSST # subtract
LTS L # jz label "" (jump to blank label if input-1=0)
Three consecutive linefeeds (LLL) are usually required to end program execution at a point, but that interpreter doesn't seem to mind if you leave them out. If they have to be added in, the score would instead be 43 bytes.
Excel VBA, 20 Bytes
Anonymous VBE immediate window function that takes input from range [A1] and output 1, infinitely if [A1] else 0
While[A1]:?1:Wend:?0
6502 machine code (C64), 17 bytes
20 FD AE 20 9E B7 8A 09 30 20 D2 FF C9 30 D0 F9 60
This is position independent code, you can enter it at any position in RAM and call it, so it doesn't need a load address. Assuming you put it at C000 (that's the case in the online demo), call it like sys49152,0 or sys49152,1 -- any other input is undefined.
Explanation:
20 FD AE JSR $AEFD ; consume comma
20 9E B7 JSR $B79E ; evaluate number, result in X
8A TXA ; transfer X to A
09 30 ORA #$30 ; convert to numeric character
20 D2 FF JSR $FFD2 ; output character
C9 30 CMP #$30 ; compare with '0' character
D0 F9 BNE *-5 ; not equal? Then jump back to output (-7)
60 RTS ; return
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
8th, 58 bytes
Code
: f getc '0 - dup 0 1 between if repeat dup . while then ;
Explanation
: f - Start of word definition
getc - Get input from STDIN
'0 - - Subtract 0's ASCII code to determine numeric input
dup - Duplicate result to be used to run loop
0 1 between if - Check if input is either 0 or 1
repeat dup . while - Print either 0 once or 1 ad infinitum
then ; - Exit word
If input is not either 0 or 1, exit with no output. At the end of the program the stack is not empty.
Assembly (as, x64, Linux), 128 bytes
.data
i:.byte 0
.text
mov $3,%eax
mov $0,%ebx
mov $i,%ecx
mov $1,%edx
int $128
l:mov $4,%eax
mov $1,%ebx
int $128
cmp $49,i
je l
Explanation
.data
i:.byte 0 ;Declare variable i with type byte
.text
mov $3,%eax
mov $0,%ebx
mov $i,%ecx
mov $1,%edx
int $128 ;Make system call read(eax=3) from stdin(ebx=0) with an address(ecx) and length in bytes(edx)
l:mov $4,%eax ;Declare section/label l
mov $1,%ebx
int $128 ;make system call write(eax=4) to stdout(ebx=1). There is no need to reassign ecx or edx
cmp $49,i ;compare the value at the address i to 49(ascii value of "1")
je l ;jump to label l if equal
Cubically, 6 bytes
According to the spec, this should work:
$(%7)7
$ - Get user input as number (either 1 or 0, according to the rules)
( )7 - do ... while input value is nonzero
%7 - Output the input as a number
However, TIO seems to continue the loop even if the input is 0. The Lua interpreter handles it correctly, though.
Cubically, 29 28 bytes
$!7{%0&}U3D1R3L1F3B1U1D3(%1)
Try it online! (May not work for a little while after posting due to TIO's version) Explanation:
$ read integer as input
!7{...} if falsy
%0 print 0th face
& exit
U3D1R3L1F3B1U1D3 quickest way to get 1 onto a face
(..) forever
%1 print the first face
Ly, 7 bytes
n:u[:u]
Explanation:
n # take input
:u # duplicate it and print it
[ # while the top of the stack is not 0...
:u # duplicate it and print it
] # end loop
C# (.NET Core), 80 79 bytes
class p{static void Main(string[]I){do{Console.Write(I[0]);}while(I[0]=="1");}}
I've seen some disagreement about whether arguments count as STDIN. "No" seemed more popular, but if it were acceptable then this would save 15 bytes over the previous C# answer.
Saved 1 byte by removing an unnecessary space
ILL, 19 bytes
/RnN~
>1nR\
\ /
ILL (inverse linear law) is new right now, so this represents virtually all the instructions/groups of instructions it has at the time of posting this. The main idea though, is that the program is run by light, which reflects off of mirrors and decrease in intensity as it moves on (obeying the inverse linear law, because its 2d). Data is primarily stored in the intensity of the light, which can sort of be used as a control structure, since light with an intensity < .5 dims and does not move on to the next tick. This means that different intensities of light move different lengths. This program utilizes the dimming behavior to either halt after printing 0, or prints 1 and continues. Basically, it takes a numerical input (side note: instructions that set intensity actually do so after the current tick has run, and they also persist the light over to the next instruction, no matter what intensity it has), prints it, and then re-intensifies and enters a loop. However, the light is only re-intensified if it reaches the re-intensify instruction, which light with an intensity of 0 will not. More detailed explanation (also a valid ILL program):
/RnN~
>1nR\
\ /
#END OF FILE#
Truth machine.
~ : emits light horizontally at the start of a program.
N : takes numerical input, set light intensity to the input.
n : produces numerical output. If the light has an intensity of 0 here, it will dim after n outputs and not move on.
R : re-intensify, if the light made it here, it can now continue into the loop.
> : double/splitting mirror, allows the light from the above / mirror to enter the loop and move right.
1 : set intensity to 1.
n : numerical output.
R : re-intensify.
the remaining \, /, and \ reflect the light back to > where it can start the loop again
Lean Mean Bean Machine, 18 bytes
O
i
?
_
u $
~
Explanation:
O - Spawns a marble at program start
i - Fetch input and assign to marble's value
? - If marble's value is truthy, spin right, else spin left
_ - Move in direction of spin
u $ - u terminates marble and prints value, $ prints value
~ - Trampoline, move marble to top of field on same column
Yep, Mayube's at it again making another language that'll probably be abandoned in a week. This one's not at all golfy though, and inspired by this challenge
Triangular, 6 bytes
$.(]%<
This formats into the triangle:
$
. (
] % <
The commands that are executed (without control flow) are $(%]. Pretty simple.
$read input as integer(open loop%print as integer]jump back to loop if top of stack is truthy
Noether, 5 bytes
0(IP)
This works very simply:
0 - Push 0 to stack
( - Pop value of stack and loop until top of stack equals popped value
I - Push user input to stack
P - Print top of stack
) - End loop
Unless you want your browser to freeze, I would advise against testing this online at https://beta-decay.github.io/noether
Wise, 3 bytes
[:]
Wise cannot actually output whenever you want, it only outputs the entire stack when the program terminates. So the solution to infinitely output is to simply infinitely fill the stack. When the program eventually halts (never), it will output the stack that, at that theoretical point in time, will have infinite values in it.
Explanation
[:] Implicit input from command-line arg
[ If last value is != 0..
: ..Duplicate last value on stack
] If last value is != 0, jump back to [
Given a non-zero number, will infinitely duplicate the input on the stack, after an infinite amount of time, will terminate and output the entire stack.
Given zero, jumps to the end of the program and immediately terminates, outputting the stack, which contains only the input.
Decimal, 32 bytes
81D301110D412D590D5111D91D30191D
Pretty simple. Explanation:
81D ; builtin to read INT to stack
301 ; print
110D ; push INT 0
412D ; compare for equality, pop values used, push result
5 ; if truthy
90D ; exit
5 ; endif
111D ; push INT 1
91D ; declare jump 1
301 ; print
91D ; exit
MarioLANG, 11 bytes
;>:[<
=====
Explanation:
; Get numerical input and save in current cell
> Move left (Required to make an infinite loop)
: Output the current cell
[ Skip next command if cell is 0
< Move right
Basically, it loops infinitely unless input = 0
Taxi, 617 bytes
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Crime Lab.1 is waiting at Writer's Depot.Go to Writer's Depot:s 1 r 1 l 2 l.Pickup a passenger going to Crime Lab.Go to Crime Lab:n 1 r 2 r 2 l.Switch to plan "z" if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 4 l 2 l.[r]Pickup a passenger going to Cyclone.Pickup a passenger going to Post Office.Go to Post Office:s 1 l 2 r 1 l.Go to Zoom Zoom:s 1 r 1 l 2 r.Go to Cyclone:w.Switch to plan "r".[z]0 is waiting at Writer's Depot.Go to Writer's Depot:n 4 l 2 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.
There are shorter programs but they kept running out of gas. Here's the ungolfed version:
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Crime Lab.
1 is waiting at Writer's Depot.
Go to Writer's Depot: south 1st right 1st left 2nd left.
Pickup a passenger going to Crime Lab.
Go to Crime Lab: north 1st right 2nd right 2nd left.
Switch to plan "z" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 4th left 2nd left.
[r]
Pickup a passenger going to Cyclone.
Pickup a passenger going to Post Office.
Go to Post Office: south 1st left 2nd right 1st left.
Go to Zoom Zoom: south 1st right 1st left 2nd right.
Go to Cyclone: west.
Switch to plan "r".
[z]
0 is waiting at Writer's Depot.
Go to Writer's Depot: north 4th left 2nd left.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.
Aceto, 11 10 bytes
X
p|1
rip^
reads a string and converts it to an integer. | tests for truthiness (1 is truthy, 0 is not) and mirrors horizontally if truthy (in that case moving to the 1). Otherwise, we'll go to we 0, which pushes the 0,print implicit zero and eXit.
If the number was truthy (e.g. 1), we got mirrored to the 1, which pushes a 1, prints, and goes one cell up (^), going into an infinite loop.
Javascript (Node), 40 bytes
for(;console.log(v=process.argv[2])|v;);
In Javascript for the browser this can be 29 bytes
v=prompt();for(;alert(v)|v;);
OIL, 25 bytes
Straightforward, but nevertheless annotated:
5 # read into cell 0
0
10 # if cell 0 is equal to 0 (from cell 1), go to cell 11 (*) else 7 (&)
0
1
11
7
4 # print what's in cell 4 (a zero) &
4
6 # jump to cell 7 (&)
7
4 # print implicit 0 *
REXX, 33 bytes
pull n
do while n
say n
end
say n
Alice, 8 bytes
i.o.&#@#
Explanation
i Read a byte X from STDIN (gives 48 for input 0, 49 for input 1).
.o Duplicate X and print that byte back to STDOUT.
. Duplicate X again.
&# Skip X commands. Since the program contains 8 commands, if X = 48,
this doesn't really do anything. The IP will just loop through the
code six times while skipping all commands. But if X = 49, it skips
one more command, so the next command is skipped.
@ Terminate the program (only gets executed for input 0).
# Skip the i at the beginning of the next iteration.
This code loops indefinitely, unless the @ terminates it on the first iteration.
Deadfish i, 16 bytes
0<+I]
1<.
2<+.[2
As this language does not support input, you must replace I with either an empty string (=0) or + (=1). The program works on my interpreter, which may or may not work like the author of the language intended.
I'm not sure how to score this program. Currently the byte count is for 1-variant.
BitCycle, 7 bytes
Golfed 4 bytes off my example program!
?~<
!~+
Provide input as 0 or 1 on the command-line. The -s or -p debug options are recommended, especially when dealing with infinite output.
Explanation
BitCycle is a 2D language that works by moving bits around a playfield. Commands used in this program are:
?puts input bit(s) onto the playfield, moving east~duplicates and negates a bit, turning the original right and the negated copy left<sends bits westward+turns 1-bits right and 0-bits left!outputs bits
The input hits the first ~. A negated copy turns left (north) off the playfield and is discarded. The original bit turns right (south).
At the second ~, the original bit turns west into the ! and is output. A negated copy turns east.
If the original bit was 0, the negated copy is 1; it turns south at the +, goes off the playfield, and is discarded.
If the original bit was 1, the negated copy is 0; it turns north at the + and then west at the <. The 0 hits the first ~ again, where it turns right (north) off the playfield and is discarded. The negated copy (1) turns left (south), leading to an infinite loop.
Common Lisp, 30
(do((x(read)))((=(print x)0)))
Common Lisp's print function returns the object that was printed. This reads a value from the user, then prints the value until the return value of the call to print returns 0.
WireWorld (It doesnt have a scoring method yet :\)
████ █ <= this pixel will be the input. if it is a electron head (1),
█ █ It will loop forever as 1. if its a wire (0), it will do nothing.
█ ██ █
██ █
██
Pyramid, 14 bytes
+1 byte to specify starting on stack 1 (originally 13 bytes).
1<
b
---
?<
u
Pyramid is my new-old language, which is based off Stackylogic. It has a bunch of extra commands that will (hopefully) make it TC, which include moving up and down multiple "stacks".
Explanation:
1< 1: Move down the stack, and push 0 to the output stack
b Break: outputs the stack, and resets it - also runs the stack again
---
?< Input: 1, 0: If it's 0, move up, push 0 to the output stack,
terminate the program and print the stack
u If the input is 1, move up to stack 0
SmileBASIC, 23 22 bytes
INPUT N@L?N?N/N
GOTO@L
Ends the program with a divide by 0 error.
If this isn't allowed, here's a 23 byte solution:
INPUT N@L?N
IF N GOTO@L
Chip, 6 bytes
e*faAs
Chip is a 2D language that behaves a bit like an integrated circuit. It takes input, one byte at a time, and breaks out the bits to individual input elements. Output stitches the values of output elements back together into bytes.
Let's break this down:
* is a source signal, it will send a true value to all adjacent elements.
e and f correspond to the fifth and sixth bit of the output.
So, e*f produces binary 00110000, which is ASCII char "0".
Now, A is the first bit of input and a is the first bit of output, so aA copies that bit from input to output. So, when combined with e*f, an input of ASCII "0" produces "0", and "1" produces "1". (There is no interaction between f and a, since neither produce any signal.)
The s on the end, when activated by a true signal, will prevent input from advancing to the next byte, meaning that the whole thing will run again with the same input.
Since the first byte of "0" is zero, it won't activate this element and the program will print "0", and thereby exhaust its input, which allows it to terminate. "1", however, activates this element, which means that "1" is output, but not consumed on the input, allowing the cycle to repeat indefinitely.
If values 0x0 and 0x1 are used for output, rather than ASCII, we can eliminate the e*f part, resulting in only 3 bytes:
aAs
If the zero must terminate itself, rather than expecting stdin to close, we get the following, which inverts the first byte with ~, and passes the result to t, which terminates the program (10 bytes):
aA~te*f
s
(t also produces no signal, so there is no interaction between t and e.)
QBIC, 10 bytes
:{?a~a|\_X
Explanation:
: Reads a number from the command line and names it 'a'
{ DO - infinite loop
?a Print 'a'
~a IF 'a': 0 is seen as false, 1 as true
| THEN: Empty THEN block, we want to act on FALSE
\_X ELSE exit the program.
_X accepts one implicit parameter, and prints that parameter on exit.
Since no parameter is given, nothing gets printed.
[IF and DO are implicitly closed by QBIC]
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.
PlatyPar, 2 Bytes
wA
Explanation:
Implicit: push input to the stack.
w: while last item.
A: alert last item.
If you give it something truthy, while(stack[-1]) goes on infinitely. If not, it skips that, and alerts the last item of the stack implicitly (falsy).
Try it online!
Press cancel instead of ok on the alert if you want to stop the loop after giving a 1.
Pushy, 3 bytes
#$#
Extremely simple:
# \ Print input
$ \ While input != 0:
# \ Print input
An input of 0 will print, skip over the while loop, and terminate, whilst any other number is considered truthy and will be printed infinitely.
Haystack, 9 bytes
id?v
|o<o
I'm aware that there already is a Haystack answer, but that answer uses the older version of Haystack, this answer uses Haystack 2016 (and it's much shorter)
Explanation
id Take input and duplicate it
? If input is truthy (1) continue, otherwise (0) go down
If input is truthy...
?v Go down
o Output number
Since this is a 2D language, the IP wraps around and does this infinitely
Also since Haystack (new) doesn't pop the top of stack after outputting
1 can be printed forever without needing to duplicate it
Otherwise...
?
< Go left
o Output number
| Exit program
PHP, 20 bytes
<?L:echo$i;if($i)goto L;# 24 bytes
<?do echo$i;while($i); # Martijn´s first version golfed 24->22 bytes
<?=$i;while($i)echo$i; # Martijn´s second version golfed 24->22 bytes
<?while($i|!print$i); # 21 bytes
<?while($i&print$i); # 20 bytes
Requires PHP <4.2 or PHP<7 with --d register_globals=0.
Save to file, call in browser with <scriptpath>?i=<value>.
explanation for the last version:
print$i is evaluated in any case (no short circuit for bitwise operations).
print always returns true, which, when cast to int (by the bitwise and) evaluates to 1.
For $i=0, 0&1 is 0, hence false and the loop exits.
for $i=1, 1&1 is 1 and the loop continues.
shortest version(s) for current PHP, 29 bytes:
while(($i=$argv[1])&print$i);
while((print$i=$argv[1])&$i);
for($i=$argv[1];$i&print$i;);
Run with php -r '<code>' <value>.
stacked, 10 bytes
[:out]loop
Assumes input is on TOS. Try it here!
Loops [:out] while TOS is truthy, repeating at least once. Surround with [] for a proper function.
PHP, 24 25 27 bytes
<?=do{echo$i;}while($i); // Also 24b
<?=$i;for(;$i&1;)echo$i; // 24b, added PHP's short echo, actually made it less
echo$i;for(;$i&1;)echo$i; // 25b
echo$i;while($i&1)echo$i; // 25b, based on 0/1 as truthy/falsy
for(;$i&1;){echo$i;}echo$i; //27b
This works by setting register_globals=on (which you shouldn't) and that going to the page with ?i=1 or ?i=0 in the url.
The logic is that the first echo will always output the input, and if it's one it'll loop until something gives in (because of & returning 1 (=truthy) for 1).
Jelly, 3 bytes
Ṅ¹¿
If reading from STDIN is absolutely required:
ƈOḂṄ¹¿`
I'm not sure which since "Jelly's main input method is via command line arguments, although reading input from STDIN is also possible."
T-SQL, 22 bytes
s:print @ if @>0goto s
requires a variable with the name @, e.g.:
DECLARE @ BIT = 0
s:print @ if @>0goto s
BrainInt, 5 bytes
&^[!]
Explanation:
& # Take user input, and store in current cell
^ # Boolean-ate current cell (nonzero -> 1, 0 -> 0)
[ ] # Loop (while cell != 0)
! # Print current cell as integer
Underload, 16 bytes
((1)S:^)~^:^(0)S
Underload has no way to take input from standard input. The most natural way to take input is therefore from the initial stack: () for 1, (!()) for 0 (this is the normal way to represent numbers in Underload).
Here are Try It Online links for 0 and for 1 (be prepared to kill this one quickly; the infinite loop runs very quickly and will spam up your browser window).
This program didn't need much effort to golf; the most idiomatic way to do things is almost the shortest (I just had to be careful not to let the input get buried too far on the stack). It's easiest to read if I translate the code to a hypothetical functional language:
function x(y)
print(1)
x(x)
end
x = x^(input)
x(x)
print(0)
The only weird thing happening here is being able to exponentiate functions, but it's a fairly easy-to-understand operation; for example, raising a function f to the power 3 would produce f compose f compose f, i.e. lambda x.f(f(f(x))). Raising a function to the power 1 does nothing (just like if you'd raised an integer to the power 1); and raising a function to the power 0 gives you the identity function (just like raising a number to the power 0 gives you 1). Actually, the integers in Underload are defined in terms of their effect exponentiating functions, rather than the other way round; the operation is fundamental enough to Underload that you use it to construct most flow control.
Fuzzy Octo Guacamole, 8 bytes
^X({@}X)
^ pushes input, X prints the top item on the stack. ( starts an infinite loop. {@} ends the program (@) only if the top item on the stack is falsy, like 0. The X prints the top item on the stack (again), and the ) ends the loop.
So it repeats, printing and checking forever.
Doxical, 11 bytes
[^]A{AdA}dA
First answer in Doxical!
Doxical is my new language, which is designed to be difficult to program in, and is grid-based. Also, there aren't any newlines in Doxical code, so every Doxical program is a one-liner.
Explanation (note that there are no comments in Doxical, this is just for clarification):
[^] # Asks for user input, if input = 1, puts 1 into the Value,
# If 0, puts 0 into the Value
A # Declares variable A as the Value
{A } # While A > 0:
dA # Output A in decimal (1 forever)
dA # Outside the while loop, output A in decimal (0 once)
Yes, "Value" is meant to be capitalised, see docs for more details.
D - 87 bytes
void main(){import std.stdio,std.conv;int i=readln[0..$-1].to!int;do i.write;while(i);}
Valve scripting language, 38 bytes
alias 0 echo 0
alias 1 "echo 1;wait;1"
This defines two commands, 0 and 1. Type 0 into the console for the zero case, and 1 for the 1 case.
Dip, 6 bytes
?_1p?0
Body must be at least 30 characters; you entered 19.
Javascript, 33 32 Bytes
i=prompt();do{alert(i)}while(+i)
uses the +i syntax (thanks ETHproductions)
Old 1
i=prompt();do{alert(i)}while(i>0)
JAISBaL, 15 6 bytes
˗Y1˄N0
Explanation:
# \# enable verbose parsing #\
while \# [0] start while loop #\
printnumln 1 \# [1] print 1 #\
end \# [2] end current language construct #\
printnum 0 \# [3] print 0 #\
PHP, 30 33 bytes
do{echo$o=$argv[1];}while($o);
Oops, didn't see the 7 other pages, one of which contains a better PHP entry.
Old 1
do{echo$argv[1];}while($argv[1]);
Crystal, 48 37 36 bytes
y=gets;y=="0\n"&&(p 0;exit);y=="1\n"&&loop{p 1}
y=gets;y=="0\n"&&(p 0;exit);loop{p 1}
y=gets;y=="0\n"&&(p 0;1/0);loop{p 1}
Edit: Shaved off 10 bytes because the post doesn't specify what should happen on invalid input (like 2). If it does and I misunderstood, let me know.
Edit: Shaved off 1 byte by dying with an error instead of normal exit.
Crystal is statically typed, so I couldn't just do gets.chomp (gets can return nil, and nil doesn't have chomp). The alternative was gets.try &.chomp, but that takes much more space than just having the newlines.
In Crystal (and Ruby) you can do something like puts 0 if y=="0\n", however you can also shave off 2 bytes by doing y=="0\n"&&puts 0 as the && operator returns the last object it tests for truthiness.
loop is a method in the standard lib that infinitely runs the block. It's a much shorter way of writing while true;CODE;end.
p prints the result of .inspect on its arguments to the output. Here I abuse it as a shorter puts because for numbers it'll just return the number.
reticular, 8 6 bytes
[do?!]
This is a function. g calls the function with the TOS as input. do outputs without popping, ?! skips the next char if it's 1. Because of the way functions work, the actual constructed function is:
do?!;
This is made in a child instance of the program. Thus, if the TOS is 0, then it terminates (exits function).
Previous versions:
8 bytes:
indp?!;!
11 bytes:
in@@p;
p1 <
This goes right by @@ if 0, and up if 1 (wrapping around to <) and prints 1 infinitely. It's in better style to do it this way, y'know, more readable. Because 2D languages are easy to read.
ABCR, 7 bytes
iAo7ox
ABCR is a stack-based programming language that allows a few simple operations on any of its three stacks and a single register.
Explanation:
i Numerical input. Places result in register.
A Queue register value to queue a.
o Output peek(a) as a number.
7 while(register){
o output peek(a) again
x }
Moorhen 1 (or original creators version 1 here), 38 bytes
The original language creator has decided to add new instructions, which would change the existing ones. Hence, this language is in Moorhen version one
op pa id el pa id el ai op id ai pi ai
Note this doesn't print if input is 1, because printing only happens at halting, so it just puts infinite ones on stack
Explanation:
Commands can be (most of) all english words, and the command they execute depends on md5 hash mod 7. I used some length two words that corresponded to each of the seven commands
re: push 0
op: increment ToS
pa: decrement ToS
el: rotate stack (place ToS on BoS)
pi: dupe ToS
id: peek TOS, skip if it is non-zero
ai: flip pointer direction
there are two main segments of code
op pa id el pa id el
ai op id ai pi ai
op pa id el pa id el
This code, when run forwards, will have the pointer leave to the right side, with the initial value on the stack, minus one (0 -> -1, 1 -> 0). When run backwards, with [-1] as stack, it leaves the to the left side with [0] as the stack. When it leaves to the left, it will print the stack, items joined with spaces, so it will print 0. It uses "nops", commands that don't do anything under certain circumstances, or are a pair of inverses.
(the reason the comments look funny is because the interpreter ignores non-words, including real words that are hyphenated)
op pa nop-when-running-forwards
id el nop-with-only-one-value-on-stack-and-running-forward
pa decrement-
id el nop-with-only-one-value-on-stack-and-running-forward
[go to next part of code]
with all these nops forward, its essentially pa when running forward. However, backwards, with -1 on stack:
el nop-with-only-one-value-on-stack
id pa skip-pa,when-TOS-nonzero(-1,is-non-zero)
el nop-with-only-one-value-on-stack
id pa skip-pa,when-TOS-nonzero(-1,is-non-zero)
op increment-
[end,print-stack(with,-1,coming-in,print-0)]
With -1, backwards, it's essentially op (then implicit print)
The code that is at the right of that code:
ai op id ai pi ai
given -1, it will just reflect it back. Given 0, it will increment it, then enter a loop of duping ToS, which will be 1.
ai reflect-pointer-direction-if-TOS-non-zero
op increment-
id skip-next-command-if-non-zero. This-command-skips-into-the-middle-of-a-loop:
ai pi ai this-is-the-loop. pointer-starts-on-pi,because-it-skipped-the-first-ai
Here is a visualisation of how it executes
pi dupe-TOS (1)
ai reverse-if-ToS-is-nonzero (it is)
pi dupe-TOS (1) -again
ai reverse-if-ToS-is-nonzero (it is)
pi dupe-TOS (1) -again
... this keeps happening
LI, 4 bytes
?iRP
Explanation:
?i if input is truthy (1):
RP Recurse the program with the printed (implied) input
Else (0 is the only falsy value in LI) return (implied) input,
which is implicitly printed.
Copy, 67 59 bytes
My new esolang :D
getch a
add b a
add b -48
print a
skip b
skip 1
copy -4 0 1
Explanation:
getch a Take input in variable 'a'
add b a Set 'b' to 'a'
add b -48 Substract 48 from 'b'
print a Print 'a'
skip b Skip the copy if 'a' is not zero
skip 1 ^
copy -4 0 1 Copy the code block from the print to this instruction after this instruction
braingasm, 5 bytes
;:[:]
The braingasm instruction ; and : are very similar to the brainfuck instructions , and ..
; gets some input from stdin, reads it as an integer, and stores the integer value in the current cell. : prints the value of the current formatted as an integer. Like in brainfuck, [] loops while the current cell is non-zero.
Logicode, 43 bytes
circ l(a)->1+l(a)
cond binp->out l(a)/out 0
Logicode can't output while in an infinite circuit loop, so this program will output ALL of the 1's after the infinite loop (when the program encounters a 1).
If a truth machine that goes into an infinite loop when 1 is entered and has no output is acceptable, the code can be shorter by 2 bytes:
circ l(a)->1+l(a)
cond binp->out l(a)/out 0
Lua, 34 Bytes
repeat print(arg[2])until arg[2]<1
arg[2] contains the first command line argument, (arg[1] contains the filename)
Give an input through the command line, and it shall spam it if it's 1, or once if it's not.
Simple enough.
Turtlèd, 7 bytes
Turtlèd cannot output without halting, so the truth machine writes down infinite ones, like a turing machine's implementation might, onto the grid if input is 1.
!.{1r.}
Explanation:
! input into string variable
. write current char of string var (by default the first char)
for a single char input, this will be the entire input
{1 } while the current char is 1
this loop is never run if input is zero, but if it is one, it will run
forever, as the last action of the loop writes 1 to the current cell
r move right, so that we constantly move right to write ones to infinite
cells
. write current char of string var (still by default the first char)
this is 1 if the loop was run at all. because the loop runs while the
current cell is one, this will cause the loop to rerun every time.
[implicit] output grid at end of program, program will only end if input isn't 1
dc, 13 12 bytes
?[pd1=@]ds@x
Run:
dc -f truth_machine.dc <<< "1"
Adding to the diversity of languages used, I present a dc solution that works as follows:
? # reads the input and pushes it on top of the stack
[pd1=@]ds@x # stores the macro command [pd1=@] into register '@' and executes it
p # prints the value on top of the stack
d # makes a duplicate that is pushed on top
1=@ # pushes 1, pops two numbers and if they are equal, the macro from
#register '@' is executed (again), thus making an infinite cycle
Straw, 17 bytes
(1>:&)(:&) <1='0>
Cubix, 5 6 bytes
Cubix is @ETHproductions new 2 dimensional language where the commands are wrapped around the faces of a cube. Online interpreter Thanks to @ETHproductions for the saving.
!I\@O
This ends up expanded out to the cube
!
I \ @ O
.
This starts with the I command. Input an integer onto the stack.
\, redirects the instruction pointer down over the no op.
O, outputs the numeric value of top of stack.
!, skip the next command (@) if top of stack true. This will jump the \ redirect if 1
\, redirects the instruction pointer to the @ exit program.
This takes advantage of the fact the stack isn't popped by the O ? ! commands.
Woefully, 266 bytes
First answer in this language!
It's called woefully because the bytecounts are saddening
Woefully is a 2d language with no conditionals, except for the notz/bool command (pop a, push 1 if not zero, else push zero), and combining this with the move char pointer command yields control flow. In a truth machine, the values entered are already zero or one, and are only of two values, so is less complex than some other conditional programs, which kind of defeats the purpose of the truth machine :P
There are two pointers, the instruction pointer (ip), and the char pointer (cp), and it's hard to explain in one post, but the ip goes through the paths, cp stays stationary unless moved by instructions the ip executes.
Woefully has 2 stacks, all pushing is to A, except dupe and AtoB
| || ||||| |
|| |||||| |
||| |||| |
|||| || |
||||| || |
||||| ||| |
||||| |||| |
||||| ||||| |
||||| |||||| |
||||| |
|||||| |
||||||| |
|||||| |
||||| |
|||| |
||| |
|| |
| |
|| |
||| |
||| |
|||| |
||| |
|| |
| |
| |
| |
| |
| |
|| |
||| |
|||| |
||||| |
|||||| |
Explanation (difficult from the size) Execution starts at the v, at the A path:
V FI \/ V shows initial char pointer pos, F the pos after movement
|A||X|||||Z| if input is zero, I if it is 1. The path marked by \/ won't
||A||||||Z| be executed until the first part has been done, and then only
|||A||||Z| #X path halts program if input is zero
||||A||Z| # A path pushes input #Z path pushes one
|||||A||O|
|||||E|||O|
|||||E||||O| #E path dupes, by peeking top of a stack, pushing to b stack
|||||E|||||O| #O path outputs TOS of A
|||||E||||||O|
|||||E| ^End of path, go back to char pointer, still over this path
||||||F| #F path pops a, moves the char pointer
|||||||F|
||||||G|
|||||G|
||||G|
|||G| #G path pushes 4
||G|
|G|
||H| #H pops a, moves char pointer by a. the char pointer is (again)
|||H| #now over F or I, depending on input
|||X| X are nops
||||X|
|||L| L path pushes 1
||L|
|L|
|V| V path multiplies both TOS (A and B), pushes to A
|V|
|V|
|V|
||O|
|||O| O path outputs tos of A
||||O|
|||||O|
||||||O|
End of path, go back to the char pointer. If input was zero, the char
pointer will be over the halting path, so program over, otherwise it's over
the next char, and goes to the infinite one river
Note this is somewhat simplified: paths overlap on the corners they meet at.
Java, 143 141 125 88 bytes
interface T {static void main(String[]a){System.out.print(a[0]);main(a[0].split("0"));}}
Ungolfed Test Code
interface T {
static void main(String[] a) {
System.out.print(a[0]);
main(a[0].split("0"));
}
}
Seriously, 4 3 bytes
,W■
, reads a value from STDIN. W starts a loop that runs while the value on top of the stack is truthy, with the body ■. ■ prints the top stack element without popping. The loop is implicitly closed at EOF.
On input of 0, the loop never executes (since 0 is falsey), and the program ends at EOF, automatically popping and printing every value on the stack. On input of 1 (or any value that is not 0, "", or []), the loop runs infinitely.
In Actually, the leading , is not needed (thanks to implicit input), bringing the score down to 2 bytes.
Python 2, 33 bytes
Golfing suggestions welcome :)
x=input()
while x:print 1
print 0
><>, 6 bytes
Takes input from command line i.e. ./fish.py program.fish -v 1
:?!;:n
Explanation:
: ? !; :n ... (Since this is fish, it wraps around and repeats)
^ ^ ^ ^
| | | |
| | | Duplicates topmost value on stack and outputs it
| | |
| | Skips the next instruction
| |
| Checks if topmost value is 0 and if so, skips the next instruction, going straight to the ; which terminates the program
|
Duplicates topmost value on stack
PHP, 34 bytes
<?for($f=fgetc(STDIN);$f;?>1<?)?>0
Wanted to try to get rid of the print but not sure it's worth it since you have to reintroduce the <? tags
PowerShell, 22 21 bytes
Variable $a into the pipeline, prints once, then prints again if the input evaluates as true. Less elegant than TimmyD's but shorter.
$a|%{$_;while($_){$_}}
After looking at his though it could also be written as below, dropping it to 21 bytes
$a|%{do{$_}while($_)}
C, 41, 40 bytes
main(c){for(c=getchar();putchar(c)&1;);}
Reads a single character from stdin, writes to stdout.
This version is 1 byte longer than feersum's solution, but removes his/her assumptions onstdin.
Churro, 100 95 bytes
{========={o}{*}======}{*}======}{={*}{={o}{={o}{={*}{={o}{======={*}{==={*}{======={*}{===={*}
Explanation
Churro is a stack-based esolang where the only syntax element is, well, churros! Or rather, ASCII-art representations of churros. An example of such a churro is {o}====}.
In Churro, each churro has three characteristics:
- Its orientation; whether it's facing left (
{o}====}) or right ({===={o}). - Its filling; whether it's filled (
{*}==}) or not ({o}==}). - Its tail length; the number of
=s in the churro is the length of its tail.
Left-facing churros are integer literals; their tail length is their value, while their filling status is their sign. Filled churros are negative, while unfilled churros are positive.
Right-facing churros are operators; their tail length is which operator they represent, according to this table:
{{o} pop A; discard A
{={o} pop A, B; push B + A
{=={o} pop A, B; push B - A
{==={o} pop A; if A == 0, jump to churro after matching occurrence of {==={o}
{===={o} pop A; if A != 0, jump to churro after matching occurrence of {==={o}
{====={o} pop A, B; store B in memory location A
{======{o} pop A; push the value in memory location A to stack
{======={o} pop A; print A as an integer
{========{o} pop A; print A as an ASCII character
{========={o} read a single character from STDIN and push it to the stack
{=========={o} exit the program
Filled operator churros have the same behaviour, but peek at the stack instead of popping from it.
With that, here's the ungolfed, explained version of the Churro truth-machine:
{========={o} read char from stdin
{*}======} push -6
{*}======} push -6
{={*} push -6 + -6 = -12
{={o} pop -6, -12; push -6 + -12 = -18
{={o} pop -6, -18; push -6 + -18 = -24
{={*} push input + -24
{={o} pop -24, input + -24; push input + -48 (convert char to int)
{======={*} print input as integer
{==={*} if input == 0 jump to matching churro
{======={*} print input as integer
{===={*} if input != 0 jump back to matching churro
I'm using TheLastBanana's Haskell interpreter to interpret this. Installation instructions can be found there.
Finally, here's the "pure" version (no comments, line length 80, spaces between churros), as output by purify truth.ch:
{========={o} {*}======} {*}======} {={*} {={o} {={o} {={*} {={o} {======={*}
{==={*} {======={*} {===={*}
Saved 5 bytes thanks to Martin Ender!
T-SQL 23 bytes
No STDIN here so a hard-coded variable.
DECLARE @ INT =1; or DECLARE @ INT =0;
and the truth machine is
l:PRINT @ IF(1=@)GOTO l
Perl 6, 28 bytes
{.say;.say while $_}(+slurp)
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...
MarioLANG, 11 8 bytes
;:
[^
=:
This prints a space after each 0 or 1 (as has been clarified is acceptable). The program was tested in the Ruby interpreter. It's not clear whether this behaviour of ^ is according to spec, but it works consistently in this implementation.
As usual, = is just some ground for Mario to walk on.
;reads an integer from STDIN into the current tape cell.[is a conditional. If the tape cell is0, Mario skips the next cell (the^), which will make him fall through the:(printing the0), off the bottom edge and terminate the program (poor Mario). If the tape cell is1, this does nothing, and execution continues.^is a jump command. It stops Mario from moving forward and sends him straight up one cell before he falls back down. For some reason (at least in this implementation) Mario can jump in mid-air provided there's another cell (even a space) below the jump. That means Mario repeatedly jumps into the top:, printing the1, falls back down onto the^and performs another jump. This must be a feature from the popular Super Ninja Brothers spin-off.
Gaot++, 125 bytes
bleeeeeeeeeeet
bleeeet bleeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeeeeeet
bleeeeeeeeet
bleeeeeeeet
Compressed: 11e4e6e13e13e13e13e9e8e6e
Racket, 36 bytes
(do([n(read)])((= n 0)n)(println n))
eacal, 58 bytes
label l
put set n cast number arg number 0
if get n
goto l
put outputs n, which is cast to the first argument. Call like:
node eacal.js tm.eaa <input>
Sesos, 2 bytes
V0
Try it online! Check Debug to see the generated binary code.
How it works
The binary file above has been generated by assembling the following SASM code.
set numin ; Switch to numeric input.
set numout ; Switch to numeric output.
get ; Read an integer from STDIN and save in in the current cell.
nop ; Set an entry marker.
put ; Print the integer in the current cell.
; (implicit jnz)
; If the integer in the current cell is non-zero,
; jump to the previous instruction.
Silicon, 3 bytes
I[]
Explanation:
I Get input
[ While the top of the stack is 1
Implicit output
] End while
Implicit output
Tellurium, 11 bytes
I?1|[i|^;]^
This program asks for input and converts it to an integer (I). After that, it checks if the input is 1. If it's 1, output 1 forever ([i|^;). If it's 0, output 0.
WistfulC, 141 bytes
This C has seen better days.
if only int n were 0...
wish for "%d",&n upon a star
someday !n... wish "1" upon a star
*sigh*
wish "0" upon a star
if wishes were horses...
Obviously not competitive, but then neither is this language.
Rough translation to regular C:
int n = 0;
scanf("%d", &n);
while (n) {
puts("1");
}
puts("0");
exit(0);
PowerShell, 24 bytes
'for(){1}'*"$args"+0|iex
Generate expression as string and pass it to Invoke-Expression (eval).
It casts $args array to string with "", then multiplication sign casts it to int and string for(){1} is repeated int times (1 or 0 - empty string). Then we add 0 to this string, which will be cast to a string also.
Resulting string expression (for(){1}0 or 0) is then piped to Invoke-Expression, resulting either in endless loop outputting 1 or one-time output of 0.
UGL, 6 bytes
il$o:o
How it works:
i #stack.push(input)
l : #while stack.peek():
$ # stack.dup()
o # print(stack.pop())
o #print(stack.pop())
Pyth, 4 3 2
Wp
There is a no! trailing space (thanks isaac :) ). The space used to be required to make the while loop compile, but Pyth has since been updated. Normally that would disqualify using it, but since this is a catalog it should be valid.
Explanation:
Wp : implicit Q = eval(input)
W : while
p : print and return the value of Q, to be evaluated as the while condition
: Functions without enough arguments automatically use Q now
: do nothing in the body of the while loop
Pyke, 4 bytes
I1r
Explanation:
print(top_of_stack) (if first run, print input())
if pop(stack):
top_of_stack = 1
goto_start()
Julia, 51 45 bytes
readline()>"0"?while 2>1 print(1)end:print(0)
Read a string from STDIN. If it's lexicographically larger than the string "0" then print 1 forever, otherwise print 0 and we're done.
Saved 6 bytes thanks to Sp3000!
JavaScript, 27 29 bytes
for(x=prompt();alert(x),+x;);
The only interesting part is the +x which converts x to a number, otherwise the string '0' would return true.
R, 16 28 25 bytes
x=scan();while(x)cat(1);0
Edited to read x
Common Lisp, 34 32 bytes
(if (= 1(read))(loop (print 1)))
Javascript, 33 31 chars
while(alert(x=x||+prompt()),x);
Lua, 56 52 Bytes
I know that this answer in 70 Bytes exists, but its author doesn't look like he's updating it when someone point out an improvement.
if io.read'*n'>0then::a::print"1"goto a end print"0"
Old 56 bytes solution
if io.read()=="1"then while""do print"1"end end print"0"
Nothing special here, just using the fact that "" evaluates to true to save a byte on the infinite loop. Parenthesis for functions parameters aren't mandatory when they only take a single string, which is not stored in a variable.
Reng v.3.3, 6 bytes
i:n?~!
This takes input I, duplicates, outputs as number, ? skips if true. If false, ~ is met and the program ends. Otherwise, we skip ~ then skip i with !, and it repeats.
Oration, 101 bytes
start a function t with x
inhale
to iterate, 1
literally, print x
if not x:break#
invoke t with input
Very long. Starts a function called t with arguments x.
Inhale is a command used to keep the program running, you need oxygen to execute. :P
to iterate, starts a while $1 loop, so this becomes while 1:.
literally, print x just prints x, the function input.
if not x:break# is a simple if statement. The # is there because the compiler appends a : to it, so that becomes if not x:break#:. It happens to be golfier than the following good code with normal syntax.
if not x
goodbye
invoke t with input calls the function.
Transpiles to:
#!/usr/bin/env python3
def t(x):
while 1:
print x
if not x:break#:
t(input("~> "))
Fission, 12 bytes
This is about the shortest I can do at the moment.
*;R?[ X!@J
R # Create a atom heading right
? # Set atom mass to input char
[ # Set direction right
X # Clone atom and sending one back
! # Print the character
@ # Swap mass and energy on atom
J # Jump (48 for 0, 49 for 1)
* # Kill program. Landing spot for 0
; # Kill atom. Landing spot for 1
The length of this program is quite dependent on the landing spots for the Jump command. There is also a requirement for a bit of space between the [ direction setter and the X linear cloner. Otherwise an extra 0 will get printed. The input must be either 0 or 1 for this to work. The input is not validated.
Originally I was going to put up a 18 byte program which is more forgiving on invalid inputs.
R?@YI@0'L
O0'&[X'1
Pylongolf2, 11 bytes
1r1=?1>~<¿
Explanations:
1 push 1 to the stack
r pick a random number between 0 and 1
0= push 1 to the stack and compare them
?1>~<¿ if true, push 1 to the stack then print it forever.
terminate
Befunge, 7 x 2 = 14 bytes
~:#v_.@
>:.
Come Here, 29 bytes
0ASKaCOME FROMa-48 1TELLaNEXT
Wierd, 225 bytes
Unlike other languages where the symbols in a program determine which instructions are executed, in Wierd, it is the bends in the chain of arbitrary symbols that determine which instructions are executed.
From the website:
First, a Riddle:
Q: What do you get when you put three marginally-sane programmers on a mailing list with the Befunge and BrainF*** programming languages?
A: You get BeF***, and then they get Wierd.
...
Chris Pressey then jumped on it, created the angle-to-instruction mapping, and christened the entire mess "Wierd"--a cross between the words "weird" (which the language seemed to be) and "wired" (which would describe the appearance of programs written in the language).
Try it online at http://catseye.tc/installation/Wierd_(John_Colagioia)
0 + ++++ ++++++++++ ++++
1+ +++ +++ ++ + + ++ +
++ + + + + + + + +
+ + + + + +
++++ +++ + ++ +
+ + ++ ++
+++++++++++++++
Beatnik, 26 bytes
J ZD ZD JA K ZZZZJ Z JJ MF
An explanation
Words Scores Action
J 8 Get character value from input
ZD 12 Duplicate TOS
ZD 12 Duplicate TOS
JA 9 Output TOS character
K ZZZZJ 5 48 Push 48 (char 0) onto stack
z 10 Pop 2 from stack and subtract
JJ MF 16 (7) If not zero skip back 7 words
Of course something like the following, while still not making sense, looks more like what you would expect for a Beatnik program.
Shall falsey determine truths? We **WithoutAWarningAboutMemoryUse** printed infinitely yeas!
Gogh, 8 7 6 bytes
Saved a byte thanks to @ZachGates
{ƤØ}?x
Run this in the command line like:
$ ./gogh nio '{ƤØ}?x:' <input>
Explanation
Input is implicit
{ Push this code block
Ƥ Print TOS
Ø Loop forever
}
? If STOS is falsy, remove the codeblock from the stack
x run the code block if there is one, else do nothing
If there is no codeblock, the program will implicitly output 0
NTFJ, 27 bytes
:*:##~~~~~#@|########@|($~^
An online interpreter can be found here.
NTFJ is an esoteric programming language, made by user @ConorO'Brien, that is intended to be a Turing tarpit. It is stack-based, and pushes bits to the stack, which can be later coalesced to an 8-bit number.
- The only pushable values are 0 with
~and 1 with#. - The only manipulations possible to the actual values of the stack are to wrap eight bits into a byte with
@, and to NAND with|. - The only logic command is IF with
(), but combined with JUMP^, it can be used to create loops.
Thus, it's quite difficult to manipulate values to do your bidding.
How it works
Implicit input: byte 48 for 0 or 49 for 1.
:*: Duplicate the top item, pop/output, and duplicate again.
##~~~~~#@| Push 193 and perform NAND.
########@| Push 255 and perform NAND.
These two operations change 48 to 0 and 49 to 1.
( If the top item is not 0:
$ Pop the top item.
~^ Push 0 and jump to that instruction.
This effectively creates a while loop that loops the entire program.
ForceLang, 52 bytes
set a io.readln()
label l
io.write a
if a="1"
goto l
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.
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
Piet, 27 18 16 codels
(Codel is a fancy name for pixel used to avoid confusion when an image is stretched for viewing. I counted codels instead of bytes because piet scripts are saved as images, so the physical size may vary. I think an ideal file format that would save this piet as efficiently as possible would take 11 bytes. In practice, my tiny gif file is 62 bytes, with optimal palette data. Tell me if I should use this as the size of my entry instead of the codel amount.)
In piet, the difference between two colors is what determines which command runs, so seeing the same color twice doesn't mean it does the same action. The execution begins in the top-left codel. Then it moves horizontally, performing the following:
- Read a number and put it on the stack
- Duplicate the top of the stack
- Pop and output the top of the stack
- Pop the top of the stack and rotate clockwise that number of times.
If the input was 1, the cursor then moves down into the lime codel, which pushes 1 on the stack. Then the execution continues going left. When the cursor passes from a color to white and from white to a color, nothing happens. Since black is considered as walls too, the cursor ends up going back to the lime codel on the top line, and repeats the whole thing from step 2.
If, however, the input was 0, the cursor will never go down and will end up in the blue J on the right (pun intended, it was worth it), were it will stay trapped (because the top, right, left and bottom sides of this J-shaped block are next to black codels or the edge of the image). Since the cursor is trapped, execution ends.
Unexpected values:
If the user writes another number, it will still be printed, then the cursor will rotate more or less times based on the value.
- Multiple of 4 or 0: execution continues horizontally and ends.
- Multiple of 3: Since going up is impossible, the cursor immediately rotates clockwise and continues horizontally, then ends.
- Multiple of 2 and not a multiple of 4: the cursor rotates and starts moving to the left. Luckily, all this does is perform a bunch of operations that don't affect the program flow and end up emptying the stack. When an operation can't be done because the stack is empty, it is simply ignored. When it hits the top left corner, the cursor has nowhere else to go but to the right again, effectively restarting the program.
- Other values: The cursor goes down as if it would with 1, which makes it print 1 forever. If the input is 5, the output will be
5111111111111...
Any non-integer value will terminate the program. Execution will continue normally, but all operations will be ignored since there is nothing in the stack. So in a way, the program never crashes - it either stops normally or loops forever.
PietDev friendly version
PietDev (a very basic online Piet IDE) seems to have trouble with white codels so I made a new version which manually rotates back up instead of relying on proper white codel automatic rotation. And I didn't even need to use a new color! If you want to test with it, make sure you draw a black border around the code because PietDev doesn't support custom program sizes.
Older versions
The first version didn't push 1 back on the stack and instead looped back to an earlier duplication instruction. It also had decorative useless codels.
Then I had the idea to push 1 on the stack to remove the blank line. It's funny how I thought of it thanks to my decorative codels.
Then I realized I had an extraneous dup that wasn't needed anymore, and I reduced the number of colors to save up on palette data in the image. I also got rid of the single decorative codel because I don't know.
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.
Piet, 16 14 codels
codel size 10 for better visibility
Pseudocode:
INN → DUP → PTR → OUN → END
↑ ↓
PSH ← OUN
Old solution (16 codels)
Pseudocode:
INN → DUP → DUP → PTR → OUN → END
↑ ↓
DUP ← OUN
Much simpler than the oddly complicated Piet truth machine on esolangs.org.
Works on PietDev and with npiet 1.3a
beeswax, 13 11 8 chars
I could golf the solution down by 3 more bytes. This solution is pretty much a literal translation of my Cardinal solution:
_T> "{'j
Explanation:
_ generate bee/IP
T enter integer, set lstack top value to this value
> redirect bee to right
" if lstack top value>0, skip next instruction
{ output lstack top value to STDOUT
' if lstack top value=0, skip next instruction
j mirror bee direction along | axis
If 0 is entered, the following instructions get executed:
+———————————————————————————— output '0'
↓
_T> "{'
After execution of ' the IP leaves the honeycomb and the program terminates.
And in case of entering 1:
+——————————————————————————— mirror bee direction of movement (to the left)
| +————————————————————————— output '1'
| | +—————————————————————— redirect bee to the right
| | | +—————————————————— mirror bee direction of movement
| | | | +———————————————— output '1'
| | | | | +————————————— redirect bee to the right
↓ ↓ ↓ ↓ ↓ ↓
_T> "'j'{" > "'j'{" > .......
... bouncing back and forth between > and j forever, printing an infinite string of ones.
Clone my beeswax interpreter (written in Julia), language specification and examples from my GitHub repository.
Ruby, 22 bytes
->(n){n==0?0:loop{p1}}
Pylons, 7 bytes.
izwp,1}
How it works:
i # Get command line input.
z # Skip the next instruction if the top of the stack is 0.
wp,1} # While 1 is truthy, print the stack.
DUP, 12 bytes
[[$.$][$.]#]
Anonymous lambda. Usage:
0[[$.$][$.]#]!
or
1[[$.$][$.]#]!
Explanation
[ {start lambda}
[$.$] {output inputnum and check if it's truthy}
[$.] {only output inputnum if previous condition is true}
# {while-loop previous 2 lambdas}
] {end lambda}
Simplex v.0.8, 3 bytes
i¦o
i ~~ take input
¦ ~~ repeat next character until zero byte met
o ~~ output character
AnnieFlow, 6 bytes
010[!"
Here is the decompressed and more readable program:
010101101100000110111111
Breakdown:
010 there are two characters, 0 and 1
1 input is accepted, first symbol popped will be whatever it is
011 there are two stacks, 0 for output, 1 for input
011 1 push occurs when 0 is popped from 1
00 that push is symbol 0 on stack 0 (output 0)
0 pop from the output (halt) when 0 is popped from 1
0011 2 pushes occur when 1 is popped from 1
01 the first push is symbol 1 on stack 0
11 the second push is symbol 1 on stack 1 (replaces the symbol we popped)
1 pop from stack 1, which we just put 1 on, so we loop forever, outputting 1
11 loop forever doing nothing if the input is empty, won't matter
Note: under some interpretations of the language, the trailing 1s can be omitted, and the advanced interpreter does this automatically, also added 0 to the end if there are any trailing 1s. The actual decompression is
01010110110000011
CJam, 16 bytes
qi1={"1o_~"_~}&0
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)
Jelly, 3 bytes
Ȯ¹¿
Try it online! (Keep in mind that online interpreters and infinite outputs aren't precisely compatible.)
How it works
¿ Convert the two previous atoms/chains into a while loop.
¹ Identity function. (condition)
Ȯ Output/print without newline. (loop body)
Detour, 2 bytes
,~
, 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.
Befunge-93+, 7
&>:.:_@
& takes integer input. :.: is a palindromic loop: it duplicates the top of the stack, prints it, and duplicates it again. _ will exit the the loop by moving to the right if the top of the stack is 0. Otherwise it executes the loop again, then > executes the loop again, and so on until the stack overflows. @ terminates the program.
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)
TrumpScript, 54 53 bytes
Say i
As long as,i is "1"?;:
Say i!
America is great.
The longer version:
Tell them what TrumpSaid
As long as , Cruz i is not number "1"?; :
Say what TrumpSaid !
America is great.
Batch, 35 bytes
@IF %1==0 (exit)
:l
@echo 1&goto l
Please, anyone who can golf this more is more than welcome to.
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
Vitsy, 10 5 4 Bytes
New Versions! :D
[DN] [ ] Repeat while the top item is not 0 D Duplicate the top item N Print it out.
I would put a try it online link here, but Vitsy's try it online doesn't output every line as it is output yet.
Pike, 94 bytes
Looks like C, but isn't C. Is interpreted. Is fast.
int main(){int x=(int)Stdio.stdin->gets();if(x!=0){for(;;){write("1");}}write("0");return 0;}
Ungolfed:
int main() {
int x = (int)Stdio.stdin -> gets();
if (x != 0) {
for(;;) {
write("1");
}
}
write("0");
return 0;
}
Mathematica, 36 33 bytes
For[Print[i=Input[]],i>0,Print@i]
Mouse16, 10 bytes
?0+[1!4\]0
Asks for input, then coerces it to an int and tests its truthiness. Then, if it's truthy, 1 is printed and the execution jumps to the 4th byte, where 1 is printed again, and so on forever (until the stack overflows), otherwise, 0 is printed.
Jolf
0 Bytes
I found out what to do with the zero-byte program! I made a truth machine.
Cardinal, 8 chars
%:> J.jN
Explanation
% create pointer
: enter number, put it on top of stack
> redirect pointer to the right
NOP
J skip next instruction if top stack value is > 0
. output number to STDOUT
j skip next instruction if top stack value is = 0
N reflect pointer to the left
The original interpreter, written by Madk, is buggy, and some instructions are missing. I fixed the errors and recompiled the interpreter.
You can clone the fixed interpreter and readme from my GitHub repository.
Staq, 5 chars
'[:]:
Explanation
' input number, put it on top of the active stack
[ jump to corresponding ] if the top stack value = 0 or nonexistent
: output top stack value as number
] jump back to corresponding [ if top stack value >0
: output top stack value as number
Julia, 45 chars
readline()[1]>48?while 1>0 show(1)end:show(0)
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.
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:

Magnified 125x, with color labels:

Rough translation:
*p=readnum
lbl A
print *p
if *p!=0 goto A
Python 2- 64 bytes
x=input()
if x==0:print"0"
elif x==1:
while True: print"1"
ROOP, 12 bytes
I
wX
nw
hO
The w operator reads a number from the keyboard because it has an input object above (I). The input object moves to the right and the number created falls down. The X operator removes the input object, the n operator checks whether the number is zero. If the number is zero, the h operator prints the number and ends the program. If it is nonzero, the number moves to the right and the w operator infinitely prints the number.
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
Java, 95 bytes
class A{public static void main(String[]c){do System.out.print(c[0]);while(c[0].equals("1"));}}
Milky Way 1.0.0, 13 bytes
'?{0b~!~&{!}}
Explanation
' # read input from command line
?{ ~ ~ } # if-else statement
0b # push 0 to stack and compare to the previous TOS
! # output the TOS
&{ } # infinite loop
! # output the TOS
Milky Way (current version), 13 bytes
'?{0b_!_&{!}}
Usage
./mw <path-to-code> -i <input-integer>
STATA, 31 bytes
di _r(a)
m
do{$a
}while($a)
end
First, get input from the user and store it in global variable a. Then switch to Mata for better commands. Print the value of a and then if it is truthy (i.e. 1), go to the start of the loop. If the end keyword is omitted, unexpected end of file (end statement missing) is output to standard error. I'm not sure if that's okay.
Brian & Chuck, 21 bytes
,}<-{-?<SOH>_{+?
_>+{?<.p
Here, <SOH> should be replaced with the corresponding control character (0x01).
Explanation
The basic idea is to subtract the character code of the input (48 or 49) from the p at the end of Chuck, which will either give a ? (which is a valid command) or a @ which is a no-op.
, reads the input character into Chuck's first cell (marked with _). We want to decrement this value down to 0 in a loop, while making some other changes:
}< moves to the p and - decrements it. Then { moves back to the input cell - decrements that as well. As long as this isn't zero yet, ? gives control to Chuck. Now > moves Brian's tape head one cell to the right (which is initialised to 1) and + increments that. Then we reset the loop with {?.
By the time the first cell on Chuck hits 0, the <SOH> cell will have been incremented to the character we've read from STDIN and p will be ? for input 1 or @ for input 0.
Now ? doesn't switch control any more. The 0 or 1 after it is a no-op, as is the null-byte (represented by _). { moves back to Chuck's first cell and + increments to ensure that it's positive, such that ? hands control over to Chuck.
This time >+ increments the cell after the end of Brian's initial tape. That cell is garbage but we'll never use it. Now { doesn't scan all the way to the front of Brian's tape, but only to the _. Hence ? is a no-op because the current cell is zero. Then <. moves one to the left (the copy of the input character) and prints it.
Finally, we encounter the ? or @. If the input was 0 and this cell is @ it's a no-op and the program terminates. But if the input was 1 and this cell is ? we hand over to Brian whose {+? will reset the loop on Chuck, and now we're printing 1s forever (until the integer in the cell at the end of Brian's tape doesn't fit into memory any more, I suppose...).
Bonus
Sp3000 and I have been golfing away at this for several days. We started out around 40 bytes and arrived at two completely different, but tied solutions at 26 bytes. Only when I started to write up the explanation for mine, did the 21-byte solution above occur to me. Many thanks to Sp for throwing ideas around and teaching each other some golfing tricks in B&C. :)
This is his 26 byte solution:
>,----{?{>1?0
#I<?_}<.<<<?
And this is mine:
,{>-<-?_0+?_1{<?
_®{?_{>.?
Where ® is a byte with value 174 (e.g. just save the file as ISO 8859-1).
At the core mine works similarly to the 21-byte solution, in that ® becomes } for input 1 and ~ (no-op) for input 0, but the execution is much less elegant.
His solution is quite neat in that the source code is ASCII-only and that it doesn't require a loop to process the input. Instead, ---- turns 1 into - and 0 into , (a no-op for Chuck). That - will then change the first ? on Brian's tape into a >, thereby creating different control flow for the 1-case.
Groovy, 51 47 bytes
x=System.in.text as int;while(x)print x;print x
Radical.
Go, 93 bytes
Terribly long.
package main
import ."fmt"
func main(){p:=Println
a:=""
Scanln(&a)
if a=="1"{for{p(a)}}
p(0)}
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.)
Microscript, 3 bytes
i{p
The shortest one I know.
Explanation:
i Takes numeric input and puts it in register 1
{ while register 1 is truthy
p Print the contents of register 1
Microscript has implicit printing of register 1 upon termination, which is the reason why an input of 0 gets printed once.
Rotor, 4 bytes
{}|
Contains an unprintable, so here's a hexdump:
0000000: 7b1b 7d7c {.}|
Explanation:
implicit -- evaluate and push input onto stack
{ beginning of block
^[ prints the top value of the stack (without popping it)
}| execute block while top value is truthy
implicit -- print stack
Arcyóu, 19 bytes
(?(#(l))(@ 1(p 1))0
Explanation:
(? (# (l)) ; If-statement on the input as int
(@ 1 ; While 1:
(p 1)) ; Print 1
0 ; Else: Print 0
This is actually three bytes shorter than saving it in a variable and while looping it without the if-statement.
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
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.
Marbelous, 22 bytes
00 .. ..
]] // ..
-O @1 ..
=O .. ..
+O /\ @1
All padding is superfluous in this program, spaces and dots can be removed.
The // sends the 00 marble through the ]] stdin device until there's a byte available, then it drops that byte. -O-O=0 or -O=O check for ascii 48 which is "0", then either the input gets output once or forever (through the @1 loop), incremented back up to the proper ascii value with a +O on the way out.
Motorola MC14500B Machine Code, 2 bytes
In hex:
58EC
Explanation:
5 OR the register with input from the data bus
8 Write the register to the data bus
E Skip next instruction if register is zero
C Jump
The Motorola MC14500B is a 1-bit microcontroller; it has one 1-bit register and a 1-bit data bus. Since the opcodes are 4 bits each, there are only sixteen; half of them carry out a logical operation between the register and the bit on the data bus.
The jump instruction sets a jump flag; when no address is provided, it is common to set the program counter to 0. If the input bit was zero, the processor will not jump. If the input bit was 1, the processor jumps back to the start; since we're ORing with input, it doesn't matter what the input signal is afterwards—the register will then be 1 forever.
As is conventional, the register is initialized to 0.
A list of the opcodes can be found on the data sheet, or here.
Aubergine, 33 24 bytes
=Ao-b1+bi=oA=bB-bA:Ab=ia
Aubergine in a nutshell:
Aubergine has four variables and four 2-argument instructions. The variables a and b can be indirected as A and B to point to locations in the program, which can be read and written just like data, making it inherently self-modifying. The other variables are o, which refers to input or output depending on whether it is the second or first argument of the assignment instruction, and i, which is the instruction pointer. The four instructions are assignment (=), addition (+), subtraction (-), and conditional jump (:). The only constant literal available is 1. All variables are initialized to zero.
Ungolfed:
=Ao Set the first character in the program to input character.
-b1 Set b=-1.
+bi Add 6 to b, yielding 5, which is the location of the "1"
=oA Output the input value.
=bB Set b to the value of where b points, viz. "1"
-bA Subtract the input value from b, yield 0 if "1" and -1 if "0"
:Ab Conditionally jump to the location corresponding to the input
value, either 48 or 49. Either is past the end of the program,
so execution will terminate. This will only happen if b is
nonzero, which happens when the input value was not "1".
=ia If we made it here, then the input was "1" and now a and b are
both zero, just like they were when the program began, so
we jump back to just after the input was read and repeat.
VB.NET, 106 Bytes
Imports c=System.Console
Module m
Sub Main
i=c.readline
1:c.Write(i)
if i=1 then goto 1
end sub
end module
Straightforward, using goto instead of a loop. Compiles with Option Explicit and Option Strict Off, and Option Infer On
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.
WTFZOMFG, 5 bytes
/\(\)
Explanation:
/ input a decimal number and store it in the cell
\ print it
( ) while the cell is not 0
\ print it
Quipu, 20 bytes
\/1&
/\/\
1&??
>>
::
Squirrel, 48 bytes
local a=stdin.readn('b')-48;do print(a) while(a)
ResPlicate, 39 38 bytes
0 -49 12 1 48 9 0 49 4 2 0 49 4 2 48 0
This was one of the earliest examples I made after implementing this language, so I have simply copied it from the linked wiki article, which I largely wrote. Actually, having rewritten my old version to shorten it by a byte, I can now say this example was written for this catalogue.
ResPlicate in a Nutshell
Programs in ResPlicate are all comprised of a list of integers, which are inserted into a queue in order. Each step, the first two integers are popped as x and y. Then a list of x integers is popped (and padded with zeros if the queue had fewer than x elements) and re-enqueued y times. This is quite sufficient to ensure Turing-completeness. Indeed, it is even Turing-complete in the limited case that y is not allowed to exceed 2.
This simple language is extended with I/O in the following way: If x is zero and y is positive, y is output as a character. If x is zero and y is negative, a character is read from input, y+1 is added to it, and the result is enqueued.
Ungolfed:
Thus, the above program can be read like this:
0 -49 Read a character from input, subtract 48 from its value.
If the input was 1 or 0, this will cause the corresponding
integer value to be pushed onto the queue.
12 1 [48 9 ... 48 0] Move the next 12 integers to the end of the queue.
This brings the input integer to the front of the queue.
So now execution follows two completely different paths depending on the value of the input. If it was "0", it continues like this:
(0) 48 The input zero and "48" are popped, causing the character
with value 48 ("0") to be printed.
9 0 [49 4 2 0 49 4 2 48 0] Pop and discard the next 9 integers, emptying the queue.
An empty queue terminates the program.
If the input was "1", the program continues thusly:
(1) 48 [9] Enqueue 48 times the number 9.
0 [49] Print the character with value 49 ("1").
4 2 [0 49 4 2] Place "0 49" (print "1") at the end of the queue,
followed by a copy of this command.
48 0 [9 9 ... 9 9] Discard the 48 9's that were enqueued earlier.
At this point, the queue contains only "0 49 4 2 0 49 4 2", which will repeatedly print "1" and then restore the queue to precisely this state, ensuring that it will continue in this manner forever.
Arnold C, 134 bytes
IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP 0 //or 1
STICK AROUND i
TALK TO THE HAND 1
CHILL
TALK TO THE HAND 0
YOU HAVE BEEN TERMINATED
While this isn't as entertaining as the other ArnoldC answer, it's golfed. For example, indentation is unnecessary, and so are the macros @NO PROBLEMO and @I LIED.
Tested with this version of the language, which cannot take input.
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'.
Java, 90 97 bytes
class T{public static void main(String[]a){while(a[0].equals("1"))System.out.println(1);}}
I'm not sure if this counts because it takes 1 or 0 as an argument rather than STDIN. It's been emotional, either way.
Edit: The above does not print zero, the below does:
class T{public static void main(String[]a){do System.out.println(a[0]);while(a[0].equals("1"));}}
PHP, 33 37 39 29 bytes
Pretty straight forward:
for($f=fgetc(STDIN);$f&print$f;);
Runs from command line:
php truth.php 1
Edits
- Added 10 bytes as the program must take input from STDIN if possible. Thanks to Martin Büttner for pointing it out. :)
- Saved 2 bytes by using
ifandforinstead ofwhile. Thanks to BLackhole - Saved 2 bytes by placing everything into the
for-loop. Thanks to fschmengler. - Saved 2 bytes by rewriting the 2nd expression of the
for-loop.
Minecraft, 18 Bytes (MC Version 15w45a)
As you can see, there is a lever directed into the repeating command block, which has the command say 1 in it. There is an signal inverting torch on top of that, which directs power into the single-run command block with the command say 0 in it.
Whenever the switch is directed towards truthy, the repeater block uses the code say 1 to output infinite 1s. When the lever is redirected to false, it outputs a single 0.
Note that this outputs a [@] by default. If you really want just straight up 1s and zeros, this becomes 34 bytes, where the code in the command blocks are tellraw @a [1] and tellraw @a [0]. This is using @Cᴏɴᴏʀ O'Bʀɪᴇɴ's suggested byte count for MC as can be found in Meta.
Brainfuck, 41 36 31 30 bytes
Shortened by printing once right after input and with help from Ethan and user46915.
,.+++[->>+<-----<]>>---<-[>.<]
Previous version: Subtract 48 from the input, and if it's not zero, add 1 to the 48 to print ASCII 1 forever, otherwise print 0.
-[>+<-----]>--->,<[->->+<<]>[>+<]>.<[>.<]
I ran it here, but due to buffered output, you cannot see any output since the program never terminates on 1.
Edit: I had forgotten to print 0 on input 0. Fixed now. I like the >.< faces at the end.
LOLCODE, 119 bytes
GIMMEH n
n R SUM OF n AN 0
BOTH SAEM n AN 0, O RLY?
YA RLY
VISIBLE 0
NO WAI
IM IN UR l
VISIBLE 1
IM OUTTA UR l
OIC
Ungolfed:
HAI
BTW, Read n as a string from STDIN and convert to an integer
GIMMEH n
n R SUM OF n AN 0
BTW, Test n for equality with 0
BOTH SAEM n AN 0, O RLY?
YA RLY
BTW, Write 0 to STDOUT and exit
VISIBLE 0
NO WAI
BTW, Loop forever, printing 1
IM IN YR l
VISIBLE 1
IM OUTTA YR l
OIC
KTHXBYE
Python 2, 46 bytes 34 bytes
x=input()
print x
while x:print x
Basically, it takes in the input, when 1, prints forever (while loop), but if it isn't 1 (when it is zero) it prints and then exits.
This is my first answer! Yay!
Thue, 34 bytes
1::=12
2::=~1
0::=~0
@::=:::
::=
@
Explanation:
1::=12 Instances of the substring "1" can become "12"
2::=~1 Instances of the substring "2" can be removed, printing "1"
0::=~0 Instances of the substring "0" can be removed, printing "0"
@::=::: Instances of the substring "@" can be replaced with strings from the input
::= End list of substitution rules
@ The initial string is "@"
Befunge-98, 7 bytes
&:.:j@#
Explanation:
& Read integer
: Push copy
. Print the copy
: Push another copy
j Jump that many characters to the right
q Terminate program (jumped over if input was 1)
# Skip next instruction
(And implicitly loop back to the start)
><>, 15 bytes
i6% \
::n?!;>
i Input character (by code point)
6% Modulo the top item on the stack by 6
\ go to second layer
:: Duplicate the top item on the stack twice
n Print the top item of the stack as an integer
?! If the top item on the stack is 0:
; End program.
> Otherwise, move forward.
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.
HSPAL, 60 bytes
110000
000000
420000
400000
420000
400000
120000
030000
040000
010000
Burlesque, 6 bytes
riqJw!
Explanation:
ri -- read int
qJ -- shortcut for {J}, which is a shortcut for {^^}
^^ = duplicate
w! -- while loop
Mind you that the reference implementation of the interpreter buffers output so you'll run out of memory sooner or later before seeing any output in case you provide "1" on STDIN.
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)
TML, 14 bytes
d={1 or 0}/0000-1111/
e.g
d=1/0000-1111/
or
d=0/0000-1111/
Finally I was able to use my language for something :) Since TML hasn't got an IO support (yet), the value must be hardcoded in the tape, but it should work as intended! If the value is 0 it halts (goes to card 0), else it will print an infinite string of 1s
Otherwise I have a 2 cards solution using the default tape:
{0 or 1}/0000-1112/0112-1112/
Atari Basic, 47 bytes
If I remember the syntax correctly, it will be something like this:
1 input a$
2 IF a$="0" THEN end
3 ? a$
4 goto 3
Please correct me if I'm wrong.
Python 2, 43 42 41 bytes
x=raw_input();print x
while x>'0':print x
Got a syntax error at the while loop if I tried to run it as a one-liner. Not really sure why.
EDIT: Knocked off a semicolon.
Knocked off ANOTHER semicolon that I put on there because I've been looking at C too much lately.
Scala, 46 bytes
if(readInt==0)print(0)else while(2>1)print(1)
Kinda uninteresting and obvious, but there we go
AutoHotkey, 20 bytes
I recently got into AutoHotkey and have been waiting for a suitable challenge to try my skills at.
$0::Send 0
1::Send
This takes input by listening for key presses and outputs via simulated key presses. The $ on the first line forces the first hotkey to take input through the keyboard only, so it just outputs 0 when the 0 key is pressed. The second is not so lucky though. When it detects the 1 key being pressed, it presses the 1 key, which it detects, so it presses 1, which it detects and so on. AutoHotkey unfortunately doesn't like this, but that can probably be fixed by adding #HotkeysInterval 1 to the top of the program. I am not brave enough to try this though, as it will probably crash my computer.
If input and output through key presses is invalid, here's a solution that avoids it:
InputBox, a
MsgBox %a%
While a{
MsgBox 1
}
APL, 6 bytes
→⎕←⍣⍲⎕
Explanation:
⎕ Read the input, then
⎕← write it out
⍣ repeatedly
⍲ until NAND of it with itself becomes true.
→ Branch to zero to avoid printing the result again.
Hexagony, 6 bytes
This was surprisingly tricky, and I'm not convinced it's optimal...
<.@!$?
After padding and unfolding the code, this represents the following hex grid:
This uses a similar control flow like my recent error-free cat program, moving along anti-diagonals. To achieve that we start by deflecting the instruction pointer (IP) to the left, where the purple path wraps around to the lower left corner.
? reads the input as an integer. ! prints it back. . is just a no-op. Now the corner of the grid acts as a branch:
If the input was 0, the IP will continue along the red path, which simply terminates the program with @.
If the input was 1, the IP will continue on the green path. Again, . is just a no-op, but $ is the equivalent of Befunge's trampoline: it skips the next instruction. After wrapping, the next instruction would be the ?, but due to $ execution actually continues on the blue path, starting with ! to print another copy of the 1. This loop which only contains !..$ is now repeated indefinitely.
A study of control flow in Hexagony...
I believe the above solution is optimal. I've written a brute forcer, which checks all 6-byte Hexagony programs, which contain at least one each of ?!@ (which are necessary; I've also checked : and % in place of @ to terminate with a division-by-zero error, but that didn't help either). The check prints all the programs which a) produce a 0 on input 0 and terminate and b) produce at least two 1s (and nothing else) and don't terminate within the first 60 ticks of the program (200 ticks for 5-byte solutions). I doubt that any valid solution would take more than 200 ticks to correctly print the first 0 or the second 1 on such a small grid, so I don't think I've missed out on any potential solutions.
The search didn't yield any results for 5 bytes, but 57 results for 6 bytes (using @; there's no need to terminate with an error if we can solve this cleanly in the same amount of bytes). Of those 57 only 6 were false positives which actually printed only two 1s and then entered an infinite loop without printing any more. One solution was listed twice because it contained two ! commands. That leaves exactly 50 valid solutions.
There is a certain amount of degeneracy between the solutions where one or two characters are not substantial, e.g. because they're effectively no-ops anyway. The solutions can be grouped into 23 sets of genuinely distinct programs (in some cases, there is only a single character difference between two sets, but it changes the control flow substantially, so I've counted them separately). Two of the groups even make use of multiple instruction pointers in a very unexpected way. As I would never have come up with most of these ways to use the branches and mirrors, they make a very interesting study of what sorts of control flow are possible in Hexagony, and I have definitely learned some new tricks for future golfs.
The overall control flow is almost always the same: read a number, print it. If it's 0 find a way to the @, if not keep looping through the ! while mainting an edge value of 1. There are four notable exceptions:
- One solution (the one with two
!) prints two1s per iteration through the grid, therefore printing about twice as fast as the majority of programs. I've marked this one withx2below. - A few solutions (those which contain an
o) replace the1with a111(the character code ofo), so they print three1s per iteration, making them print about three times as fast as the majority of programs. I've marked these withx3below. - Two solutions append a
1to the edge value in each iteration (so1-->11-->111--> ...). Those print very fast, but they'll run out of memory eventually. I've marked these withOoMbelow. - Two solutions enter a very tight loop which merely bounces back and forth over the
!, printing on every other tick (instead of of every 5th or so), which makes them slightly faster (and neater). I've marked these with><below.
So here is the entire zoo:
#1 #5 #12 #19
?!/$.@ ?$!>$@ .?!/$@ |!|?$@ # ><
?!/$1@ # OoM ?$!|$@ =?!/$@
?!/$=@ #20
?!/$\@ #6 #13 $@.?<!
?!/$o@ # x3 ?/!<|@ .?/!$@ $@1?<! # OoM
?!/$!@ # x2 =?/!$@ $@=?<!
#7 $@o?<! # x3
#2 ?\!<|@ #14
?!>$)@ \!?__@ #21
?!>$1@ #8 _>_!?@
?!>$o@ # x3 ?<!>$@ # >< #15
?!|$)@ \_?!$@ #22
?!|$1@ #9 <!@.$?
?!|$o@ # x3 ?\$!@$ #16 <!@/$?
\_?!_@ <!@=$?
#3 #10 <$@!$?
?!|)$@ ?~#!@) #17 <.@!$?
?!|1$@ ?~#!@1 $$?\@! </@!$?
?!|o$@ # x3 <=@!$?
#11 #18
#4 ?$)\@! \$?\@! #23
?_!<@> ?$1\@! <<@]!?
?$o\@! # x3
The following is a short walkthrough for a handful of the more representative groups. Especially groups 10 and 23 are worth checking out. There are many other interesting and sometimes convoluted paths in the other groups, but I think I've bored you enough at the end of this. For anyone who really wants to learn Hexagony, these are definitely worth investigating though, as they exhibit even more possible uses of the mirrors and $.
Group 1
This one isn't much more elaborate than my original solution, but the paths go in different directions. It also allows for the largest number of variations in a single cell, as the right-most no-op can be replaced with 5 different commands which still make this valid without changing the structure:
Group 2
This one is quite interesting, because it only moves horizontally. After wrapping to the >, the IP reverses immediately, taking the branch in the corner. It's not entirely well visibly no the diagram, but in the case of the 1 we traverse the first row again, but backwards this time. This also means we run into ? again, which now returns 0 (EOF). This is fixed with ) (increment) to keep printing 1s. This also has 5 variations, as ) could also be 1 or o, and > could also be |:
Group 3
This one looks almost identical to the previous one but it's messy as hell. Up to hitting | and then traversing the bottom or top row it's the same. But in the case of a loop, the $ now skips over the ) onto the mirror. So we follow the turquoise path to the right, now hit the increment, skip over the @ before we wrap around to the | again and then go back to the green path at the top.
Group 4
I thought this one was particularly nifty:
The _ mirror in the top right corner is initially a no-op, so we print with ! and hit the <. The 0 path now hits the horizontal mirror and terminates. The 1 path takes a really interesting trajectory though: it deflects down, wraps to the !, gets redirected towards the horizontal and then wraps back to the ! again. It then keeps moving in this rhombus shape, printing twice per iteration (every third tick).
Group 8
This is one of the two solutions with a really tight printing loop:
The < acts as the branch. After wrapping twice, 0 hits @. 1 on the other hand, first skips the ?, then > sends it onto the the $ again, so that is skips the @. Then the IP wraps into the turquoise path, where it bounces back and forth between the > and < (wrapping around the edge in between).
Group 10
One of two groups which use other instruction pointers, and it's absolutely beautiful. Hexagony has 6 - each one starts from a different corner along the clockwise edge, but only one of them is active at a time.
As usual, we read with ?. Now ~ is unary negation: it turns the 1 into a -1. Next, we hit the #. This is one way to switch between IPs: it takes the current edge value modulo 6 and switches to the corresponding IP (IPs are numbered from 0 in the clockwise direction). So if the input was 0, then the IP simply remains the same, and travels boringly straight ahead into !@. But if the input was 1, then the current value is -1 which is 5 (mod 6). So we switch to the IP which starts on the very same cell (the green path). Now # is a no-op and ? sets the memory edge to 0. ) increments so ! prints a 1. Now we hit ~ again to ensure that # is still a no-op (as opposed to switching us to IP 1 which would terminate the program). It's mindblowing how well everything fits together in this little program.
Group 22
Just to note, this is the group my original solution is in. It also happens to be largest group, because the no-op can be in two different places, and there are several choices for the actual (effective no-op) command.
Group 23
This is the other group using multiple IPs. In fact this one uses 3 different IPs. The top right corner is a bit of a mess, but I'll try to walk you through this:
So, the beginning you've seen before: < deflects North-East, ? reads input. Now ] is another way to change between IPs: it hands control to the next IP in clockwise order. So we switch control to the turquoise path which (I know it's hard to see) starts in the North-East corner going South-East. It is immediately reflected by the < so that it wraps to the South-East corner, going North-West. It also hits the ] so we switch to the next IP. This is the grey path starting in the East corner, going South-West. It prints the input, then wraps to the North-East corner. < deflects the path into the horizontal, where it is reflected by the other <. Now the right-hand < acts as a branch: if the input was 0, the IP moves North-East, and wraps to the @. If the input was 1, the IP moves to the !, wraps to the lef-thand < where it is reflected... now in the corner, it wraps back to the !, gets deflected by the the right <, reflected by the left < and the paths starts over...
Quite a mess, but a beautiful mess. :)
Diagrams generated with Timwi's amazing HexagonyColorer.
Swift, 187 bytes
import Foundation
let i = Int("\(String(data: NSFileHandle.fileHandleWithStandardInput().availableData, encoding: NSUTF8StringEncoding)!.characters.first!)")!
print(i)
while i>0{print(i)}
Sadly this has to read from stdin if it can :( Would be so much smaller if I could just declare it inside...
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. :-)
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
Ruby, 20
print while/1/||gets
Run from the command line to avoid warnings, as
ruby -e "print while/1/||gets" <<< 0
ruby -e "print while/1/||gets" <<< 1
Explanation:
Less golfed, this is
while /1/ || gets
print
end
When a Regexp is used in a conditional, it evaluates as falsey unless the variable $_ is populated and matches the pattern. On the first time through the loop, $_ is empty so we fall through to gets, which sets the value of $_ to a line read from STDIN. print with no arguments prints $_. Now we evaluate the conditional again. If we read in 1, we short-circuit and just print 1 again, and so on forever. Otherwise, we fall through to gets, but since there's no second line of input, gets returns nil, so the loop ends.
><>, 6 bytes
::n?!;
Pushes the input on the stack to start
: copy top element on stack
: copy top element on stack again
n pop and outputs top element
? condition trampoline - pops top element, if it is zero skips next instruction
! trampoline skips next instruction
; finish execution
LaTeX, 97 bytes
\documentclass{proc}\begin{document}\typein[\q]{}\loop\typeout{\q}\ifnum\q=1\repeat\end{document}
I guess it's sort of a grey area since everything is generated at compile time. Prints 1s to "stdout" until it runs out of memory or one 0 depending on input.
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);
}
}
><>, 7 bytes
i2%:n:,
This uses the fact that ><> pushes -1 on EOF, which is 1 mod 2. It also uses divide by 0 for termination (which is apparently okay since the consensus is that STDERR output is ignored).
Just for reference, exiting cleanly without errors is an extra byte:
i2%:n?!;
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.
Loader, 30 bytes
run from m.ldr (or replace the m in the last line with the name of the file)
~B:set B =@IN
print B
B:load m
Theoretically infinite, in practice will result in Error: Stack Overflow in the reference implementation.
With comments:
~B:set B =@IN !!If B is zero (the default for uninitialized variables), set B to a number from the input
print B !!Exactly what it says on the tin
B:load m !!If B is nonzero, load a separate instance of this module on a copy of the current memory space
Math++, 11 bytes
?>a
a
2*a>$
Explanation:
1:Set a to a number from the input
2:Print a (the designator ">out" is implied if none is specified)
3:If a is 1, go to 2; if a is 0, exit
Batch, 31 bytes
@IF 0%1==01 echo 1&%0 1
@echo 0
On my machine, running <script name> 1 twice from the command prompt caused CMD to crash. The first time it stopped after printing a lot of lines with 1s on it. (Presumably because of CMD running out of memory.)
Explanation
@ – This tells CMD not to print the commands on this line. (Output will still be printed.)
%1 – This will be substituted with the first argument given.
%0 – This will be substituted with the script name.
The first line will output 1s and then launch the script itself with an argument 1 if the script was called with the argument 1. Otherwise, the condition evaluates to false and the script will proceed to the second line. It will then output 0 and exit.
C, 37 bytes
A different take on how to do it in C.
main(c){for(gets(&c);putchar(c)&1;);}
c defaults to an int of value 1. gets(&c) gets a string from stdin, here clobbering the value of c, hackishly since c is not a char*. putchar(c) prints the value of c to stdout, and returns c. Since '0' is 48 and '1' is 49 in ASCII, we can use the last bit (&1) to determine which it is. If it's '0', the loop breaks. Otherwise, it goes forever.
Compiles (with a warning about gets) and runs under gcc-4.8 on Linux.
JavaScript, 28 bytes
For loops are often shorter than while loops.
alert(x) returns undefined, which is falsy, so the bitwise or operator, |, casts it to 0. Thus, if x is "0", alert once, otherwise keep looping. Uses alert for STDOUT like this answer.
for(x=prompt();alert(x)|x;);
Batch, 44 bytes
@set/p n=
:a
@echo %n%
@if %n%==1 goto :a
Explanation
set /preads from stdin into a variable:ais 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.
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.
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
SWI-Prolog, 45 bytes
m(X):-put(X),(X=48,halt;m(X)).
:-get(X),m(X).
The put and get predicates work with character codes, so we need to test against 48 for the 0 case. If that succeeds, halt; if it fails, try m(X) recursively instead.
To run from Linux command-line, put the code in a file and execute swipl -qs truth.pro. (The q is optional; it suppresses extra output from the interpreter.) Or, try it here.
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.
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
Perl, 18 + 1 = 19 13 + 1 = 14 bytes
print while$_
Run like this:
echo -n NUM | perl -p truth.pl
Thanks to ThisSuitIsBlackNot (who is way better at Perl golfing than me) for golfing off five bytes.
???, 37 bytes
?!";.;.--,'",'";,-,,,,,'";...'";!-'"
This is a simple translation of mbomb's Brainfuck solution.
C++, 83 77 76 bytes
#include<iostream>int main(){int n;std::cin>>n;do{std::cout<<n;}while(n);}
Ungolfed:
#include <iostream> // Needed for IO
int main() // Necessary for any C++ program
{
int n; // Declare integer variable
std::cin >> n; // Retrieve input from STDIN
do // Perform the following at least once
{
std::cout << n; // Output number, either 0 or 1
} while(n); // Continue doing so if number wasn't 0
}
Thanks to @feersum for letting me know that input can only be 0 or 1 I saved 6 bytes.
Thanks to @Alex A for saving another byte by removing a space
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
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
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
pb, 21 bytes
^t[B]v<w[B!48]{>b[T]}
There is currently only one pb interpreter. It's called pbi and it's hot garbage. I wrote it, and I have 0 other experience writing that kind of program. The pb variables are global variables in pbi's source code, loops are implemented recursively (the tokenizer turns the entire code of the loop into a single token, then when it's reached that token is sent back into the tokenizer and is executed until the condition becomes false), the function to evaluate an expression is def expression(e): return eval(e, globals())... overall it manages to do basically nothing right and I'm probably going to rewrite it.
I bring this up because pbi in its current state only outputs anything when the program terminates, so a 1 input makes it look like it does nothing forever. Here are the reasons why I believe this answer is valid anyway:
- The canvas is being written to, which is how output works in pb. If the loop were to eventually terminate somehow, a lot of 1s would be outputted at once.
- There is a way to watch program execution in pbi. It's intended for debugging and it's about as horrible as the rest of the interpreter, but the flag
-d=followed by a number will print the canvas and pause execution for that many milliseconds after each tick.
How it works
^ # Move the brush to Y=-1, where input lives
t[B] # Save the value at (0, -1) to T
v< # Go to (-1, 0)
w[B!48]{ # While the space under the brush doesn't have the value 48 ('0'):
# (this loop is guaranteed to be entered at least once)
> # Increase the brush's X coordinate by 1
b[T] # Save the value in T to the brush's current coordinates
} # If the input was '0', the space under the brush has the value 48 and the loop is
# terminated. Otherwise, it repeats indefinitely.
JavaScript, 32 bytes
x=prompt();do{alert(x)}while(+x)
On input of 0, alerts 0 to the user; on input of 1, forever alerts 1. If alert is not a suitable alternative for STDOUT, replace it with console.log and add 6 to the byte count.
Edit: I've been solidly beat by @intrepidcoder; see this answer.
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 for0, 49 for1)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. Prints0.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. Prints1.<- Unconditionally point the beam to the left.@- Output the beam as an ASCII character. Prints1.>...
...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!
Python 2, 29 bytes
a=input()
while 1:print a;1/a
This terminates with a division error on 0, which is allowed by default.
Browser LiveScript, 54 bytes
switch prompt!
|'0'=>alert 0
|'1'=>while true
alert 1
I believe I can use prompt and alert instead of STDIN and STDOUT with browser languages, is that correct?
Ouroboros, 11 7 bytes
Inspired by Sp3000's ><> answer.
r.*.n!(
Each line of code in an Ouroboros program represents a snake eating its tail.
r reads a number from input, or -1 for EOF. .* squares it, keeping 0 and 1 the same but mapping -1 to 1. .n outputs the number, leaving a copy on the stack. Finally, !( logically negates and eats that many characters of the end of the snake. If the number was 0, this eats one character, the (, which is also the current instruction. Since the instruction pointer was swallowed, the snake dies and the program ends. If the number was 1, this eats zero characters, and execution loops back to the beginning of the snake, repeating indefinitely.
Try it:
// Define Stack class
function Stack() {
this.stack = [];
this.length = 0;
}
Stack.prototype.push = function(item) {
this.stack.push(item);
this.length++;
}
Stack.prototype.pop = function() {
var result = 0;
if (this.length > 0) {
result = this.stack.pop();
this.length--;
}
return result;
}
Stack.prototype.top = function() {
var result = 0;
if (this.length > 0) {
result = this.stack[this.length - 1];
}
return result;
}
Stack.prototype.toString = function() {
return "" + this.stack;
}
// Define Snake class
function Snake(code) {
this.code = code;
this.length = this.code.length;
this.ip = 0;
this.ownStack = new Stack();
this.currStack = this.ownStack;
this.alive = true;
this.wait = 0;
this.partialString = this.partialNumber = null;
}
Snake.prototype.step = function() {
if (!this.alive) {
return null;
}
if (this.wait > 0) {
this.wait--;
return null;
}
var instruction = this.code.charAt(this.ip);
var output = null;
console.log("Executing instruction " + instruction);
if (this.partialString !== null) {
// We're in the middle of a double-quoted string
if (instruction == '"') {
// Close the string and push its character codes in reverse order
for (var i = this.partialString.length - 1; i >= 0; i--) {
this.currStack.push(this.partialString.charCodeAt(i));
}
this.partialString = null;
} else {
this.partialString += instruction;
}
} else if (instruction == '"') {
this.partialString = "";
} else if ("0" <= instruction && instruction <= "9") {
if (this.partialNumber !== null) {
this.partialNumber = this.partialNumber + instruction; // NB: concatenation!
} else {
this.partialNumber = instruction;
}
next = this.code.charAt((this.ip + 1) % this.length);
if (next < "0" || "9" < next) {
// Next instruction is non-numeric, so end number and push it
this.currStack.push(+this.partialNumber);
this.partialNumber = null;
}
} else if ("a" <= instruction && instruction <= "f") {
// a-f push numbers 10 through 15
var value = instruction.charCodeAt(0) - 87;
this.currStack.push(value);
} else if (instruction == "$") {
// Toggle the current stack
if (this.currStack === this.ownStack) {
this.currStack = this.program.sharedStack;
} else {
this.currStack = this.ownStack;
}
} else if (instruction == "s") {
this.currStack = this.ownStack;
} else if (instruction == "S") {
this.currStack = this.program.sharedStack;
} else if (instruction == "l") {
this.currStack.push(this.ownStack.length);
} else if (instruction == "L") {
this.currStack.push(this.program.sharedStack.length);
} else if (instruction == ".") {
var item = this.currStack.pop();
this.currStack.push(item);
this.currStack.push(item);
} else if (instruction == "m") {
var item = this.ownStack.pop();
this.program.sharedStack.push(item);
} else if (instruction == "M") {
var item = this.program.sharedStack.pop();
this.ownStack.push(item);
} else if (instruction == "y") {
var item = this.ownStack.top();
this.program.sharedStack.push(item);
} else if (instruction == "Y") {
var item = this.program.sharedStack.top();
this.ownStack.push(item);
} else if (instruction == "\\") {
var top = this.currStack.pop();
var next = this.currStack.pop()
this.currStack.push(top);
this.currStack.push(next);
} else if (instruction == "@") {
var c = this.currStack.pop();
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(c);
this.currStack.push(a);
this.currStack.push(b);
} else if (instruction == ";") {
this.currStack.pop();
} else if (instruction == "+") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a + b);
} else if (instruction == "-") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a - b);
} else if (instruction == "*") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a * b);
} else if (instruction == "/") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a / b);
} else if (instruction == "%") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a % b);
} else if (instruction == "_") {
this.currStack.push(-this.currStack.pop());
} else if (instruction == "I") {
var value = this.currStack.pop();
if (value < 0) {
this.currStack.push(Math.ceil(value));
} else {
this.currStack.push(Math.floor(value));
}
} else if (instruction == ">") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(+(a > b));
} else if (instruction == "<") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(+(a < b));
} else if (instruction == "=") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(+(a == b));
} else if (instruction == "!") {
this.currStack.push(+ !this.currStack.pop());
} else if (instruction == "?") {
this.currStack.push(Math.random());
} else if (instruction == "n") {
output = "" + this.currStack.pop();
} else if (instruction == "o") {
output = String.fromCharCode(this.currStack.pop());
} else if (instruction == "r") {
var input = this.program.io.getNumber();
this.currStack.push(input);
} else if (instruction == "i") {
var input = this.program.io.getChar();
this.currStack.push(input);
} else if (instruction == "(") {
this.length -= Math.floor(this.currStack.pop());
this.length = Math.max(this.length, 0);
} else if (instruction == ")") {
this.length += Math.floor(this.currStack.pop());
this.length = Math.min(this.length, this.code.length);
} else if (instruction == "w") {
this.wait = this.currStack.pop();
}
// Any unrecognized character is a no-op
if (this.ip >= this.length) {
// We've swallowed the IP, so this snake dies
this.alive = false;
this.program.snakesLiving--;
} else {
// Increment IP and loop if appropriate
this.ip = (this.ip + 1) % this.length;
}
return output;
}
Snake.prototype.getHighlightedCode = function() {
var result = "";
for (var i = 0; i < this.code.length; i++) {
if (i == this.length) {
result += '<span class="swallowedCode">';
}
if (i == this.ip) {
if (this.wait > 0) {
result += '<span class="nextActiveToken">';
} else {
result += '<span class="activeToken">';
}
result += escapeEntities(this.code.charAt(i)) + '</span>';
} else {
result += escapeEntities(this.code.charAt(i));
}
}
if (this.length < this.code.length) {
result += '</span>';
}
return result;
}
// Define Program class
function Program(source, speed, io) {
this.sharedStack = new Stack();
this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
var snake = new Snake(snakeCode);
snake.program = this;
snake.sharedStack = this.sharedStack;
return snake;
}.bind(this));
this.snakesLiving = this.snakes.length;
this.io = io;
this.speed = speed || 10;
this.halting = false;
}
Program.prototype.run = function() {
this.step();
if (this.snakesLiving) {
this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
}
}
Program.prototype.step = function() {
for (var s = 0; s < this.snakes.length; s++) {
var output = this.snakes[s].step();
if (output) {
this.io.print(output);
}
}
this.io.displaySource(this.snakes.map(function (snake) {
return snake.getHighlightedCode();
}).join("<br>"));
}
Program.prototype.halt = function() {
window.clearTimeout(this.timeout);
}
var ioFunctions = {
print: function (item) {
var stdout = document.getElementById('stdout');
stdout.value += "" + item;
},
getChar: function () {
if (inputData) {
var inputChar = inputData[0];
inputData = inputData.slice(1);
result = inputChar.charCodeAt(0);
} else {
result = -1;
}
var stdinDisplay = document.getElementById('stdin-display');
stdinDisplay.innerHTML = escapeEntities(inputData);
return result;
},
getNumber: function () {
while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
inputData = inputData.slice(1);
}
if (inputData) {
var inputNumber = inputData.match(/\d+/)[0];
inputData = inputData.slice(inputNumber.length);
result = +inputNumber;
} else {
result = -1;
}
var stdinDisplay = document.getElementById('stdin-display');
stdinDisplay.innerHTML = escapeEntities(inputData);
return result;
},
displaySource: function (formattedCode) {
var sourceDisplay = document.getElementById('source-display');
sourceDisplay.innerHTML = formattedCode;
}
};
var program = null;
var inputData = null;
function showEditor() {
var source = document.getElementById('source'),
sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
stdin = document.getElementById('stdin'),
stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');
source.style.display = "block";
stdin.style.display = "block";
sourceDisplayWrapper.style.display = "none";
stdinDisplayWrapper.style.display = "none";
source.focus();
}
function hideEditor() {
var source = document.getElementById('source'),
sourceDisplay = document.getElementById('source-display'),
sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
stdin = document.getElementById('stdin'),
stdinDisplay = document.getElementById('stdin-display'),
stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');
source.style.display = "none";
stdin.style.display = "none";
sourceDisplayWrapper.style.display = "block";
stdinDisplayWrapper.style.display = "block";
var sourceHeight = getComputedStyle(source).height,
stdinHeight = getComputedStyle(stdin).height;
sourceDisplayWrapper.style.minHeight = sourceHeight;
sourceDisplayWrapper.style.maxHeight = sourceHeight;
stdinDisplayWrapper.style.minHeight = stdinHeight;
stdinDisplayWrapper.style.maxHeight = stdinHeight;
sourceDisplay.textContent = source.value;
stdinDisplay.textContent = stdin.value;
}
function escapeEntities(input) {
return input.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
function resetProgram() {
var stdout = document.getElementById('stdout');
stdout.value = null;
if (program !== null) {
program.halt();
}
program = null;
inputData = null;
showEditor();
}
function initProgram() {
var source = document.getElementById('source'),
stepsPerSecond = document.getElementById('steps-per-second'),
stdin = document.getElementById('stdin');
program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
hideEditor();
inputData = stdin.value;
}
function runBtnClick() {
if (program === null || program.snakesLiving == 0) {
resetProgram();
initProgram();
} else {
program.halt();
var stepsPerSecond = document.getElementById('steps-per-second');
program.speed = +stepsPerSecond.innerHTML;
}
program.run();
}
function stepBtnClick() {
if (program === null) {
initProgram();
} else {
program.halt();
}
program.step();
}
function sourceDisplayClick() {
resetProgram();
}
.container {
width: 100%;
}
.so-box {
font-family:'Helvetica Neue', Arial, sans-serif;
font-weight: bold;
color: #fff;
text-align: center;
padding: .3em .7em;
font-size: 1em;
line-height: 1.1;
border: 1px solid #c47b07;
-webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
background: #f88912;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
display: inline-block;
border-radius: 6px;
float: left;
margin-right: 25px;
cursor: pointer;
}
.option {
padding: 10px 20px;
margin-right: 25px;
float: left;
}
h1 {
text-align: center;
font-family: Georgia, 'Times New Roman', serif;
}
a {
text-decoration: none;
}
input, textarea {
box-sizing: border-box;
}
textarea {
display: block;
white-space: pre;
overflow: auto;
height: 50px;
width: 100%;
max-width: 100%;
min-height: 25px;
}
span[contenteditable] {
padding: 2px 6px;
background: #cc7801;
color: #fff;
}
#stdout-container, #stdin-container {
height: auto;
padding: 6px 0;
}
#reset {
float: right;
}
#source-display-wrapper , #stdin-display-wrapper{
display: none;
width: 100%;
height: 100%;
overflow: auto;
border: 1px solid black;
box-sizing: border-box;
}
#source-display , #stdin-display{
font-family: monospace;
white-space: pre;
padding: 2px;
}
.activeToken {
background: #f93;
}
.nextActiveToken {
background: #bbb;
}
.swallowedCode{
color: #999;
}
.clearfix:after {
content:".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {
display: inline-block;
}
* html .clearfix {
height: 1%;
}
.clearfix {
display: block;
}
<!--
Designed and written 2015 by D. Loscutoff
Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: https://codegolf.stackexchange.com/a/40331/16766
-->
<div class="container">
<textarea id="source" placeholder="Enter your program here" wrap="off">r.*.n!(</textarea>
<div id="source-display-wrapper" onclick="sourceDisplayClick()"><div id="source-display"></div></div></div><div id="stdin-container" class="container">
<textarea id="stdin" placeholder="Input" wrap="off">1</textarea>
<div id="stdin-display-wrapper" onclick="stdinDisplayClick()"><div id="stdin-display"></div></div></div><div id="controls-container" class="container clearfix"><input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /><input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /><input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /><input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /></div><div id="stdout-container" class="container"><textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea></div><div id="options-container" class="container"><div class="option so-box">Steps per Second:
<span id="steps-per-second" contenteditable>20</span></div></div>
Previous two-snake solution:
rm1(
S.n.!(
Snake 1
r reads a number from input; m moves it to the shared stack. Then 1( causes the snake to eat its instruction pointer and die.
Snake 2
S switches to the shared stack. .n duplicates the value and outputs it as a number. .!( duplicates again, logically negates, and eats that many characters. If the number was 0, this eats one character, killing the second snake and ending the program. If the number was 1, this eats zero characters and execution loops back to the beginning of the snake, repeating indefinitely.
Java, 149 128 120 bytes
class A{public static void main(String[]a)throws Exception{int n=System.in.read()%2;do System.out.print(n);while(n>0);}}
Why 120 bytes? Because Java.
Edit: Saved 21 bytes thanks to Justin. Saved 8 bytes thanks to dohaqatar7.
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.
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
Bash + GNU utils, 13
grep 0||yes 1
Bash, 35
read n;for((;n;));{ echo 1;};echo 0
GNU sed, 10
:;/1/{p;b}
Explanation
:define an unnamed label/1/If input matches the regex1, thenpprint the pattern space (i.e. 1)band jump back to the unnamed label (forever)- If the input was not 1 (i.e. 0), then the pattern space is printed unmodified and the program ends.
3var, 6 bytes
">|[w]
Each 0 or 1 is followed by a newline. I've never actually used 3var's loop features before, so this is a first for me.
Explanation
" Read input into R
> Copy R into A
|[ ] Do while A > B...
w Output R
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.
Stack, 67 bytes
{ '1' print a call } `a set '' input num 1 = a { '0' print } ifelse
Run by placing the stack folder into your python lib folder, and running py -3 -m stack.cli truth.stack
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.
Brainbool, 5 bytes
,.[.]
Brainbool is Brainfuck, but it only operates on bits, and does I/O through 0 and 1 characters.
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.
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.
Arnold C, 296 Bytes
IT'S SHOWTIME
HEY CHRISTMAS TREE i
YOU SET US UP @NO PROBLEMO
BECAUSE I'M GOING TO SAY PLEASE i
STICK AROUND i
TALK TO THE HAND i
CHILL
BULLSHIT
TALK TO THE HAND i
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE BEEN TERMINATED
Not really competitive, but for the fun of it.
Does not support stdin, replace @NO PROBLEMO with @I LIED for a zero value. @No Problemo is 1.
Run with (assuming file is truthmachine.arnoldc):
wget http://lhartikk.github.io/ArnoldC.jar
java -jar ArnoldC.jar truthmachine.arnoldc
java truthmachine
QBasic, 23 bytes
INPUT x
1?x
IF x THEN 1
Gotos are the best way to loop. ;^) 1 is a label; ? is a shortcut for PRINT.
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.)
APL, 9 bytes
{⎕←⍵:∇⍵}⎕
Explanation:
⎕ ⍝ read a number from the keyboard
{⎕←⍵: } ⍝ output it, and if it is true:
∇⍵ ⍝ call the function again with that input
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.
Labyrinth, 7 bytes
?+
@!:
Labyrinth is a 2D stack-based language where control flow depends on the sign of the top element of the stack, checked after every instruction. Execution begins moving rightward from the first valid instruction on the top row, which here is the ?.
The relevant instructions are:
? Input integer
+ Add top two elements (Labyrinth's stack has infinite 0s on the bottom)
: Duplicate top element
! Output as number
@ Terminate program
If the input is 0, the IP reads input with ?, adds the top two of the stack (0 + 0 = 0), then duplicates : and outputs ! a 0. Here we encounter the sole junction in the program, and have to check the top of the stack to determine where to go. Since the top is 0, we move forward and terminate with @.
On the other hand, if the input is 1, we do the same instruction as before (but outputting a 1) before reaching the junction at the !. Now the top of the stack is positive, causing us to turn right into the ?. On EOF Labyrinth pushes 0, so we do 0 + 1 = 1 at the +, duplicate :, and output !. Once again we have a 1 at the top of the stack and the loop continues.
For a bonus, here's @MartinBüttner's 7 byte solution, which operates similarly:
?+!@
1!
Note that, unlike most languages, 1 actually pops n off the stack and pushes n*10 + 1, making the building up of large numbers easy. However, since the top of the stack is empty at that point, it's no different from merely pushing 1.
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.
C, 39
main(){for(;putchar(getchar()&49)&1;);}
STDIN must be a 1-byte file. It will not work if there is a trailing newline. This is because the program relies on all calls to getchar following a 1 to return EOF, which is represented as -1 (all ones in binary).
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
PowerShell, 24 Bytes
param($a)do{$a}while($a)
Gets variable $a, then uses the do-while loop functionality to output $a at least once, but continuing the loop if $a is truthy (i.e., 1).
Alternatively, using traditional while looping, also 24 bytes
param($a)while($a){$a}$a
In this instance, if $a is falsey, the while loop will never be executed and just the value of $a will be printed in the end statement. If $a is truthy, the program will enter the while loop and continuously print the value of $a.
Ruby, 32 30 bytes
p gets.to_i<1?0:loop{p 1};exit
Foo, 6 bytes
&1($i)
Input is hardcoded as the second character, since Foo doesn't have STDIN input. Don't we agree that Foo is awesome now? :)
Explanation
&1 Set current cell to 1
( ) Do-while loop (or, at least according to the interpreter)
$i Print current cell as int

























