# Internal Truth Machine

It's a normal truth machine but instead of taking input, it uses the first character of the program. Thus, internal.

The 0 and 1 are plain characters, i.e. ASCII code 0x30 and 0x31 respectively.

Example: 0abcd prints 0 and halts, and 1abcd prints 1 infinitely. Then your submission is abcd, whose score is 4 bytes. The 0 or 1 (the first character of the program) is not counted towards your score.

Of course, you're not allowed to look inside the file itself. Like a quine.

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 198288; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(a) {
});
comment_page = 1;
}
});
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
});
else process();
}
});
}

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

function getAuthorName(a) {
return a.owner.display_name;
}

function process() {
var valid = [];

var body = a.body;
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});

var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
});

});

valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});

var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;

.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)

var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();

languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});

var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);

langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});

for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
language = jQuery(language);
jQuery("#languages").append(language);
}

}
body { text-align: left !important}

width: 290px;
float: left;
}

#language-list {
width: 290px;
float: left;
}

font-weight: bold;
}

table td {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>

</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<tr><td>Language</td><td>User</td><td>Score</td></tr>
<tbody id="languages">

</tbody>
</table>
</div>
<table style="display: none">
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
</tbody>
</table>

• Wait, why did you post it so fast from the Sandbox? – user85052 Jan 21 at 14:01
• So, to make sure I understand, this requires two programs in the same language that differ only in the first character being either 0 or 1? – histocrat Jan 21 at 14:02
• Quasi-duplicate of Implement a Truth-Machine. The added restriction on input doesn't make it distinct in an interesting way. – Grimmy Jan 21 at 15:39
• @LuisMendo, But I think one major qualification for whether a question here is a duplicate is whether the answers here would answer the question for the proposed duplicate (even with trivial changes). But I don't think that is the case. Maybe for a couple of languages. But not for many of these. The Lua answer there would not work here, and in fact, it's impossible to answer this challenge here in Lua. That certainly has to be taken into consideration. – ouflak Jan 21 at 16:33
• Although I agree with Grimmy and something else could have been chosen as output for 1/0 respectively, I don't really see it as a dupe. Uninteresting since we already have the other challenge: definitely; but dupe: not really. This challenge isn't even possible in Java or Whitespace for example (a.f.a.i.k.), and although the core part is indeed the same, getting around that leading 0/1 will be tricky in some languages. EDIT: Ah, @ouflak already mentioned everything I said I now see.. – Kevin Cruijssen Jan 21 at 16:34

# Python 3, 29 bytes

 or~print(0)
while 1:print(1)


A full program, which if prefixed with 0 will print 0 then halt, exiting with an error, or if prefixed with 1 will print 1 forever.

The right of a logical or is only executed if the left is falsey (which 0 is, while 1 is not).

If the prefix is 0 the argument, print(0), of bitwise-not, ~, is evaluated - this has a side-effect of printing 0 and returns None which is an invalid argument for ~ causing an error which halts the program.

If the prefix is 1 the code ~print(0) is not evaluated and the infinite loop of while 1:print(1) is reached.

• That's really clever. Have an upvote. – AdmBorkBork Jan 21 at 19:12
• It's just as long, but exit('0') instead of ~print(0) would work without the error... – AVee Jan 23 at 14:07
• @AVee True, although exit prints to stderr which would mean different output streams for the two programs - I'd want to check that was acceptable. – Jonathan Allan Jan 23 at 18:50

## W, 2 bytes

You know, duplicate the first character and apply while. Simple enough.

:w


## Explanation, applied the bits

1:  % The condition and the body is both 1
w % While the condition 1 is true, output 1


## Explanation 2

0:  % The condition and the body is both 0
w % This while does not get executed
% The condition 0 gets returned & printed

• I really like this solution. Short and to the point. +1 – GipsyD Jan 22 at 13:26

# R, 20 bytes

->a
while(print(a))0


0Try it online!

1Try it online!

Uses rightwards assignment ->, which I now seem to use about once a month on this site (and never anywhere else).

• I knew this would be here. The only use I've ever thought of for -> outside of the site is at the end of a long pipe expression, but that's actually more confusing for future readers than it's worth. – Giuseppe Jan 21 at 20:15
• @Giuseppe maybe you paste some data into console, and then realized that you need assign it to some variable... – tsh Jan 22 at 3:50
• @tsh that's pretty much where I use it, when I'm skunkworksing some big pipe expression and need to use it as a vector mask or something – CriminallyVulgar Jan 23 at 8:39
• I use it in setClass statements (you certainly don't have to, it just looks nicer to me to do setClass("myClass",...) -> myClass though I can't put my finger on why) – JDL Jan 24 at 14:25

# x86-16 machine code, IBM PC DOS, 11 bytes

Binary:

(0 example)

00000000: 3002 ad8a d03c 30cd 2175 fcc3            0....<0.!u..


(1 example)

00000000: 3102 ad8a d03c 30cd 2175 fcc3            1....<0.!u..


Unassembled listing:

?? 02       DB  ?, 2        ; first byte is '1' or '0', second byte is DOS write char fnc
AD          LODSW           ; load input from [SI] into AL, INT 21H function 2 in AH
8A D0       MOV  DL, AL     ; output to DL
3C 30       CMP  AL, '0'    ; is input 0?
OUTPUT:
CD 21       INT  21H        ; write to console
75 FC       JNZ  OUTPUT     ; if not a '0', keep looping forever
C3          RET             ; return to DOS (only if it was a 0)


Explanation:

The first byte of the program is either a '0' or a '1', and combined with a second byte of 2 (more on that later) decodes to a benign instruction of either XOR [BP+SI], AL or XOR [BP+SI], AX. In PC DOS, many registers are initialized to known values, so we know that AX is 0, and SI is 100H which is the first byte of the program. Whatever memory address [BP+SI] translates to, it simply XOR's 0 to it, doing nothing.

The LODSW instruction puts the input byte into the AL register and a 2 into the AH register, which is the DOS INT 21H API function number to write an ASCII char in DL to the console.

The input is compared and ZF (zero flag) is set "true" if input is a 0. The char is written to the console and if ZF is not zero, it will loop indefinitely.

Output of both variants:

# 05AB1E, 3 bytes

µ=0


Try 0µ=0 online!

Try 1µ=0 online!

Also 3 bytes:

i[,


Try 0i[, online!

Try 1i[, online!

# Jelly, 3 bytes

Ṅḷ¿

 Ṅḷ¿ - Main Link: no arguments
.    - set Left to 0 or 1
¿ - while...
ḷ  - ...condition: Left
Ṅ   - ...do: print and yield (Left)
- implicit print (Left)


# Scratch 3.0, 10 blocks/80 bytes

As SB Syntax:

//1 or 0
repeat until<(n)=[0
say[1
end
say[0
define 0
set [n v]to[0
define 1
set[n v]to[1


It's more of a snippet than a program, but it works.

Try it online Scratch!

# ><>,  6  5 bytes

-1 thanks to Jo King!

:n?!;


### How?

Instruction pointer starts at the top left (i.e. 0 or 1) facing right. If the instruction pointer leaves the code it wraps around to the other side, continuing in the same direction.

X:n?!; -               X=0                X=1
X      - push X          {0}                {1}
:     - duplicate       {0,0}              {1,1}
n    - pop & print     {0,} "0"           {1} "1"
?   - pop & if...     {}                 {}
!  - ...truthy:      skip & wrap to X
; - ...falsey:                         exit


!f=f 0
_!f=f 1*>0!f
main=0!print


I think this is the only answer posted so far where the first character (the digit) isn't the entry point.

Anyway, explanation: I'm creating an operator function called !, and defining it by cases. We enter the top case if the left operand matches the program's first digit, and the bottom case otherwise. The right operand is bound to f in both cases (and it happens to always be print). In the top case, we just print a 0. In the bottom case, we print a 1, and then recursively call ourself with the same operands. (We know the left operand will always be 0.) Finally, main, the entry point, calls our operator with 0 and print.

# Labyrinth, 5 bytes

"
!"@


### How?

Instruction pointer starts at the top left (i.e. 0 or 1) facing right, the stack starts as infinite zeros.

0:

0"
!"@


  - stack = {0,0,0,...} (infinite supply of zeros)
0 - multiply top of stack by 10 and add 0 {0,0,0,...}
- 2 neighbours, 0 -> go forward
" - no-op {0,0,0,...}
- 2 neighbours -> go forward
" - no-op {0,0,0,...}
- 3 neighbours T-junction from stem, 0 -> turn around
" - no-op {0,0,0,...}
- 2 neighbours -> go forward
0 - multiply top of stack by 10 and add 0 {0,0,0,...}
- 2 neighbours -> go forward
! - pop top of stack, print as decimal "0" {0,0,0,...}
- 2 neighbours -> go forward
" - no-op {0,0,0,...}
- 3 neighbours T-junction from side, 0 -> go forward
@ - exit labyrinth


1:

1"
!"@


  - stack = {0,0,0,...} (infinite supply of zeros)
1 - multiply top of stack by 10 and add 1 {1,0,0,...}
- 2 neighbours -> go forward
" - no-op {1,0,0,...}
- 2 neighbours -> go forward
" - no-op {1,0,0,...}
- 3 neighbours T-junction from stem, 1 -> turn right
! - pop top of stack, print as decimal "1" {0,0,0,...}
- 2 neighbours -> go forward
1 - multiply top of stack by 10 and add 1 {1,0,0,...}
- ...etc.


# APL (Dyalog Unicode), 8 bytesSBCS

{⍞←⍺}⍣≠1


Prints to stderr.

### How they work

0{⍞←⍺}⍣≠1
{⍞←⍺}⍣≠   ⍝ Iterate {⍞←⍺} until (next value)≠(prev value) is true
{⍞←⍺}     ⍝ First iteration: print and return left arg (0)
≠   ⍝ (next value)=0, (prev value)=1, so 0≠1 is true
⍝ Function terminates

1{⍞←⍺}⍣≠1
{⍞←⍺}⍣≠   ⍝ Iterate {⍞←⍺} until (next value)≠(prev value) is true
{⍞←⍺}     ⍝ First iteration: print and return left arg (1)
≠   ⍝ (next value)=1, (prev value)=1, so 1≠1 is false
{⍞←⍺}     ⍝ Second and subsequent iterations: called with the same arg (1)
⍝ Never terminates; prints 1 infinitely

• I tried translating this into J to improve my current approach but wasn't able to. Is J's ^:v^:_ just fundamentally different from the APL iterate or am I missing something? – Jonah Jan 23 at 5:13
• @Jonah I guess it's because J's ^:_ is special-cased to find the fixed point. So it stops not only when v gives 0, but also when the right argument doesn't change. – Bubbler Jan 23 at 5:28
• Yeah that was the problem. – Jonah Jan 23 at 5:36

## Befunge-93, 5 bytes

:_.@#


Try 0 online

Try 1 online

First submission, and I only started learning Funge yesterday, so it's very likely there's a shorter solution.

I tried to find a way to remove the need for the ":" but I couldn't.

• Welcome to CGCC! This is a very nice solution – Jo King Jan 23 at 5:21

# Python 3, 37 bytes

and exec('while 1:print(1)');print(0)


# MathGolf, 3 bytes

Äo↑


Explanation:

1     # Push 1
↑  # While true without popping,
Ä    # by using a single builtin as inner block:
o   #  Print with trailing newline without popping

0     # Push 0
↑  # While true without popping
# (output the entire stack joined together implicitly as result)


# PowerShell, 21 bytes

0|?{$_}|%{for(){1}};0  Try it online! # Pyth, 6563 56 bytes Pyth's prefix operators don't really suit well to this challenge... Ws@$__import__("inspect").stack()[1][0].f_locals$_101 1  Edit 1: Saved 2 bytes by letting Pyth do the dictionary index, and using h instead of @<py_code>0 because I remembered it exists. Edit 2: Saved 7 bytes because @isaacg found an even sillier trick :) Try it online! • I really like this! I found a even sillier way to shorten it a bit more by removing the need for the "pyth_code" index. 56 bytes: Try it online! – isaacg Jan 21 at 19:08 • @issacg Clever! also thanks for making such a fun little language to play with, I've sunk more time into it than I'd like to admit >.< – famous1622 Jan 21 at 20:37 • I'm really glad you've enjoyed it! – isaacg Jan 21 at 20:43 # JavaScript, 34 bytes ?(_=>{for(;;)alert(1)})():alert(0)  Try it online! • Would a recursive function be legal, along the lines of (g=_=>g(alert(1)))()? – Neil Jan 21 at 22:43 • ?(a=1):(a=0);do alert(a);while(a) is 33 bytes long – tsh Jan 22 at 4:30 • ?eval('for(;;)alert(1)'):alert(0) is 33 bytes also. – tsh Jan 22 at 4:37 • ?a=1:a=2;for(;a;)alert(a&=1) funny version still based on @tsh suggestion – AZTECCO Jan 22 at 6:41 • @AZTECCO I'd post yours as it's own answer, I feel it's a little too novel for me to take... – famous1622 Jan 22 at 13:46 # Charcoal, 6 bytes 1ＷΣ⊟ＫＡＤ  Try it online! Link is to verbose version of code. 0ＷΣ⊟ＫＡＤ  Try it online! Link is to verbose version of code. Explanation: The leading 1 or 0 simply prints literally to the canvas. There then follows a while loop, the condition of which is the digital sum of the last character on the canvas. Thus if this is zero, the loop never gets off the ground, and the canvas gets implicitly output with the 0 still on it. However, if this is a non-zero digit, such as 1, then the loop will dump a copy of the canvas for ever. (Note that the dump command has a rate limit on it, so that TIO will time out before the output reaches the size limit.) There are a few variants with the same byte count, such as using Cast rather than Sum, or Maximum or Minimum rather than Pop, or even by using Count or Find instead. # ><>, 12 10 bytes :?vn; n:<  -2 bytes thanks to @JonathanAllan ## Answer History  :?vn; >:n:<  Try it online! or Try it with 1 Try it with 0 ## Explained Path visualiser is https://fishlanguage.com/ Gif converter is https://www.onlineconverter.com/video-to-gif • Save two using wrapping. – Jonathan Allan Jan 21 at 23:20 • 5 bytes by keeping it 1D. – Bubbler Jan 22 at 8:16 • But then that would be the same as the other 5 byte ><> answer – Lyxal Jan 22 at 8:20 • Oh, didn't notice that. – Bubbler Jan 22 at 8:26 # PHP, 24 bytes ?:die(0.);for(;;)echo 1;  Uses ternary condition knowing that in PHP one of the alternatives can be empty and i doesn't need to be assigned to a variable. Edit: had to add '0' to properly echo zero Edit2: Had forgotten that die was synonym of exit (thanks manual) Edit3: saved 1 byte with for(;;) instead of while(1) Edit4: saved 1 byte with die(0.) instead of die('0') thanks to @Christoph • You can use die(0.); to save a byte only integers get returned instead of printed. – Christoph Jan 22 at 11:58 # Cubix, 5 bytes ^O?@u  Maps onto the cube like  0 ^ O ? @ u  • ^ Redirect up onto the top face • 0 or 1 pushed to the stack • ? test • uO?@ if 0 then u-turn onto the integer output pass through the test again and halt • O^ if 1 output the integer and redirect up again # Turing Machine Code, 29 bytes or 28 bytes With the strange rule that the leading '0' or '1' doesn't count towards the byte count. 0 0 1 * 1 * _ 0 * 1 * 1 1 r 1  Try '0' online! 1 0 1 * 1 * _ 0 * 1 * 1 1 r 1  Try '1' online! # Perl 6, 16 15 bytes -1 byte thanks to Jo King &&1 xx*X[&put]$

• Using X with a custom operator is very clever. My thought was to use ..., but that only ties with your old solution. Try it online! – Jo King Jan 23 at 21:35
• @JoKing You can replace +* with 1 for -1 byte, so both approaches are tied again. – nwellnhof Jan 24 at 14:13

# ><>, 15 9 bytes

?\0n;
n1<


Try it online!

• -6 bytes thanks to JoKing

My first fish program, doesn't beat the other one but I wanted to post it anyway. Beats the other one now!

### Explanation:

For 0:
0? skip the next command
0 push 0 to the stack
n output the top of the stack
; terminate
For 1:
1? don't skip the next command (no-op)
\ mirror down
> switch direction to forward
1 push 1 to the stack
n output, then wrap round

• @JoKing "d"o can be replaced with dn I tried that but TIO outputs unrecognised characters... am I missing something? – Artemis still doesn't trust SE Jan 23 at 16:10
• Oh right I used o not n because apparently I can't read. Thanks! – Artemis still doesn't trust SE Jan 24 at 19:42

# Python 3, 38 bytes

0 or print(0)or exit()
while 1:print(1)


Try it online!

1 or print(0)or exit()
while 1:print(1)


Try it online!

If output to STDERR is allowed (30 bytes):

0 or exit('0')
while 1:print(1)


If output as exit code is allowed (28 bytes):

0 or exit(0)
while 1:print(1)


Try it online!

• I was not expecting that to be possible – PkmnQ Jan 21 at 14:22

# Ruby, 17 bytes

>0?loop{p 1}:p(0)


Try it online!

# TI-BASIC, 10 bytes

Repeat not(Ans:Disp Ans:End:"


Add either 0: or 1: to the beginning of the code to get the desired output.
Output is either just 0 or an infinite amount of 1s.

Repeat loops until its condition is true and ignores the condition for the first loop.
Thus, not(Ans will be 1 if 0: is added and 0 if 1: is added.

An empty string is added to the end of the program to prevent it from printing Done.

Examples:

prgmA: 0:Repeat not(Ans:Disp Ans:End:"

prgmB: 1:Repeat not(Ans:Disp Ans:End:"

prgmA
0

prgmB
1
1
1
1
1
1
1


Note: TI-BASIC is a tokenized language. Character count does not equal byte count.

# Keg, 4 bytes

{:|④


Try it online!

It seems I'm a bit late to the party! ¯\_(ツ)_/¯

Anyhow, this is simply a modification of the usual truth machine This is literally the same truth machine as it would be if we didn't have to place the digit at the start. Funny how implicit input works.

By this, I mean it doesn't matter if y'all place the digit at the start or you place it in input.

(⌐■◡■)

# Triangular, 9 bytes

.%).?/%(<


Try it online!

Formatted, it looks like this, with X being the number:

   X
. %
) . ?
/ % ( <


How it works:

• The instruction pointer begins at the top going southeast. It hits the first byte which is the number and pushes that to the stack.
• % prints the top of the stack as a number.
• ? skips the next instruction if the top of the stack is not positive. This effectively ends the program if the first byte was zero.
• < redirects the IP left.
• ( creates a jump point, % prints the top of the stack, ) unconditionally jumps to the most recent jump point.

# Alchemist, 27 bytes

a->a+Out_b
_+0a->a+b
a+b->_


Try it online with 0!

Try it online with 1!

This was a bit tricky. Every execution path up to the first application of the first line must be possible in both programs, and the two possible patterns in the first line are mutually exclusive. Hence, in order for the program to work, execution up to that point must be non-deterministic. This program swaps infinitely between two states until the first line is applied.

0a->a+Out_b    # the 0 version: from the initial state, add an a to halt and output 0
1a->a+Out_b    # the 1 version: from the a+b state, output 1 and leave the state unchanged
_+0a->a+b      # From the initial state, move to the a+b state
a+b->_         # From the a+b state, move to the initial state
`

A deterministic solution is possible by starting the first line with a two-digit number, but this is 14 bytes longer.

• The second program can be shortened to 36 bytes – Jo King Jan 22 at 4:19