# Question
Title: Write an interactive Deadfish interpreter
Deadfish is a joke "programming language" with four commands. Because the Esolang page is a bit contradictory and the interpreters on that page don't all work exactly the same, you should implement the following variation:

---

## Specification

1. There is an accumulator which is *at least* 16 bits in size, more is allowed but less is not. Negative numbers do not need to be supported. The accumulator is `0` when the program starts.
2. There are the following two sets of four commands, and your program must support both at the same time.
```
  Standard Deadfish    │   XKCD Variant   │    Meaning
  ─────────────────────┼──────────────────┼────────────────────────────────────
        i              │        x         │    Increment accumulator
        d              │        d         │    Decrement accumulator
        s              │        k         │    Square ( acc = acc * acc )
        o              │        c         │    Output accumulator, as a number

```
3. If, after executing a command, the accumulator is either `-1` or `256`, the accumulator must be reset to zero. **Note that this is not normal wrap-around.** If, say, the accumulator is `20`, and the `s` command is run, the accumulator should be `400` afterward. Similarly, if the accumulator is `257` and the `d` command is run, the accumulator should become `0`.
4. Any input that isn't one of these commands should be ignored.

---

## Test programs

* `xiskso` should output `0`
* `xiskisc` should output `289`

---

## I/O

Your program should display a prompt: `>>`. The prompt must be at the beginning of a new line. It should then read a line of user input, and run the given commands left-to-right. When outputing numbers, the numbers must be separated. I.e., `12 34` is OK, `12,34` is OK,

```
12
34

```

is OK, but `1234` is not.

Your program should keep doing this in a loop, at least until `EOF` is reached.

Example session:

```
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

```

# Answer
# K, 77 bytes

```
  {1">>";0{x*2=-1 256?x:y@x}/("xkcdiso"!7#(1+;{x*x};{-1@$x;x};-1+))@0:0;.z.s`}`
>>xiskso
0
>>xiskisc
289

```

Note this is K4. A K6 solution is slightly longer because the IO verbs are longer, even if everything else is better:

```
{""0:">>";0{x*^-1 256?x:y@x}/("xkcdiso"!7#(1+;{x*x};{""0:,$x;x};-1+))@0:"";o`}`

```
* `""0:` prints and returns its argument. Note in K4 we simply apply to .
* `0 f/ args` demonstrates reduce with an initial value, i.e. `f[f[0;first arg];second arg]…`
* `{x*2=-1 256?x…` classifies x into the 0 (for -1), 1 (for 256) and 2 for all other values. `2=` means we get `1` for unclassified values and `0` otherwise, multiplying by `x` is shorter than a conditional. In K6 we can do a little better because `{x*^-1 256?x:y@x}` relies on the fact that `-1 256?x` returns `0N` (null) and `^` detects nulls.
* The "parser" is the map `"xkcdiso"` instead of the suggested order because `7#` will wrap around the four arguments i.e. `7#"abcd"` returns `"abcdabc"` which keeps our table smaller
* The map translates `"x"` and `"i"` to the projection `1+` which is equivalent to the function `{1+x}` but shorter.
* The map translates `"d"` to the projection `-1+` which is equivalent to the function `{-1+x}` but shorter.
* The map translates `"k"` and `"s"` to the function `{x*x}`
* The map translates `"c"` and `"o"` to the output function `{-1@$x;x}` which again in K6 is slightly longer: `{""0:,$x;x}` but both print its output followed by a newline, and then returns the argument.
* .z.s is self-recursion. In K6 we can simply say `o`` which is shorter.
> 7 votes

# Answer
## Perl 5, 90 bytes

```
do{print+(map{$?+=/i|x/-/d/;$?**=1+/s|k/;$?=~s/-1|^256$/0/;"$?
"x/o|c/}/./g),'>> '}while<>

```

Try it online!

Thanks to @xfix for his help on this previously! Saved 4 bytes thanks to @Xcali!
> 9 votes

# Answer
## Powershell, ~~131~~ ~~126~~ ~~121~~ ~~114~~ 113

```
for($x=0){[char[]](read-host ">>")|%{switch -r($_){"i|x"{$x++}"d"{$x-=!!$x}"s|k"{$x*=$x}"o|c"{$x}}
$x*=$x-ne256}}

```
* `for($x=0){...}` \- set the accumulator to 0 and loop forever
* `read-host '>>'` \- get the user input with prompt `>>`
* `[char[]](...)` \- convert the user input to an array of characters
* `|%{...}` \- perform what's inside `{}` for each character
* `switch -r($_)` \- regex switch for each character
* `"i|x"{$x++}` \- match `i` or `x` \- increase the accumulator
* `"d"{$x-=!!$x}` \- match `d` \- decrease `$x` by `!!$x`, which will be `0` if `$x` is `0`, and `1` otherwise. This makes sure the accumulator never reaches `-1`.
* `"s|k"{$x*=$x}` \- match `s` or `k` \- square
* `"o|c"{$x}` \- match `o` or `c` \- output the accumulator
* `$x*=$x-ne256` \- multiply the accumulator by `0` if it is `256` or by `1` otherwise

**Example output**

```
>>: xiskso
0
>>: xiskisc
289
>>: ddddo ddddo
285
281
>>: ddddo ddddo
277
273
>>: dddddddo
266
>>: dddddddddo
257
>>: do
0
>>: do
0
>>: io
1
>>:

```

I guess the implementation of `read-host` is host specific, so this Powershell host (ConsoleHost) appends `:` to the specified prompt.
> 7 votes

# Answer
## Rebol 3, ~~178~~ ~~169~~ ~~161~~ 159

```
f: does [if a = -1 or (a = 256)[a: 0]]d: [any[["i"|"x"](++ a f)|["d"](-- a f)|["s"|"k"](a: a * a f)|["o"|"c"](print a)| skip]]a: 0 forever [parse (ask ">>") d]

```

Prettier version:

```
f: does [if a = -1 or (a = 256) [a: 0]]
d: [
    any [
        ["i"|"x"] (++ a f) |
        ["d"] (-- a f) |
        ["s"|"k"] (a: a * a f) |
        ["o"|"c"] (print a) |
        skip
    ]
]
a: 0
forever [parse (ask ">>") d]

```
> 7 votes

# Answer
## Haskell, 202

```
r=pure;-1%c=0%c;256%c=0%c;s%'o'=s<$print s;s%'c'=s%'o';s%'i'=r$s+1;s%'x'=s%'i'
s%'d'=r$s-1;s%'s'=r$s^2;s%'k'=s%'s';s%_=r s;n s(c:[])=s%c;n s(c:f)=s%c>>=(`n`f)
main=p 0;p s=putStr">> ">>getLine>>=n s>>=p

```
> 6 votes

# Answer
# Python 3, 141

I know I am to late, but I wanted to take the opportunity to post a shorter Python-version (and my first CodeGolf-attempt). :)

```
v=0
m=lambda y:(0,y)[-1!=y!=256]
i=x='+1'
d='-1'
s=k='*v'
c=o=');print(v'
while 1:
 for n in input('>>'):exec('v=m(v'+locals().get(n,'')+')')

```

The print-statement was kinda tricky for this. If the prompt has to end with a whitespace, add one char to the count. :)

## Explanation

`v` is the accumulator.

`m` checks whether the given value is `-1` or `256`. If so, `0` will be returned, the value otherwise.

In the following lines the operations are assigned to the corresponding variables (as some have the same meaning (like `i` and `x`) this is shorter than instantiating a new dictionary). Those are then used in the `exec` below.

`while 1:` is the main-loop

Now the fun begins. Like @jazzpi's solution, it iterates over each char of the input. `locals()` is the dictionary of all current (visible) variables. With `.get(n,'')` the corresponding key will be put into the exec-string (an empty string, if the key (= other input) was not found). This then will be, when executed, concatenated with `v` and passed towards `m`. The return value will be stored in `v` again.

> ### Short example:
>
> Be `n = 'i'` (`n` = input-char), we get `'+1'` out of the `locals`-block as `i` is the variable with value `'+1'`.
> The string for the `exec` than looks like this: `'v=m(v+1)'`.
> Maybe now it is easier to see, that, when executing, it will call `m` with the value of `v+1` and store it's output in `v` again.

Repeat this until you are bored. :)
> 5 votes

# Answer
# Ruby, ~~140~~ 138

```
a=0
loop{$><<'>> '
eval gets.gsub(/./){|c|({i:i='a+=1',x:i,d:'a-=1',s:s='a**=2',k:s,o:o='p a',c:o}[:"#{c}"]||'')+';a=a==-1||a==256?0:a;'}}

```

Sample session (same as yours):

```
c:\a\ruby>deadfish
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

```
> 4 votes

# Answer
# K, 121

```
i:0;while[1;1">> ";{i{(r;0)(-1~r)|256~r:y x}/d{x@&x in y}[x;!d:"ixdskoc"!,/(2#(1+);-1+;2#{x*x};2#{-1@$i::x;})]}'" "\:0:0]

```

.

```
C:\q>q deadfish.k -q
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

```
> 4 votes

# Answer
## Ada

Here's an Ada implementation for the few who're interested by this language. It took me quite some time in order to use some of Ada's best practices (like the use of Indefinite\_Holders instead of access) and also to fully comprehend how's Deadfish must work.

```
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Indefinite_Holders;
with Ada.Integer_Text_IO;

procedure Deadfish is
   package String_Holder is new Ada.Containers.Indefinite_Holders(String);
   use String_Holder;

   value_output : Natural := 0;
   str_input : String_Holder.Holder := To_Holder("");
begin
   Prompt :
   loop
      Put(">> ");
      String_Holder.Replace_Element(str_input, Get_Line);
      for rg in str_input.Element'Range loop
         case str_input.Element(rg) is
            when 'i' | 'x' =>
               case value_output is
                  when 255 => value_output := 0;
                  when others => value_output := Natural'Succ(value_output);
               end case;

            when 'd'       =>
               case value_output is
                  when 257 => value_output := 0;
                  when 0 => null;
                  when others => value_output := Natural'Pred(value_output);
               end case;
            when 's' | 'k' =>
               case value_output is
                  when 16 => value_output := 0;
                  when others =>value_output := value_output * value_output;
               end case;
            when 'o' | 'c' => Ada.Integer_Text_IO.Put(value_output, Width => 0); Put_Line("");
            when others => null;
         end case;
      end loop;
   end loop Prompt;
end Deadfish;

```

And the output :

```
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

```

If some people experimented in Ada could give me some optimisation hints, I would be thankful.
> 4 votes

# Answer
## C, 159 chars

```
A; main(c) {
  printf(">> ");
  while (c = getchar(), ~c)
    A = c - 'i' & c - 'x'?
        c - 'd'?
        c - 's' & c - 'k'?
        c - 'o' & c - 'c'?
        c - '\n'?
        A :
        printf(">> "), A :
        printf("%d\n", A), A :
        A * A :
        A - 1 :
        A + 1,
    A *= ~A && A - 256;
}

```

I tried another approach based on setting up a look-up table for instruction decoding, but unfortunately that ended up longer (**169**). I included it since someone might come up with a clever tweak to cut down the size. (Must be run without any arguments)

```
#define X !--c?A

A,M[256];
main(c) {
  for(; !M['x']; c++) M["@osid\nckx"[c]]-=c%5+1;
  for (printf(">> "); c = ~M[getchar()]; A *= ~A && A - 256)
  A= X,printf("%d\n", A),A:X*A:X+1:X-1:A;
  main();
}

```
> 4 votes

# Answer
# Python 3, 181 175 171 162

```
a=0
s=lambda x:"a=%d"%(x!=-1and x!=256and x)
while 1:
 for i in input(">>"):u,b,o=s(a+1),s(a*a),"print(a)";exec(dict(i=u,x=u,d=s(a-1),s=b,k=b,o=o,c=o).get(i,""))

```

This outputs a newline after the `>>`, but the OP didn't say that wasn't allowed. *Not anymore!*

Thanks to `GlitchMr`, `minitech` and `golfer9338`!
> 3 votes

# Answer
## C, 163

```
#define i(u,v);if(c==u+89|c==v+89)
a;main(c){printf(">>");while(c=getchar()-10){i(6,21)a++i(1,1)a--i(8,16)a*=a;i(0,12)printf("%d\n",a);a=a==-1|a==256?0:a;}main();}

```
> 3 votes

# Answer
# R, 161, 148, 138

```
a=0;repeat{x=readline(">> ");for(i in utf8ToInt(x)-99){a=a^((i==8|i==16)+1)+(i==6|i==21)-(i==1&a);a=a*(a!=256);if(i==0|i==12)cat(a,"\n")}}

```

Ungolfed version:

```
a = 0
repeat{
  x = readline(">> ")
  for(i in utf8ToInt(x) - 99) {
    a = a ^ ((i == 8 | i == 16) + 1) + (i == 6 | i == 21) - (i == 1 & a)
    a = a * (a != 256)
    if(i == 0 | i == 12) cat (a, "\n")
  }
}

```

Example session (in interactive mode):

```
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

```
> 3 votes

# Answer
# **Python 2, 139**

```
a=0
while 1:
 for c in raw_input(">> "):
  if c in'ix':a+=1
  if c=='d':a-=1
  if c in'sk':a*=a
  if c in'oc':print a
  if a in(-1,256):a=0

```

This is neat, but also pretty straightforward. Here's a longer, cooler version:

```
def i(a):
 while 1:
  c=yield
  if c in'ix':a+=1
  if c=='d':a-=1
  if c in'sk':a*=a
  if c in'oc':print a
  if a in(-1,256):a=0
 j=i(0);next(j)
while 1:
 for c in raw_input(">> "):j.send(c)

```

Weighing in at 190 characters, it's perhaps not the most competitively-lengthed answer here. On the other hand, coroutines are pretty rad and I'm always looking for an excuse to use (and share) them
> 3 votes

# Answer
# TI-BASIC, ~~104 107~~ ~~102~~ ~~100~~ 98

For TI-83+/84+ series calculators.

Name this `prgmD`; it eventually overflows the stack by calling itself. Replace the recursion with a `While 1`, at the cost of two bytes, to fix this.

```
Input ">>",Str1
For(I,1,length(Str1
int(.5inString("?ixskd?oc",sub(Str1,I,1
If Ans=4
Disp Y
imag(i^Ans)+Y^int(e^(Ans=2     //decrements when Ans=3; increments when Ans=1
min(0,Ans(Ans≠256→Y
End
prgmD

```

Y is 0 by default, so either run this with a freshly memory-cleared calculator or store 0 to Y manually before running this.

Too bad that the lowercase letters (in the string literals) are two bytes each; otherwise this would be shorter than Dom Hastings' answer.

EDIT: Fixed a divide-by-zero (0^0) error at the cost of three bytes.

107 -\> 102: Used imaginary exponentiation trick to save four bytes (including 1 from parentheses and -1 from lengthening the lookup string) and used Y instead of X, which takes one less byte to initialize.
> 3 votes

# Answer
# C (~~224~~ 212 characters)

This is probably a bad language choice, but oh well. It's not that language like C can do better than some dynamic programming language. On Clang, you will need to specify a value for `return` (this is not necessary for gcc).

```
#define s(x,y)case x:y;break;
main(){int c=10,a=0;for(;;){switch(c){s(-1,return)s('i':case'x',++a)s('d',--a)s('s':case'k',a*=a)s('c':case'o',printf("%d\n",a))s(10,printf(">> "))}a!=-1&a!=256||(a=0);c=getchar();}}

```
> 2 votes

# Answer
# Postscript 272

```
/cmd<</i{1 add}/x 1 index/d{1 sub}/s{dup mul}/k 1 index/o{dup =}/c 1 index>>def
0{(>> )print flush{/f(%lineedit)(r)file def}stopped{exit}if{f
1 string readstring not{exit}if cmd exch 2 copy known{get exec}{pop pop}ifelse
dup -1 eq 1 index 256 eq or{pop 0}if}loop pop}loop

```

Ungolfed:

```
/cmd <<  % define commands
/i { 1 add }
/x 1 index
/d { 1 sub }
/s { dup mul }
/k 1 index
/o { dup = }
/c 1 index
>> def
0        % accumulator on stack
{
    (>> )print flush   % print prompt
    { /f (%lineedit) (r) file def } stopped {exit} if  % read input line or quit
    {
        f 1 string readstring not {exit} if   % read 1-char string from line
        cmd exch 2 copy known { get exec }{ pop pop } ifelse   % execute command or don't
        dup -1 eq 1 index 256 eq or { pop 0 } if   % adjust accumulator if needed
    } loop
    pop
}loop

```
> 2 votes

# Answer
# Haskell, ~~186~~ 178 bytes

This needs to be run with `runhaskell` (or inside `ghci`) since they both set the `BufferMode` to `NoBuffering` by default which safes quite a lot of bytes:

```
infix 4#
-1#x=0#x
256#x=0#x
r#x:y=case x of 'i'->r+1#y;'x'->r+1#y;'d'->r-1#y;'s'->r^2#y;'k'->r^2#y;'o'->print r>>r#y;'c'->r#'o':y;_->r#y
r#_=putStr">> ">>getLine>>=(r#)
main=0#""

```

Try it online!

### Explanation

This defines a new operator `state # source` (the fixity declaration allows us to drop parentheses when using it in conjunction with other operators `(+)`,`(-)`,`(^)`,`(:)` and `(>>)`):

* the first two lines "fix" the states `-1` and `256`
* it then matches the first character and acts upon it
* once it runs out of characters (`r#_`), it reads new ones and starts over again keeping the old state

To start the process we initialize the state with `0` and read a new source line, ie. begin with an empty source:

```
main=0#""

```
> 2 votes

# Answer
# Python 3, 130 119 bytes

```
a=0
while 1:
 for c in input(">> "):
  a+=(c in'ix')-(c=='d')+(a*a-a)*(c in'sk')
  if c in'oc':print(a)
  a*=-1!=a!=256

```

Try it online!

This is just a conversion of stackspace's response to Python 3, with an improvement to the wrap-around code. We gain 1 byte from losing the print statement, but save 4 bytes from switching to `input()`, and remove another 6 from the new wrap-around code.

Edit: Saved another 11 bytes by moving all the math operations onto one line. Moving the square operation doesn't actually save any bytes, but it does look cooler.
> 2 votes

# Answer
## Windows Batch, 204 256

```
@echo off
set a=0
:a
set /p i=^>^>
if %i%==i set /a a=%a%+1
if %i%==x set /a a=%a%+1
if %i%==d set /a a=%a%-1
if %i%==s set /a a=%a%*%a%
if %i%==k set /a a=%a%*%a%
if %i%==o echo %a%
if %i%==c echo %a%
if %a%==256 set a=0
if %a%==-1 set a=0
set i=n
goto a

```

Successfully ignores other commands. Really got bloated without having `or` to work with...

Edit:

> Fixed:
>
> * No more Echoing all commands
> * Made it actually DO math with /a
> * Reset on -1
> * Reset input after every cycle
>
> This cost 52 characters.
>
> Didn't fixed:
>
> * Squaring 0 writes "0\*0" in a.
> * Inputting space (or inputing nothing, when you just opened it) crashes script.
> * You NEED to input one char at a time.
> 1 votes

# Answer
# Lua, 230 228

```
a=0repeat io.write(">> ")x=io.read()for i=1,#x do c=x:sub(i,i)if c=="i"or c=="x"then a=a+1 elseif c=="d"then a=a-1 elseif c=="s"or c=="k"then a=a*a elseif c=="o"or c=="c"then print(a)end if a==256or a==-1then a=0 end end until _

```

Not the worst, not the best.

NOTE: as reported by @mniip `256or` may not work in your interpreter. More info in comments.

(more or less) Readable version:

```
a=0
repeat
  io.write(">> ")
  x=io.read()
  for i=1,#x do
    c=x:sub(i,i)
    if c=="i"or c=="x"then
      a=a+1
    elseif c=="d"then
      a=a-1
    elseif c=="s"or c=="k"then
      a=a*a
    elseif c=="o"or c=="c"then
      print(a)
    end
    if a==256or a==-1then
      a=0
    end
  end
until _

```

Output:

```
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

```

Edit: thanks to @mniip for 2 char optimization: `until nil` -\> `until _`
> 1 votes

# Answer
## Windows Command Script - 154

Abusin unknown features to the max.

```
@echo off
set i=1
set x=1
set d=-1
set/as=[*[-[
set/ak=[*[-[
set.=0
set/p.=^>^>
set/a[=[+%.%
e%.:o=c%h%.:c=o% %[% 2>nul
set[=%[:-1=%
if;%[%==256 set[=
%0

```
> 1 votes

# Answer
# \>\<\>, 258 bytes

I've done another \>\<\> answer since I couldn't test phase's and it used pre-stacked commands rather than emulating a shell anyway.

```
0v
"<vooo">>
!~>i:0)?v~ >
 ^?=a:  /  ^!?="c"v?="o":v?="s":v?="k":v?="d":v?="x":v?="i":
   voan:<        ~<  v*:~<      <  v-1~<  v+1~<      <
   <                 <             <      <vv?=-10:v?=*:+1f:
  v                                        <>      >~0

```

It can certainly be golfed down, but I'm not sure I'll have the needed ~~insanity~~bravery !

I tested it with the official interpreter running under python 3.5 under cygwin under windows 7 and could reproduce the test run :

```
$ python fish.py deadfish.fish
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>> (pressed ctrl-Z)Stopped

```

In case you can't run it on your machine (input seems to be tricky) or you just want to try it without any other software, you can use the following version on the online interpreter.

```
0v
 <vooo">> "<
  >i:0)?v~
      o:/  ^!?="c"v?="o":v?="s":v?="k":v?="d":v?="x":v?="i":
 ^oanoa:<        ~<  v*:~<      <  v-1~<  v+1~<      <
   <                 <             <      <vv?=-10:v?=*:+1f:
  v                                        <>      >~0

```

It obviously disregards \n and EOF since you can't input them in the online interpreter, but will behave as if enter had been pressed after each output command.
> 1 votes

# Answer
# C (gcc), 139 bytes

Compile with `-Dk="_nZZiaeY"` (included in byte count). -2 bytes if prompt `>>\n` is allowed.

```
x;f(c){for(printf(">>");c=getchar()-10;x+=c--?c--?c--?c||printf("%i\n",x),0:x*x-x:-1:1,x*=~x&&x^256)c=strchr(k,c)-k>>1;f();}

```

Try it online!

## Degolf

```
/** Preprocessor **/
-Dk="_nZZiaeY" // This is a lookup string; it corresponds to "ixddskoc",
               // with 10 deducted from each character. Upon compilation,
               // all occurences of the string literal are replaced with a
               // pointer to its location in memory.

/** Source **/
x;f(c){ // x: 32-bit accumulator, c: local variable for read character
    for(printf(">>"); // Start for-loop and print prompt.
            c=getchar()-10; // Read a character from STDIN.
                            // Loop breaks if it is '\n'.

            // The below happens at the end of each iteration.
            x+=c--?c--?c--?
               // Find the correct operation by testing c and post-
               // decrementing with multiple ternary-ifs. If c is 0,
               // operation was found, add the else-value to the
               // accumulator x.
               //     If the character is invalid, the value of c is
               // very large, and will not reach 0 with 3 decrements.

               c||printf("%i\n",x),0
               // If c-3 is 0, print accumulator, else do nothing.
               // Returns 0 regardless of what happens. (No change to x)
               :x*x-x
               // Square. Results in x=x+x*x-x, and is shorter than (x*=x)
               :-1:1,
               // Decrement, Increment.
               x*=~x&&x^256
               // Because -1==0xffffffff, ~x==0 when x==-1. Likewise,
               // x^256==0 only when x==256. The logical-AND coerces the result
               // to boolean 1 (no match) or 0 (match). Multiplication resets
               // the accumulator as appropriate.
           )
        // This is the actual body of the for-loop
        c=strchr(k,c)-k>>1;
           // Finds the index of the read character in the lookup string,
           // then "divides" it by two.
           // Because strchr() returns NULL (0) when character is not found,
           // deducting k from it results in a very negative number.
           // The right-shift results in division by 2 for positive numbers,
           // while the negative numbers become very large positive numbers
           // (c >= 0x70000000) because of the 2's complement representation.
    // Finally, recurse until forceful termination.
    f();
}

```
> 1 votes

# Answer
## Keg, 68B

```
0{'::"ÿ1+=$0<+['_0"] \>\>\
,,,,?:o=[':."]:i=['1+"]:d=['1-"]:s=[':*"

```
> 1 votes

# Answer
## Golf-Basic 84, 88 characters

```
:0_A:0_O:1_I:2_D:3_S:O_C:I_X:S_Kl`1i`N@A=256:0_A@N=0d`A@N=1:A+1_A@N=2:A-1_A@N=3:A^2_Ag`1

```

Prompts one command at a time, as in at least 3 other solutions. Here is a test run for `xiskisc`:

```
?X
?I
?S
?K
?I
?S
?C
             289

```

Also, `xiskso` outputs 0, as it should.
> 0 votes

# Answer
## Haskell, 230

```
import System.IO
i""n=[]
i(a:b)n
 |a=='o'||a=='c'=[n]++i b n
 |True=i b$v a n
v a n=w(case a of 'i'->n+1;'x'->n+1;'d'->n-1;'s'->n^2;'k'->n^2)
w(-1)=0
w 256=0
w n=n
main=do;putStr ">> ";hFlush stdout;s <- getLine;print$i s 0;main

```

If only I could get rid of that pesky `hFlush stdout` call! Without it, the prompt is not displayed until an `o` operation is performed. Any advice?
> 0 votes

# Answer
## PHP+HTML 345

```
<form><?php $i=0;$o='';if(isset($_GET[i])){$i=$_GET[a];foreach(@str_split($_GET[i]) as $j=>$v){$v==i||$v==x?$i++:($v==d?$i--:($v==k||$v==s?$i*=$i:($v==o||$v==c?$o.=$i."\n":'')));($i==256||$i==-1)&&$i=0;}$_GET[p].='>> '.$_GET[i]."\n".$o;echo"<textarea locked name=p>$_GET[p]</textarea><input type=hidden name=a value=$i><br>";}?>>> <input name=i>

```

output is a little sketchy (history/session is shown on a textarea, and with error reporting enabled a lot warnings are printed) but everything works
> 0 votes

# Answer
# \>\<\>, 239

```
v
\r0&
v                  <
\&::&01-=$f1+:*=+?v
v             &0~&<
\:"i"=?v
       >~&1+&      ^
\:"d"=?v
       >~&1-&      ^
\:"s"=?v
       >~&:*&      ^
\:"o"=?v
       >~&:o&      ^
\:"h"=?v
       >~;        (^)
>~                 ^

```

The initial stack is the input. You can try it online here.
> 0 votes

# Answer
# JavaScript (Node.js), 204 Bytes

```
process.openStdin(f=a=>process.stdout.write((i=0,""+a).split` `.map(x=>([...x.slice(0,-1)].map(d=>({i:x=e=>i++,d:e=>i--,s:k=e=>i*=i,o:c=e=>e,x,k,c})[d](i=-1||i==256?i=0:0)),i))+"\n>> "),f``).on("data",f)

```

This can probably be golfed. Node.js again proves it's strange disguised verbosity once again. Code explained:

```
process.openStdin( // This function has to be called to take input, but doesn't have arguments
  f=a=> // Define a function f. This is the deadfish interpreter. It takes an argument `a` which is a Buffer
  process.stdout.write( // Same as console.log, but doesn't output trailing newline
    (i = 0, "" + a) // Take advantage of comma operator to (A) define the accumulator i, and casts a (which is a Buffer) to a String
      .split` ` // Split the string a at spaces, making it an array
      .map(     // Map through each element of the array
        x=>     // Map function, takes argument x, the value in the array (string)
          ([...x.slice(0,-1)] // Remove the last character (newline) and than use the spread operator to divide the string into an array of it's chars
            .map(d=> // Map function, you know how this works
              ({ // Here I define the various deadfish commands
                i: x = e => i++,
                d: e => i--,
                s: k = e => i*=i,
                o: c = e => e,
                // Take advantage of ES6 object notation. Equivilent to {"x": x, "k": k, "c", c}
                x,
                k,
                c
              })
              [d] // Get the command to execute. If this is passed something which isn't valid, a giant error will appear
              (
                i==-1 || i==256 ? i = 0 : 0 // Take advantage of the fact that none of the command functions take arguments to handle the strange "overflow"
              )
            ),
          i)
      ) +
  "\n>> "), // Display the prompt again, as well as a newline
  f`` // Initalize the prompt by passing an empty script
)
.on("data",f) // Bind the f function to newline on STDIN

```
> 0 votes

# Answer
# C#, 311 bytes

```
using System;class p{static void Main(){int a=0;int s(int b)=>b==-1||b==256?0:b;while(true){Console.Write(">>");var c=Console.ReadLine();for(int i=0;i<c.Length;i++){switch(c[i]){case'i':case'x':a=s(a+1);break;case'd':a=s(a-1);break;case's':case'k':a=s(a*a);break;case'o':case'c':Console.WriteLine(a);break;}}}}}

```

would be 283 byte if usings and class declaration etc could be ommitted by just providing a function definition
> 0 votes

# Answer
# 05AB1E, 50 bytes

```
0[„>>,I"idsoxdkc"©Ãε®skн}"><n="sè"Džz1(‚såi0}"ý.V

```

Try it online!

**Explanation:**

The basic idea is to translate it into 05AB1E code and eval it.

```
0[„>>,I"idsoxdkc"©Ãε®skн}"><n="sè"Džz1(‚såi0}"ý.V
0                                                    Set the accumulator to 0.
 [                                                   Do this forever.
  „>>,                                               Print ">>"
      I                                              Read input
       "idsoxdkc" Ã                                  Keep only "idsoxdkc" characters.
                 ©                                   Also put "idsoxdkc" in the register.
                   ε    }                            For each character in the filtered input:
                    ®skн                             Find it's index in "idsoxdkc"
                         "><n="sè                    Index into "><n="
                                 "Džz1(‚såi }"ý      After each command, check if accumulator = -1 or 256
                                           0         If it does, change it to 0
                                               .V    Evaluate as 05AB1E code.

```
> 0 votes

# Answer
# Tidy, 136 bytes

```
a:=0{h:a:=a+1 if h='i∨h='xa:=a-1 if h='da:=a*a if h='s∨h='kout(a)if h='o∨h='ca:=0 if a=-1∨a=256}→stoa(h)while h:=prompt(">> ")

```

Try it online! `prompt` is interactive, so it looks a bit weird online. See the "Example run" section below.

## Ungolfed and commented

```
? initialize the accumulator
acc := 0

map(

    ? map this function...
    { char :
        acc := acc + 1      if char = 'i  or  char = 'x
        acc := acc - 1      if char = 'd
        acc := acc * acc    if char = 's  or  char = 'k
        out(acc)            if char = 'o  or  char = 'c
        acc := 0            if acc  = -1  or  acc  = 256
    },

    ? over each character...
    stoa(line)

? over each line
) while line := prompt(">> ")

```

## Example run

```
C:\Users\conorpc\Programming\Tidy (master -> origin)
λ tidy test.tidy
>> xiskso
0
>> xiskisc
289
>> ddddo ddddo
285
281
>> ddddo ddddo
277
273
>> dddddddo
266
>> dddddddddo
257
>> do
0
>> do
0
>> io
1
>>

```
> 0 votes

# Answer
# Emojicode, 308 bytes

```
0➡a>>❗c❗↪dxdikscoc❗➡i↪i◀4a⬅➕i2✖2➖1↪i◀6a⬅✖aa 10❗❗↪a-1a2560➡a

```

Try it online here.

Ungolfed:

```
    Main code block
    0 ➡   a   Accumulator, initialised to 0
         Repeat forever:
         >> ❗   Output prompt
         c    ❗    For each character c in the next line of input:
            ↪  dxdiksco c ❗ ➡ i    If the character is a valid command, get its index i in the string "dxdiksco"
                ↪ i ◀ 4    If that index is less than 4, it is either the increment or the decrement command ...
                    a ⬅ ➕ i  2 ✖ 2 ➖ 1   ... adjust accumulator accordingly

                 ↪ i ◀ 6    Else, if it is smaller than 6, it is the square command ...
                    a ⬅ ✖ a   ... multiply the accumulator by itself
                     Else, it must be the print command ...
                      a 10 ❗❗   .. output the accumulator in base 10, followed by a line feed

                ↪ a  - 1  a  256    If the accumulator is now either -1 or 256 ...
                    0 ➡  a   ... reset it to 0

```
> 0 votes

# Answer
# Pip, 70 bytes

```
W(O">> ")&#YqR'i'xFcy@`[xkcdso]`;V("U SQ:  P i&D SQ:"^sAc)."i*:i!=256"

```

(-1 byte if no space is needed after the `>>`, which is what the accepted answer does but is contrary to the example given in the question. +1 byte if an empty line isn't an acceptable way of marking end-of-input.)

Try it here!

### Explanation

The core of the interpreter is based on my answer to the other Deadfish question, with some reshuffling to accommodate the `xkcd` input, so I won't repeat that part of the explanation. The interaction loop is as follows:

```
W                                 While...
  O">> "                           Output the prompt with no newline
 (      )&                         Logical AND that (nonempty string, truthy) with...
            q                      Read a line of input
             R'i'x                 Replace all i's with x's
           Y                       Store it in y
          #                        Take the length
                                  So, loop while (prompt and read input) is nonempty:
                                    [translate and eval all valid commands in y]

```
> 0 votes

# Answer
# AWK, ~~\[133\]~~ 122 bytes

```
gsub(z,FS){for(a=0;b=$++a;c==-1||c==256?c=0:0)if(b~"o"||b~"c")print c;else b~"i"||b~"x"?c++:b~"d"?c--:b~"s"||b~"k"?c*=c:0}

```

Try it online!

*Thanks to user41805 for hints that dropped 11(!) chars*

This is pretty straight forward in the end. I think the only reason it's somewhat short is that AWK is essentially a state machine, which fits the problem pretty well.

```
gsub(z,FS)

```

Splits the input line such that each letter is one positional field.

```
{for(a=0;b=$++a; ... ) ... }

```

Loops through all the positional variables (one letter for each one).

```
c==-1||c==256?c=0:0

```

The `end of loop` statement just handles the wrap around code, resetting the accumulator `c` when it hits `-1` or `256`.

```
if(b~"o"||b~"c")print c;else ...

```

The print command can't be handled by the nested ternary that deals with all the other commands, since in AWK `print` doesn't return a value. So that's pulled out into an `if/then/else` statement.

```
b~"i"||b~"x"?c++:b~"d"?c--:b~"s"||b~"k"?c*=c:0

```

Handles all the other commands, adjusting the accumlator `c` as necessary.
> 0 votes

---
Tags: code-golf, interpreter, deadfish
---


title: Levenshtein Your Source

text:
# Question
Title: Levenshtein Your Source
> The Levenshtein edit distance between two strings is the minimum possible number of insertions, deletions, or substitutions to convert one word into another word. In this case, each insertion, deletion and substitution has a cost of 1.
>
> For example, the distance between `roll` and `rolling` is 3, because deletions cost 1, and we need to delete 3 characters. The distance between `toll` and `tall` is 1, because substitutions cost 1.
>
> Stolen from original Levenshtein question

Your task is to calculate the Levenshtein edit difference between an input string and your source. This is tagged , so cheating quines (for example, reading your source code) are *not* allowed.

### Rules

* The input will be non-empty and will be composed of ASCII, unless your source contains non-ASCII, in which case the input may include Unicode. Regardless, the Levenshtein distance will be measured in characters, not bytes.
* The output is the minimum Levenshtein edit distance of the input and your source.

This is , so shortest answer, in bytes, wins.

# Answer
> 6 votes
# Python 2 + sequtils, 101 bytes

```
from sequtils import*;_='from sequtils import*;_=%r;print edit(_%%_,input())';print edit(_%_,input())

```

# Answer
> 5 votes
# Python 2, ~~278~~ 258 bytes

```
t=input();s,f='t=input();s,f=%r,lambda m,n:m or n if m*n<1else-~min(f(m-1,n),f(m,n-1),f(m-1,n-1)-((s%%s)[m-1]==t[n-1]));print f(len(s%%s),len(t))',lambda m,n:m or n if m*n<1else-~min(f(m-1,n),f(m,n-1),f(m-1,n-1)-((s%s)[m-1]==t[n-1]));print f(len(s%s),len(t))

```

Try it online!

This is just the usual quine in Python, mixed with the Levenshtein algorithm from this answer. Note that it gets ~~quite~~ *extremely* (thanks to Mr. Xcoder :P) slow.

# Answer
> 2 votes
# Vyxal `D`, 10 bytes

```
`:qp꘍`:qp꘍

```

Try it Online!

Thanks to Aaron Miller for this one.

```
`:qp `:qp  # Standard quine
    ꘍    ꘍ # Levenshtein distance

```

# Vyxal `D`, 13 bytes

```
`q\`:Ė\`+꘍`:Ė

```

Try it Online!

```
`q\`:Ė\`+ `:Ė # Standard eval quine (see https://codegolf.stackexchange.com/a/232956/100664)
         ꘍    # Leveshtein distance with input

```

10 bytes in Vyxal 2.6, whiich hasn't been released yet

# Answer
> 2 votes
# Haskell, 210 bytes

```
main=interact$show.((x++show x)%);x@(a:c)%y@(b:d)|a==b=c%d|1>0=1+minimum[x%d,c%y,c%d];x%y=length$x++y;x="main=interact$show.((x++show x)%);x@(a:c)%y@(b:d)|a==b=c%d|1>0=1+minimum[x%d,c%y,c%d];x%y=length$x++y;x="

```

Try it online!

Computes the levenshtein distance modified from here. (I wrote the code there too) This is combined with a standard quine mechanism. Not much special here.

If you want to play around with it I suggest making edits towards the end of the string. The algorithm is more or less \\$O(n+m^4)\\$ where \\$n\\$ is the location of the difference between the input and the source, and \\$m\\$ is the length of the string after the first difference. So if you add a character to the front of this the compute time is exponential with the length of input and you won't see your result on tio.

# Answer
> 2 votes
# Python 3.8 (pre-release), 135 bytes

```
exec(s:="l=lambda a,b:min(l(A:=a[1:],B:=b[1:])-(a[0]==b[0]),l(A,b),l(a,B))+1if b>''<a else len(a+b);print(l('exec(s:=%r)'%s,input()))")

```

Try it online!

took my solution of levenstein distance (https://codegolf.stackexchange.com/a/233868/103772) and adapted it to a quine. It is very (very) slow but it works

# Answer
> 1 votes
# JavaScript, 113 bytes

This is a valid quine.

```
f=t=>[...t].map((v,j)=>x=x.map((w,k)=>q=k--?Math.min(q,w,x[k]-(v==u[k]))+1:j+1),x=[...[,...u=`f=${f}`].keys()])|q

```

```
f=t=>[...t].map((v,j)=>x=x.map((w,k)=>q=k--?Math.min(q,w,x[k]-(v==u[k]))+1:j+1),x=[...[,...u=`f=${f}`].keys()])|q

console.log(f('f=t=>[...t].map((v,j)=>x=x.map((w,k)=>q=k--?Math.min(q,w,x[k]-(v==u[k]))+1:j+1),x=[...[,...u=`f=${f}`].keys()])|q'));
console.log(f('%'));
console.log(f('12345'));
```

Idea stolen from other answer.

---
Tags: code-golf, string, quine, edit-distance
---


title: Evaluate left-or-right

text:
# Question
Title: Evaluate left-or-right
*Originally sandboxed by @xnor*

Left-or-right is a very simple language @xnor made up. Its expressions are made of arrows `<` (left), `>` (right), and parentheses. The goal is to evaluate an expression to either `<` or `>`.

An expression `A<B` picks the left item `A`, while `A>B` picks the right one `B`. Think of `<` and `>` as arrows pointing to the item we want, not as comparison operators.

Take, for example, `><>`. The operator in the middle is `<`, and confusingly, the items on each side `A` and `B` are also arrows. Since the operator tells us to take the left one `A`, which is `>`. So, `><>` equals `>`.

Expressions also nest. We can replace the expression with its value. So, for example, `(><>)<<` equals `><<` equals `>`. And, `>(><>)<` equals `>><` equals `<`. For another example, `(><>)(<<<)(>><)` equals `><<` equals `>`.

In the input, you'll be given a well-formed expression consisting of either a trio of arrows like `><>` or the result of repeatedly replacing some arrow by a trio of arrows in parens like `><(><>)` . You can assume the input won't already be a lone arrow. You may alternately accept the whole inputs encased in parens like `(><>)` or `(<(><>)>)`.

The input is given as a flat string consisting of symbols `<>()`. You may not take it in a pre-parsed form like a tree.

The shortest code in bytes wins.

## Test cases

Generated using this script.

### Evaluates to `<`

```
>><
<<(<><)
(>>>)><
(<(<<>)(<<<))<<
((>(>><)>)(><>)>)><
(<<(>(<>>)<))((><>)(><<)>)(<<<)
((<<<)<>)((>><)<(<><))((>>>)<<)
>(>((><>)<>)(<>>))((>><)((><>)<<)<)
((><<)(><<)(<<>))(<(>><)(>><))(<<(<<>))
(<(><<)(>(>>>)>))((>>>)>>)((<>(>><))<<)

```

### Evaluates to `>`

```
<>>
((<<<)>(<<>))(><<)>
((>>>)<>)<((<<<)>>)
>(>>(<<<))(>((<>>)<<)<)
((><>)(<<>)>)(<<(<<<))(<(>>>)<)
(><((><>)><))(>(>>(>>>))(<><))(>>>)
(((>><)<>)(><>)(><>))(<<(<>>))(<<>)
((><>)<(<<(<<>)))((<(<<>)<)(<><)>)(>>>)
(<<(<><))(((<>>)><)(><<)(><>))(<(><>)>)
((>>>)<<)(<(<><)<)((<<(<<<))>(>(><>)<))

```

# Answer
## x86-16 machine code, ~~31~~ ~~26~~ 22 bytes

Saved 5 bytes thanks to @Bubbler.

Saved 4 bytes thanks to @640KB.

```
0000:0000  AC 3C 29 74 03 50 EB 0A-5A 58 3C 3E 58 74 01 92   .<)t.P..ZX<>Xt..
0000:0010  58 52 E2 EC 58 C3                                 XR..X.

```

Callable function.

Expects `SI` = address of code, `CX` = length of code.

Expects the code to be enclosed in `(...)`:

> You may alternately accept the whole inputs encased in parens like `(><>)` or `(<(><>)>)`.

Returns the output at `AL`.

Disassembly:

```
         LOOP:                  ; Main loop:
AC            LODSB             ; AX = [SI++]
3C29          CMP     AL, ')'   ; AX == ')'?
7403          JZ      BRACE     ; * If so, jump to 'BRACE'
         PUSHSTH:               ; Otherwise...
50            PUSH    AX        ; * Push AX onto stack
EB0A          JMP     END       ; * Jump to 'END'
         BRACE:                 ; If AX == ')'?
5A            POP     DX        ; * pop TOS to DX
                                ;   * (So DX is now the rightmost angle brace)
58            POP     AX        ; * pop TOS to AX
                                ;   * (So AX is now the middle angle brace)
3C3E          CMP     AL,'>'    ; * Compare current AL with '>' (result stored in PSW)
58            POP     AX        ; * AX = left argument
7401          JZ      RAB       ;   * If prev. value of AL == '>', jump to 'RAB'
         LAB:                   ; * Handle prev. value of AL == '<':
92            XCHG    DX,AX     ;   * DX = left argument instead
         RAB:                   ; Now, DX is the chosen value.

58            POP     AX        ; * Discard TOS (which is an excess '(')
52            PUSH    DX        ; * Push DX onto stack
         END:                   ; Finally,
E2EC          LOOP    LOOP      ; * Loop the above CX times
58            POP     AX        ; Pop TOS to AX
C3            RET               ; Return to caller

```
> 12 votes

# Answer
# JavaScript (Node.js), 50 bytes

```
f=a=>a[1]?f(a.replace(/\((.>)?(.)(<.)?\)/,'$2')):a

```

Try it online!

Repeat apply regex replace until only 1 char left. The regex `/\((.>)?(.)(<.)?\)/` get the calculate result as 2nd capturing group.

---

Save 1 byte, thanks to Arnauld
> 11 votes

# Answer
# \>\<\>, 121 bytes

```
0&v
>o ;
^? <=1l~<;o~$?=">"$
<<v<<<&0 ~&~$?=">"$<
~]v&0[0~ < >
>>>i:0(?^   :>>>v
<< v<<<<<^? ="("<
+&^>>:")"=?^&:&2= ?^&1

```

Try it online!

This code takes advantage of the `><>` functionality where a new stack/register can be created, code can operate on that new stack, then once that stack is closed, the results are merged back into the lower level stack.

It reads one character (codepoint really) at a time creating new stacks whenever it hits a `(` and closing them when a `)` is encountered.

The other logic use is a simple state machine, based on the contents of the register associated with the current stack.

When the value of the register is `0` the char just read is the left hand side of the statement, a value of `1` means it's the operator (`<` or `>`), and a value of `2` means we have the right hand side.

Anytime the state is `2`, the code can resolve the 3 character on the stack (RHS, OP, LHS) to get an answer for that operation.

When the input is exhausted, we'll be back at the base stack with either `1` or `3` entries on the stack. If there are `3` entries on the stack, the code does one final operation to resolve the stack, then the sole entry on the stack is printed as a character.

The code is broken up to save characters, but I'm going to explain it using the original code. The only difference is that direction shifts, extraneous spaces and directional indicators have been removed to make it easier to see what's happening. Well, unless I goofed when formatting it...

```
# initialization
0&v  # Set the register (state) to 0, call input loop
 [0]

# [0] loop to read input and process each char
       [1]    [2]    [3]    [4]
>>>i:0(?^:"("=?^:")"=?^&:&2=?^&1+&
.. i                               # Read next char/codepoint
    :0(                            # Check it codepoint < 0
       ?^                          # If true, all input done call [1]
         :"("=                     # Compare char to "("
              ?^                   # If true, call [2] to open new stack
                :")"=              # Compare char to ")"
                     ?^            # If true, call [3] to close stack
                       &:&         # Load and resave the register
                          2=       # Compare state to 2 (RHS,OP,LHS)
                            ?^     # If true, call [4] to pick answer
                              &1+& # Increment the register (state)

# [1] code to handle EOF
             [5]
        >~1l=?^$"<"=?$~o;
.. ~                 # Delete top of stack, clean-up
    1l=              # Compare stack size to 1
       ?^            # If true, call [5] to print/exit
         $           # Flip top two stack entrys, pulls OP to top
           ">"=      # Compare OP to ">"
               ?$    # If true, flip top two stack entries
                 ~   # Delete top of stack (the choice we don't want)
                  o; # Print top of stack as char, then exit

# [5] called on EOF if the stack has only 1 entry

              >o;
.. o;           # Print top of stack as char, then exit

# [2] code to handle "(", stack a new stack
               >~0[0&
.. ~            # Delete top of stack, clean-up...
    0[          # Open a new stack with 0 entries from the old one
      0&        # Set the register (state) to 0

# [3] code to handle ")", close the stack
                       >~]
.. ~]           # Delete top of stack, close stack to merge down

# [4] code to resolve a stack with RHS,OP,LHS
                             >$">"=?$~&~0&
.. $            # Flip top two stack entrys, pulls OP to top
    ">"=        # Compare OP to ">"
        ?$      # If true, flip top two stack entries
          ~     # Delete top of stack (the choice we don't want)
           &~&0 # Set register (state) to 0

```
> 10 votes

# Answer
# APL (Dyalog Extended),  ~~30~~ 23 bytes

```
(⍎'(⊣⊢)'['(<>'⍳⍞])/'<>'
         '(<>'⍳⍞          take the input ⍞ and get the indices of '(<>'
                          this fills with the last index + 1 if not found, saving 1 char
  '(⊣⊢)'[ stuff ]         index into '(⊣⊢)', replacing <> with ⊣⊢, the left and right tack functions
 ⍎                        evaluate this as a train
                          APL trains of the form (f g h) when applied to left and right arguments x and y produce (x f y) g (x h y)
                          This translates directly to this language
                          Replacing <> with ⊣ and ⊢ which do the same thing, the input becomes a valid function in APL
(    train       )/'<>'   Reduce over '<>', which uses '<' as a left argument and '>' as a right one

```

Try it online!
> 9 votes

# Answer
# Retina 0.8.2, 22 bytes

```
{`\((.>)?(.)(<.)?\)
$2

```

Try it online!

Basically the port of my JavaScript answer in Retina. I just learnt how to write loop in past 10 minutes and got this.

`{`` loops the replace until nothing changed. The replacement calculate one step each time.
> 7 votes

# Answer
# , 30 bytes

```
')/''<>'''".@,~'(',rplc&'<[>]'

```

Try it online!

Very similar to rak1507's APL answer, though I had the idea independently -- it's natural for J, though loses some elegance because of the quote escaping.

* `rplc&'<[>]'` replace `<>` with `[]`, which in J are the "left" and "right" identity operators, meaning they return the left or right argument.
* `(` Prepend a left paren to that result.
* `')/''<>'''...,~` Append `)/'<>'` to the previous result.
* Now we have `( ~~input with [] instead of <>~~ )/'<>'`.
* Which is the same as: `'<' ( ~~input with [] instead of <>~~ ) '>'`
* `".@` Evaluate that string. From here, J trains and the definition of `[` and `]` do exactly what we want.
> 7 votes

# Answer
# Python 3, ~~98~~ 74 bytes

Saved a whopping 24 bytes thanks to ovs!!!

```
import re
f=lambda p:p[1:]and f(re.sub('\(((.)<.|.>(.))\)',r'\2\3',p))or p

```

Try it online!

Takes an input string with enclosing in parentheses and returns whether it's left (`<`) or right (`>`).
> 4 votes

# Answer
# Red, ~~136~~ ~~120~~ 86 bytes

This version is courtesy @hiimboris (https://gitter.im/red/parse)!

```
func[s][r:["<"|">"]while[parse s[to change["("x: r["<"r |">"x: r]")"](x/1)to end]][]s]

```

Try it online!
> 4 votes

# Answer
# C (gcc), ~~117~~ \\$\cdots\\$ ~~101~~ 98 bytes

Saved 10 bytes thanks to an idea from Davide!!!
Saved 3 bytes (and got below 100!) thanks to ceilingcat!!!

```
i;f(char*p){for(i=0;*p++-40||p[3]-41;++i);p[-1]=p[p[1]-62?0:2];bcopy(p+4,p,strlen(p));i&&f(p+~i);}

```

Try it online!

Takes an input string with enclosing parentheses and reduces it to either a left (`<`) or a right (`>`).

### Explanation (before some golfs)

```
i;f(char*p){                       // function taking a string parameter p
  for(i=0;p[i++]-40||p[i+3]-41;);  // loop until we find chars '(' and ')'
                                   // separated by 3 characters.
                                   // since our input is enclosed in
                                   // parentheses we will always find one.
  p[i-1]=                          // i has gone forward one but set the
                                   // first of these characters  - the '('
                                   // to...
         p[i+1]-62?                // ...depending on whether the middle
                                   // char is a '<' or a '>'...
                   p[i]:           // ...the one before the middle if '<'
                        p[i+2];    // ...the one after the middle if '>'
  memcpy(p+i,p+i+4,strlen(p));     // move the back end of the string forward
                                   // over the other 4 chars.
                                   // now a "(A<B)" is reduced to "A"
                                   // and a "(A>B)" is reduced to "B"
  ~-i&&                            // if we didn't just reduce the start of p
       f(p);                       // then recursively call f.
                                   // otherwise p is reduced to the answer
                                   // and we're done.
 }

```
> 4 votes

# Answer
# Perl 5 `-p`, 32 bytes

```
s/\((.>(.)|(.)<.)\)/$2$3/g&&redo

```

Try it online!

Takes advantage of the spec allowing outside parentheses to be required.
> 4 votes

# Answer
# Jelly, 15 bytes

```
O;1ị“/ṛ  ɗḷ”vØ<

```

A monadic Link accepting a list of characters\*, which yields a character.

* Uses the encased in parens option.

**Try it online!**

### How?

Converts the input to Jelly code which will reduce the pair `['<', '>']` to produce the answer. Jelly ignores spaces and has a 1-indexed and modular index-into function, , so the Link starts by converting the input characters to their ordinal values and uses  to form the code:

```
input character   ordinal   indexed into "/ṛ  ɗḷ"   meaning
           (        40        (space)                 ignored
           <        60        ḷ                       yield left argument
           >        62        ṛ                       yield right argument
           )        41        ɗ                       last three links as a dyadic function
(or reduce command)  1        /                       reduce by

```

So:

```
O;1ị“/ṛ  ɗḷ”vØ< - Link: list of characters   e.g. (<>>)
O               - ordinals                        [40,60,62,62,41]
 ;1             - concatenate a one               [40,60,62,62,41,1]
    “/ṛ  ɗḷ”    - "/ṛ  ɗḷ"                        "/ṛ  ɗḷ"
   ị            - index into                      " ḷṛṛɗ/"
             Ø< - "<>"                            "<>"
            v   - evaluate with input             '>'

```

---

The example above evaluated:

```
ḷṛṛɗ/ - monadic chain (with left argument ['<', '>'])
    / - reduce (['<', '>']) by - i.e. f('<', '>'):
   ɗ  -   last three links as a dyad - i.e. g('<', '>'):
ḷ     -     yield left = '<'
  ṛ   -     yield right = '>'
 ṛ    -     (ḷ) yield right (ṛ) = '>'

```
> 4 votes

# Answer
# \>\<\>, ~~36 31~~ 30 bytes

```
>i:6%0$.

v

v~0[
v0(?o$6%?$~]

```

Try it online! Verification of test cases

Takes input surrounded by parenthesis, and outputs a single character before terminating with an error.

### Explanation:

```
>i:           Take input and make a copy
   6%         Map the possible codepoints through modulo: EOF,<,>,(,) => 5,0,2,4,5
     0$.      Jump to that line

>             Line 0 ('<'): This just jumps back to the first line again
v             Line 2 ('>'): Does nothing and goes back to the first line again

v~0[          Line 4 ('('): Pop the extra copy of input and create a new stack

 0(?          Line 5 (')'): If the input is EOF (-1)
    o                       Output the top of stack (and error later)
     $6%                    Otherwise, check what the middle character is
        ?$                  If it is a >, swap the other two
v         ~]                Discard the right character and leave the other other one on top of the next stack

o~            Line 1 (EOF): If there is no more input, pop the copy and output the remaining character

```
> 4 votes

# Answer
# JavaScript (ES6),  ~~69~~  67 bytes

*Saved 2 bytes thanks to @Neil*

```
f=s=>s<(s=s.replace(/.?([<>]{3}).?/,(_,s)=>s[s[1]>'<'?2:0]))?f(s):s

```

Try it online!
> 3 votes

# Answer
# Jelly, 17 bytes

```
“)ɗ<ḷ>ṛ( ”y;”/vØ<

```

Try it online!

Same essential approach as rak1507's APL answer. Requires the input fully parenthesized.

```
“        ”y          Replace
 )                   ) with
  ɗ                  last-three-links-as-dyad,
   <                 < with
    ḷ                return-left-argument-and-ignore-right,
     >               > with
      ṛ              return-right-argument-and-ignore-left,
       (             and ( with a space which is essentially ignored.
           ;”/       Append the reduce quick,
              v      and evaluate the result as a monad with argument
               Ø<    "<>".

```
> 3 votes

# Answer
# 05AB1E, 20 bytes

```
Δ„<>3ã€…(ÿ)¬¦¨ºĆ'>ª:

```

Takes the input wrapped in parenthesis in both programs, as is allowed.

Try it online or verify all test cases.

# 05AB1E (legacy), 20 bytes

```
'<∞©3ãε…(ÿ)}¬®Ã∞®«S:

```

Should have been 19 bytes by also using `€…(ÿ)`, but apparently there is a bug in the legacy version, so we'll have to use `ε…(ÿ)}` (or `'(ì')«`) instead.

Try it online or verify all test cases.

**Explanation:**

```
Δ                     # Continue until it no longer changes, using the (implicit) input:
 „<>                  #  Push string "<>"
    3ã                #  Create all possible triplets of these two characters:
                      #   ["<<<","<<>","<><","<>>","><<","><>",">><",">>>"]
      €               #  Map over each string in the list
       …(ÿ)           #   And wrap it in parenthesis
           ¬          #  Get the first item (without popping the list): "(<<<)"
            ¦¨        #  Remove its first/last characters: "<<<"
              º       #  Mirror it: "<<<>>>"
               Ć      #  Enclose; appending its own head: "<<<>>><"
                '>ª  '#  Convert it to a list of characters, and append ">":
                      #   ["<","<","<",">",">",">","<",">"]
                   :  #  Replace all ["(<<<)",...,"(>>>)"] with ["<",...,">"]
                      # (after the loop, the result is output implicitly)

'<∞                  '# Push "<" and mirror it to "<>"
   ©                  # Store this string in variable `®` (without popping)
    3ãε…(ÿ)}¬         # Same as above
             ®Ã       # Only keep the characters that are also in `®`, removing the "()"
               ∞      # Mirror it: "<<<>>>"
                ®«    # Append `®`: "<<<>>><>"
                  S   # Convert it to a list of characters:
                      #  ["<","<","<",">",">",">","<",">"]
                   :  # Keep replacing all ["(<<<)",...,"(>>>)"] with ["<",...,">"]
                      # until there is nothing more to replace
                      # (after which the result is output implicitly)

```
> 3 votes

# Answer
# Ruby, ~~51~~ ~~49~~ 44 bytes

-1 byte thanks to Neil! (match any character `.` instead of the opening bracket `\(`)
-4 bytes thanks to Dingus! (`String#sub!` returns `nil` if there was no match)

Outputs by modifying the input. This would be 43 bytes with tsh's regex.

```
->s{s.sub!(/.((.)<.|.>(.))\)/,'\2\3')&&redo}

```

Try it online!

---

# Ruby `-p`, ~~40~~ ~~39~~ 38 bytes

-1 byte thanks to Sisyphus!

```
sub /.((.)<.|.>(.))\)/,'\2\3'while/../

```

Try it online!
> 3 votes

# Answer
# C (gcc) (no builtins), ~~147~~ 143 bytes

*4 bytes saved thanks to ceilingcat!*

```
i,m,c,q,w;f(char*s){for(i=m=w=0;c=s[i]%9;i++)if(c-1?c-4?w+=w-~c%3,++m==4:(q=i,m=w=0):0)for(s[q]=w-2&&w<9?62:60;q++<i;)s[q]=1;s=*s%3-1?*s:f(s);}

```

Try it online!

Function that takes a null-terminated `char` array as input, and returns a `char` (`int`).

Here's a visualization of how it works:

```
(((>>>)<<)(<(<><)<)((<<(<<<))>(>(><>)<)))
((>....<<)(<<....<)((<<<....)>(>>....<)))
(>........<........(<........><........))
(>........<........<....................)
>........................................

```

(In the code, it uses 0x01 instead of `.`, but due to the modulus, they're equivalent even in data representation.)

Essentially it scans the code looking for instances of `(data)`, where `data` consists of substring of 3 characters, except `'.'` and `'('`. (4, in the code, since it tracks the `)` as the 4th character.) The program keeps track of the start of this string (`q`) and a binary representation of the visited characters (`w`). If we consider `'>'` to be equivalent to the binary `1`, and `'<'` the binary `0`, we simply look at a table of what the results of the binary strings should be. As it turns out, for `q=1,4,5,6`, the answer is `'<'`, and `'>'` otherwise. Thus, `w-1&&w<5` is a sufficient determiner. (In fact, since we keep track of `)` as part of this binary string, we have to consider that everything is doubled, and for no byte cost, we can modify this formula to obtain the `w-2&&w<9`.)

After we determine what the result should be, we replace the initial `(` with the result, and all subsequent characters with `.`. Then, so long as the initial character of the string is `(`, we repeat our function. This allows us to skip moving the string around, which, in my head, should save bytes, but I haven't tested the alternative.

Started working on this before I saw the existing (much shorter) C answer. But I enjoyed this nonetheless.
> 3 votes

# Answer
# PCRE, 52 bytes

```
(((<|>|\((?3){3}\))(?=(?>(?4))?>)(?3))?(\((?1))?)(.)

```

Try it online! Link includes Perl 5 test harness. Does not take outer parentheses (admittedly a version that takes outer parentheses would probably be shorter.) The desired result is captured in group 5. Explanation: Group 3 matches an operator. Group 2 matches two operators, but only if the second operator evaluates to `>`; a recursive atomic match is used to determine whether that is true. Group 4 then recurses if the current operator is an expression.

```
(               Group 1 is:
 (              Group 2, which is:
  (             Group 3, which is either:
   <|>|         ... a literal `<` or `>` or...
   \((?3){3}\)  ... three recursive matches of group 3 inside parentheses;
  )
  (?=           Followed by a lookahead to:
   (?>(?4))?    An optional atomic recursive match of group 4...
   >            ... which must be followed by a `>`;
  )
  (?3)          Followed by another recursive match of group 3.
 )?             Group 2 is optional.
 (              Group 4, which is...
  \(            ... a literal `(`...
  (?1)          ... followed by a recursive match of group 1.
 )?             Group 4 is optional.
)               End of group 1.
(.)             Group 5 then captures the desired result.

```
> 3 votes

# Answer
# \>\<\>, ~~22~~ 20 bytes

*-2 bytes thanks to Jo King*

```
i:2%?\
?$~$~\0(?o$6%

```

Try it online! or verify all test cases

## Explanation

```
i:2%?\              main loop:
i                     Read a character from the input and push it onto the stack
 :2%?                 If it's not a multiple of two (")" or EOF),
     \                  Swap to the branch
                      IP wraps around, repeat

?$~$~\0(?o$6%       branch:
     \                Entrance
      0(?             If the character is less than 0 (EOF),
         o$             Output the result and error
                      Otherwise,
          $             Check the middle value
?          6%           If it's not a multiple of 6 (">"), [the IP wraps around]
 $         $              Reverse the other two values
  ~                     Pop the right value
   $~                   Remove the "(" from the stack
     \                  Return to the main loop

```
> 3 votes

# Answer
# Stax, 23 bytes

```
ü▼2δ`▀ÆH╞íq`º╪ ≈♀ô☺ßX→ú

```

Run and debug it

Uses the same regex as tsh's Javascript solution, and replaces till a fixed point is reached.

## Explanation

```
"\((.>)?(.)(<.)?\)".$2RgiH
                       g   generator:
                        i  apply the following till invariant:
"\((.>)?(.)(<.)?\)".$2     regex replace with second capture group
                         H take last generated value

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), 54 bytes

```
#//._[a___,"(",b_,c_,d_,")",e___]->a.If[c=="<",b,d].e&

```

Try it online!

Input a list of characters.
> 2 votes

# Answer
# Python 3.8 (pre-release), 73 bytes

```
f=lambda s:~(q:=s.rfind('('))and f(s[:q]+s[q+ord(s[q+2])-59]+s[q+5:])or s

```

Try it online!

# Python 3, 77 bytes

```
def f(s):q=s.rfind('(');return~q and f(s[:q]+s[q+ord(s[q+2])-59]+s[q+5:])or s

```

Try it online!

Solution without regex. Requires the whole input be parenthesized.

-1 byte thanks to ovs
> 2 votes

# Answer
# Charcoal, 27 bytes

```
Ｆ⁻Ｓ(≡ι)«≔⊟υθ≡⊟υ>§≔υ±¹θ»⊞υιυ

```

Try it online! Link is to verbose version of code. Takes input wrapped in `()`s. Explanation: Port of @2x-1's answer.

```
Ｆ⁻Ｓ(

```

Remove `(`s from the input and loop over the remaining characters.

```
≡ι)«

```

If the current character is a `)` then...

```
≔⊟υθ

```

... pop the last character from the stack; and ...

```
≡⊟υ>

```

... if the (second) last character was a `>` then...

```
§≔υ±¹θ

```

... overwrite the (third) last character with the originally popped character.

```
»⊞υι

```

Otherwise push the current character to the stack.

```
υ

```

Print the final remaining character.
> 1 votes

# Answer
# Java (JDK), 76 bytes

```
s->{while(s.length()>1)s=s.replaceAll("\\((.>)?(.)(<.)?\\)","$2");return s;}

```

Try it online!

## Credits
> 1 votes

# Answer
# Julia, 61 bytes

using tsh's regex

```
f(x,y=replace(x,r"\((.>)?(.)(<.)?\)"=>s"\2"))=x==y ? x : f(y)

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Unicode), 27 bytes

```
'\((.>)?(.)(<.)?\)'⎕R'\2'⍣≡

```

Try it online!

This is longer than rak1507's answer, but I just wanted to use a different approach. Uses the same regex as everyone else.
> 1 votes

# Answer
# Pip, 24 bytes

```
L#aaR:`\((...)\)`B@A@>Ba

```

Try it online!

### Explanation

This one is a regex replacement solution:

```
L#aaR:`\((...)\)`B@A@>Ba
                          a is command-line argument
L#a                       Do the following len(a) times:
   aR:                     In a, replace (and assign back to a)
      `         `          this regex:
       \(                   Literal open paren
         (...)              Three characters (captured in group 1)
              \)            Literal close paren
                           with the result of the following callback function:
                    @>      All but the first character of
                      B     capture group 1
                   A        ASCII code of (the first character of) that string
                 B@         Use that value to index cyclically into group 1
                       a  After the loop, output the value of a

```

The replacement works because the charcode of `<` is 60 and the charcode of `>` is 62. Using those values as modular 0-based indices into a three-character string gives the first character and the last character, respectively--exactly what we need.
> 1 votes

# Answer
# Pyth, 25 bytes

```
u:G."(\‹Kž%<—åkí2""\\2

```

Try it online!

---

Uses the regex from tsh's Javascript answer. Replaces each match with its second matching group until a fixed point is found and printed.
> 0 votes

# Answer
# sed -r 4.2.2, 27

Using the same regex as everyone else:

```
:
s/\((.>)?(.)(<.)?\)/\2/
t

```

Try it online!
> 0 votes

# Answer
# Pip, 27 bytes

```
VaR^"<>"''._R'("({bQ'<?ac}"

```

Takes input with outer parentheses. Verify all test cases: Try it online!

### Explanation

Translates the input into a Pip expression and evaluates it. In Pip, function call syntax is `(f a b c)`, so all we have to do is quote the angle brackets and insert an appropriate function inside each opening parenthesis:

```
 a                           Command-line input
  R                          Replace
   ^"<>"                      either of < and > with
        ''._                  itself with a single quote prepended
            R                Replace
             '(               open parenthesis with
               "(         "   open parenthesis followed by a string representation of
                 {       }    this function:
                  bQ'<?        If the second argument is equal to <
                       a        then return the first argument
                        c       else return the third argument
V                            Evaluate as Pip code

```
> 0 votes

# Answer
# Nim \+ npeg, 196 bytes

```
import npeg
let p=peg(t,s:seq[int]):
 t<-o[3]:
  let a=[s.pop,s.pop,s.pop];s.add a[a[1]*2]
 o<-'('*t*')'|a
 a<- >'<'| >'>':s.add int $1<">"
var
 s= @[4]
 m=p.match(stdin.readAll,s)
echo "><"[s[1]]

```

Using an actual parsing library, yay!
> 0 votes

---
Tags: code-golf, string, interpreter
---


title: Create a Checkbox

text:
# Question
Title: Create a Checkbox
Write a program that creates a two-state checkbox that people can interact with using a mouse.

Specifically, your program should achieve all of the following:

1. Have a 8×8 pixel (or larger if desired) region of the screen that is the clickable area of the checkbox. Henceforth this region is simply called the checkbox.
2. When the mouse cursor is moved within the checkbox and the default\* mouse button is pressed, the checkbox should toggle states.
Checked becomes unchecked. Unchecked becomes checked.
3. The checkbox should not move when it is toggled.
4. In the checked state, the checkbox may be any colors.
5. In the unchecked state, the checkbox may be any colors **as long as at least 16 pixels are visually distinct from the checked state**.
6. In a single program instance, all checked states should be visually identical to one another and all unchecked states should be visually identical to one another.
7. Don't end the program until it's explicitly terminated (e.g. via exit button or Alt+F4), so a user can click the checkbox as much as they want.

\*You may assume the default mouse button is always left click, but it's also fine to use the default as defined by mouse software or the OS, which may not actually be left click depending on the user.

# Notes

* It does not matter what is outside of your checkbox region. It could just be the desktop. It could be a portion of a console that changes on every toggle.
* It does not matter what state your checkbox starts in.
* The checkbox region may have any dimensions at or above 8×8 pixels. It need not be square.
* You may make minor allowances for settings that are out of your control such as console font size, browser zoom, monitor resolution, etc. As long your program works in a reasonable test setting it should be valid.
* If your program opens a window, you may assume it has been dragged to an appropriate location on the screen if necessary (e.g. top left corner).
* You may use markup languages such as HTML or other languages we usually don't consider as full-fledged programming languages.
* Your checkbox *must* be be toggleable using the default mouse button. It's alright if it also toggles for other forms of input (e.g. right mouse button), **with the exception of mouse motion**. i.e. the state should not change if the mouse is merely moved within the checkbox.
* **Screenshots of your checkbox in action are highly encouraged!**

# Scoring

The shortest code in bytes wins.

# Example

A canonical HTML example in 23 bytes.

```
<input type="checkbox">
```

For me in Google Chrome, this makes a 12×12 pixel checkbox and about 30 pixels clearly change between checked and unchecked states.

I make the allowance that browser zoom is at 100%.

# Answer
## Mathematica, 10 bytes

```
Checkbox[]

```

Assumes Mathematica's notebook environment.

The two states look like this:
> 33 votes

# Answer
## HTML, 20 bytes

Don't know how valid this will be as an answer. HTML requires the tag to be closed to legally validate, but modern browsers will automatically close them so it's executable.

```
<input type=checkbox
```
> 32 votes

# Answer
# Bash, ~~67~~ ~~55~~ ~~50~~ ~~35~~ ~~32~~ 31 bytes

```
:()(read -p$[i^=1]
›?9h -sn6
:)

```

The code contains a CR byte (first newline) and a CSI byte (small right angle bracket with the Windows-1252 encoding). It requires xterm (or equivalent) and the ISO-8859-1 encoding (or similar).

The code defines a function named `:`, which alternately displays a white **1** or **0** in a black rectangle. There are exactly 24 differing pixels with xterm's default settings. (proof)

For an older version that toggles the color of the entire terminal, check revision 10 of this answer.

*Thanks to @ais523 for suggesting* xterm, *which saves 4 bytes!*

### How it works

`:(...)` creates a function named `:` that executes `...`.

The *read* command does the actual magic.

* `-p` specifies an input prompt, which is printed to STDOUT.

+ `$[i^=1]` is an arithmetic expansion which XORs the variable **i** with **1**. **i** may initially be unset; when this occurs, it will be treated as **0**.
    + The carriage return places the cursor back at the beginning of the line.
    + `›?9h` captures the mouse in supported terminals. Each click will send six characters to the terminal, namely `←[Mbxy`, where  represents the ESC byte (**0x1b**). `←[` indicates an escape sequence, `M` the mouse, `b` the button (**0x20** \+ the button number), `x` the **x** coordinate of the click (**0x20** \+ coordinate), and `y` the **y** coordinate.
    + `-sn6` makes *read* silent (the mouse input won't be echoed to STDERR) and stops after reading exactly 6 bytes. It saves the input in the **REPLY** variable, but we're not interested in the output it produces.

Finally, once *read* finishes (after exactly one mouse click), `:` recursively calls itself, entering an infinite loop.

### Creation and invocation

```
$ echo $':()(read -p$[i^=1]\r\x9b?9h -sn6\n:);:' > checkbox.sh
$ xxd -c 17 -g 1 checkbox.sh
0000000: 3a 28 29 28 72 65 61 64 20 2d 70 24 5b 69 5e 3d 31  :()(read -p$[i^=1
0000011: 5d 0d 9b 3f 39 68 20 2d 73 6e 36 0a 3a 29 3b 3a 0a  ]..?9h -sn6.:);:.
$ LANG=en_US xterm -e bash checkbox.sh

```

### Output
> 29 votes

# Answer
# GitHub Flavored Markdown - 6 bytes

```
- [ ]

```

(There is a trailing space)

In a gist :
> 25 votes

# Answer
# HTML + JavaScript, ~~32~~ ~~30~~ 25 chars

```
<p onclick=innerHTML^=1>0
```
> 24 votes

# Answer
# Processing, ~~78~~ ~~66~~ ~~65~~ ~~63~~ 61 bytes

*2 bytes saved thanks to @TuukkaX by using `-a%2` instead of `a%2*-1`*

*2 bytes saved thanks to @TuukkaX by using `a=-a`*

```
int a=1;void draw(){background(a);}void mousePressed(){a=-a;}

```

The checkbox alternates between being black and white.

### Explanation

```
int a=1;                   //the variable that contains the state of the checkbox
void mousePressed(){a=-a;} //if the mouse is pressed, change the sign of a

```

Now there are many other alternatives like using an if-statement to process this, but then it gets weird and constantly changes the background while the mouse is being pressed. I first tried `mouseButton`, but then I would need more conditions and more code that will just end up much more verbose.

Now for `mousePressed()` to be called forever (otherwise it would just stop after the program has just started), we need a `draw()` function.

```
void draw(){               //loop infinitely
  background(a);           //set the sketch's background to -a%2
  //if a ==  1, the background colour is set to almost black
  //if a == -1, the background colour is set to white
}

```

---

A smaller checkbox would be 90 bytes (the checkbox is in the top left corner, so we can remove some mouse conditions):

```
int a=1;void draw(){fill(a);rect(0,0,8,8);}void mousePressed(){if(mouseX<9&mouseY<9)a=-1;}

```
> 22 votes

# Answer
# Unix Shell (+x11-apps), 3 bytes

**Disclaimer**

The answer below is boring, borderline and "feels cheating" (at least to me).

Yet, it does not seem to violate any of the challenge rules "as written", or "default loopholes", so I'm posting it.

(If you can point a specific rule it breaks, please comment on !)

**Golfed**

```
xgc

```

> The xgc program demonstrates various features of the X graphics primitives.

The *xgc* screen is actually filled with various checkboxes:

and "sticky buttons" (which qualify as checkboxes, under this challenge rules):
> 22 votes

# Answer
# AHK, 25 bytes

```
Gui,Add,Checkbox
Gui,Show

```

Output -
> 18 votes

# Answer
# Scratch, 2 blocks

Put this script in the default sprite (which comes with 2 costumes)
> 17 votes

# Answer
## Python REPL, 45 bytes

```
from tkinter import*
Checkbutton(Tk()).pack()

```
> 14 votes

# Answer
# GeoGebra, 10 bytes

```
Checkbox[]

```

Entered into the input bar.

Here is a gif of the execution:
> 14 votes

# Answer
# Tcl/Tk, 21 byte

**Golfed**

```
grid [checkbutton .c]

```
> 13 votes

# Answer
# HTML with JavaScript - ~~136~~ ~~124~~ ~~120~~ ~~115~~ ~~113~~ ~~111~~ ~~109~~ 79 bytes

```
<p style=height:20;border:solid onClick=t=this;t.innerHTML=(t.e=!t.e)?'x':''>

```

-2 with thanks to @KritixiLithos

Reduced to 79 after some fantastic golfing from @Jan. Although the new version fits the requirements I have kept the old version for professional pride reasons.

While it is perfectly valid to use built-ins, I thought it was more fun to create my own from scratch. Tested with Chrome and Firefox. `border:solid` is there for IE compatibility but I don't know if it is actually needed in newer IE versions - I don't have IE available to test.

The `px` in the height is there for the benefit of "Run code snippet" so is not included in the "real" byte count. It works fine in the browser without it.

```
<p style=height:20px;border:solid onClick=t=this;t.innerHTML=(t.e=!t.e)?'x':''>
```

Previous version:

```
<p id=d style="width:20px;height:20px;border:solid 1px"onClick="d.innerHTML=d.innerHTML=='x'?'':'x'"align=center>
```
> 11 votes

# Answer
# Minecraft 1.0.0, 1 byte

A lever in Minecraft meets all the criteria for a check box. This answer is only valid for older versions of the game where punching a lever still toggles it.

Scored using @Connor O'Brien's suggested byte count.
> 10 votes

# Answer
## Any version of Windows command line, 3 bytes

**(cmd.exe, batch, powershell, start-\>run, whatever)**

```
osk

```

Opens the on-screen-keyboard which has several "checkboxes" such as shift, ctrl, alt, capslock keys Similar to the xgc answer, and inspired by the SmileBASIC answer screenshot.
> 10 votes

# Answer
# TI-Basic, 15 bytes

```
While 1:Shade(0,9:Input :ClrDraw:Input :End

```

Fairly straightforward. The checkbox covers approximately 40% of the screen and alternates between black and white. When checked, the screen will look something like this:

>
> 8 votes

# Answer
# Octave, ~~36~~ 20 bytes

```
uicontrol('sty','c')

```

Thanks to @LuisMendo saved 16 bytes!
> 7 votes

# Answer
# Excel VBA, ~~38~~ ~~32~~ ~~31~~ 29 Bytes

Immediates Window function that inserts a checkbox of height=9 and width=9, at the cell `A1` on the first sheet of the active Excel VBA project

```
Sheet1.CheckBoxes.Add 0,0,9,9

```

-6 Thanks to pajonk for replacing `[A1],[A1],9,9` with `0,0,9,9`

-1 for replacing `Sheets(1)` with `[Sheet1]`

-2 for realizing the above was stupid and using `Sheet1` instead
> 7 votes

# Answer
# SmileBASIC, 49 bytes

```
@L
O=T
TOUCH OUT T,,
X=T<O!=X
KEY 1,""[X]GOTO@L

```

and  are an empty box and a checked box in SB's font.
Toggle the checkbox by touching the screen (the closest thing to clicking with a mouse)

# Cheating answers:

### 0 bytes:

(the on-screen keyboard has buttons that act like checkboxes, such as the caps lock and insert keys)

### 14 bytes:

```
EXEC"SYS/SBGED

```

Opens up the built in graphics editor, which has multiple checkbox-like buttons
> 7 votes

# Answer
# KV Lang, 8 bytes

```
CheckBox

```

---

assuming a really basic Python environment for kv lang to even run:

```
from kivy.app import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('CheckBox'))

```

This works basically because `CheckBox` is a Kivy widget included in a `kivy.Factory` as each widget from the standard library.

That simple string creates an instance of `CheckBox` and because of `runTouchApp` expecting a widget to run I can use `Builder.load_string`.

The background of `load_string` handles basically every kv string and if there is a single instance of a widget defined (e.g. `CheckBox`), then it is elevated to a **root** widget position, for example:

```
Application
    openGL Window
        root widget(mostly layout)
            main tree
            and some widgets
            ...

```
> 7 votes

# Answer
## C#, ~~124~~ 120 bytes

saved 4 bytes thanks to grabthefish.

note: because of edits, the picture doesn't exactly represent what the code makes, the "checkBox1" isn't displayed with the current code.

```
using System.Windows.Forms;class P{static void Main(){var a=new Form();a.Controls.Add(new CheckBox());a.ShowDialog();}}

```

ungolfed: `using System.Windows.Forms;
class P{
 static void Main(){
 var a=new Form();
 a.Controls.Add(new CheckBox());
~~Application.Run(a);~~
 a.ShowDialog();
 }
}`
> 7 votes

# Answer
# Ruby with Shoes, 16 characters

```
Shoes.app{check}

```

Sample output:
> 6 votes

# Answer
# Powershell v5+, 94 Bytes

```
($a=[Windows.Forms.Form]::new()).Controls.Add([Windows.Forms.Checkbox]::new());$a.ShowDialog()

```

This is pretty terrible, but I can't get the statements any shorter with either `Add-Type` or `using namespace` \- and the variable is required, since I need to reuse the object to show the form, and `Controls.Add()` returns nothing usable.

`ShowDialog` is required on my system to have the box be interactive after running this command, otherwise the form is frozen.

also `System.Windows.Forms.Form` can only be shortened to `Windows.Forms.Form` before (at least my own) system stops auto completing it in a fresh session.
> 6 votes

# Answer
## HTML with JavaScript, ~~46~~ ~~33~~ 28 bytes

```
<body onclick=innerHTML^=1>0

```

v2

```
<body onclick=this.innerHTML^=1>0

```

v1

```
<body onclick=t=this;t.innerHTML=t.e=!t.e||''>

```

This is a variant on @ElPedro's answer: Create a Checkbox . Got down to 28 bytes with the help of @Albert Renshaw It could be further reduced, but that would make it identical to Create a Checkbox

The whole application area is clickable. It will display `0` in the `off` state and `1` in the `on` state. Try it out at https://jsbin.com/nuhetiyocu/1/edit
> 6 votes

# Answer
# Operation Flashpoint scripting language, 273 bytes

**To show the checkbox:**

```
createDialog"b"

```

**But first it must be defined:**

Save the following to a file named `description.ext` in the mission folder:

```
class b{idd=999;movingEnable=1;class controls{class c{idc=457;x=0.1;y=0.1;w=0.1;h=0.1;text="";action="if(ctrlText 457=={})then{ctrlSetText[457,{V}]}else{ctrlSetText[457,{}]}";type=1;style=2;colorText[]={1,1,1,1};font="tahomaB36";sizeEx=0.1;}}}

```

**The checkbox in action:**
> 5 votes

# Answer
# Pug, 20 bytes

```
input(type=checkbox)

```
> 4 votes

# Answer
## VBA (Word), ~~74~~ 57 bytes

-17 thanks to Taylor Scott

```
Sub a()
f = a.FormFields.Add(Selection.Range, 71)
End Sub

```

Filename of the document should be a.
> 4 votes

# Answer
# Clojure, ~~201~~ ~~195~~ ~~145~~ 127 bytes

```
(ns c(:require[quil.core :as q]))(def a(atom nil))(q/defsketch b :draw #(q/background(if@a 0 99)):mouse-clicked #(swap! a not))

```

-6 bytes by getting rid of the need for `m/fun-mode`.

-50 bytes by removing the `:setup` and `:size` options, since they are defaultable and unnecessary in non-`fun-mode`. Also removed the unnecessary import for middleware.

-18 bytes thanks to @ASCII-only. Changed to "smaller" colors, and removed an unnecessary space before the dereference operator (`@`).

Creates a Quil sketch (a Clojure library that provides a layer over Processing), therefore, this requires the Quil library to run.

```
(ns bits.golf.checkbox
  (:require [quil.core :as q]))

; Mutable global variable to hold the toggle state
(def a (atom nil))

(q/defsketch b
         ; Draw the background color to be either black or red depending on the toggle state.
         :draw #(apply q/background (if @a [0 0 0] [255 0 0]))

         ; Negate the state on mouse click
         :mouse-clicked #(swap! a not))

```
> 4 votes

# Answer
# AutoIt, 78 Bytes

```
GUICreate(0)
GUISetState(GUICtrlCreateCheckbox(0,0,0))
Do
Until GUIGetMsg()=-3

```

Opens a maximized window that can be closed like any other windows window. The maximization and ... on-top-ness is a side effect of the golfing.
> 3 votes

# Answer
## Python, 62 bytes

```
from tkinter import*
a=Tk()
Checkbutton(a).pack()
a.mainloop()

```
> 3 votes

# Answer
# Jolf, 19 bytes

```
"<Ξ♠ΐ♠type=Ξ\t5δbox>

```

Replace `\t` with a tab literal and  with `0x06`. Try it here!

```
"<Ξ♠ΐ♠type=Ξ\t5δbox>
"...................   string containing...
 <                     "<"
  Ξ♠ΐ♠                 compressed for "input "
      type=            "type="
           Ξ\t5δ       compressed for "CHECK"
                box    "box"
                   >

```

This displays a checkbox to the output element.
> 3 votes

# Answer
## Slim, 21 Bytes

```
input type="checkbox"

```

Try it here

So yeah. One of slim's major features is that \< and \> characters are not there. So basically, I get 2 bytes less than the creator of the question!
> 3 votes

# Answer
# Bash + zenity, 31

```
zenity --checklist --column a a

```
> 3 votes

# Answer
# Bash (+yad), 23 bytes

**Golfed**

```
yad --form --field :chk

```

> YAD is a program that will display GTK+ dialogs, and return (either in the return code or on standard output) the users input. This allows you to present information, and ask for information from the user, from all manner of shell scripts.

Yad is available in Debian and Ubuntu repositories (and probably others).

**Demo**
> 3 votes

# Answer
## C#, 814 bytes

Out of interest I decided to see how many bytes it would take to use a console application in C# using the mouse to change the checked state. There is no built in support so you have to use unmanaged code and it get's very long, very fast. There might be room for improvement but it's never going to be short.

Note: It does seem to change the checked state when the mouse is pressed and is moved at the same time. But seeing as this is never going to compete I decided to leave that be as a quirk.

```
using System;using System.Runtime.InteropServices;class P{static void Main(){int m=0,n=0,c=0;var h=GetStdHandle(-10);GetConsoleMode(h,ref m);SetConsoleMode(h,m&=~64);new System.Threading.Thread(()=>{for(;;){var r=new[]{new r()};ReadConsoleInput(h,r,1,ref n);Console.Clear();if(r[0].e==2&&r[0].m.s==1)Console.BackgroundColor=++c%2<1?0:(ConsoleColor)1;}}).Start();}[StructLayout((LayoutKind)2)] struct r{[FieldOffset(0)]public int e;[FieldOffset(4)]public m m;}struct m{int p;public int s;}[DllImport("kernel32.dll")]static extern IntPtr GetStdHandle(int h);[DllImport("kernel32.dll")]static extern bool GetConsoleMode(IntPtr h,ref int m);[DllImport("kernel32.dll")]static extern bool SetConsoleMode(IntPtr h,int m);[DllImport("kernel32.dll")]static extern bool ReadConsoleInput(IntPtr h,[Out]r[]r,int l,ref int n);}

```

And the formatted version:

```
using System;
using System.Runtime.InteropServices;

class P
{
    static void Main()
    {
        int m = 0, n = 0, c = 0;

        var h = GetStdHandle(-10);
        GetConsoleMode(h, ref m);
        SetConsoleMode(h, m &= ~64);

        new System.Threading.Thread(() =>
        {
            for (;;)
            {
                var r = new[] { new r() };
                ReadConsoleInput(h, r, 1, ref n);

                Console.Clear();
                if (r[0].e == 2 && r[0].m.s == 1)
                    Console.BackgroundColor = ++c % 2 < 1 ? 0 : (ConsoleColor)1;
            }
        }).Start();
    }

    [StructLayout((LayoutKind)2)]
    struct r
    {
        [FieldOffset(0)]
        public int e;
        [FieldOffset(4)]
        public m m;
    }

    struct m
    {
        int p;
        public int s;
    }

    [DllImport("kernel32.dll")]
    static extern IntPtr GetStdHandle(int h);

    [DllImport("kernel32.dll")]
    static extern bool GetConsoleMode(IntPtr h, ref int m);

    [DllImport("kernel32.dll")]
    static extern bool SetConsoleMode(IntPtr h, int m);

    [DllImport("kernel32.dll")]
    static extern bool ReadConsoleInput(IntPtr h, [Out]r[] r, int l, ref int n);
}

```
> 3 votes

# Answer
# Java 1.4+, 104 bytes

```
import java.awt.*;interface g{static void main(String[]a){new Frame(){{add(new Checkbox());show();}};}}

```

-13 thanks to Kevin Cruijssen.

# Groovy, 67 bytes

```
import java.awt.*;{new Frame(){{add(new Checkbox())setVisible(1)}}}

```
> 3 votes

# Answer
# CSS, 46

Assumes a minimal HTML document, not unlike this CSS Hello World submission.

This one avoids the extra "X" of the old 42 char solution, making it conform with the rules.

NOTE: Seems to only work in Firefox (51.0.1)

```
* :after{content:'X'}*:active :after{all:unset
```

# CSS, 42 (old solution)

```
:after{content:'X'}:active:after{all:unset
```
> 3 votes

# Answer
## P5.js ~~35~~ 26 bytes

~~`function setup(){createCheckbox()}`~~

~~not really fun, but it works.~~

```
setup=s=>createCheckbox()

```

-9 bytes thanks to Kritixi
> 2 votes

# Answer
# FLTK, 48 characters

```
Function{}{}{Fl_Window{}{}{Fl_Check_Button{}{}}}

```

Sample run:

```
bash-4.3$ fluid -c checkbox.fl

bash-4.3$ fltk-config --compile checkbox.cxx
g++ -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/freetype2 -I/usr/include/cairo -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -g -O2 -fvisibility-inlines-hidden -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_THREAD_SAFE -D_REENTRANT -o 'checkbox' 'checkbox.cxx' -Wl,-Bsymbolic-functions -lfltk -lX11

bash-4.3$ ./checkbox

```

Sample output:
> 2 votes

# Answer
# C#, ~~151~~ 139 bytes

This is a longer approach than @satibel his answer, but it's completely different and doesn't require a form. Since I couldn't comment about if I could use key presses instead of mouse clicks (not enough rep.) I'm not 100% sure this is allowed, so let me know!

**EDIT**: Managed to lose 12 bytes thanks to some of my own improvements, and some are thanks to @TheLethalCoder

## Golfed

```
using c=System.Console;class p{static void Main(){for(int _=1;;_++){c.ReadKey();_%=2;c.BackgroundColor=(System.ConsoleColor)_;c.Clear();}}}

```

## Ungolfed

```
using System;
class p
{
    static void Main()
    {
        int _ = 0;
        for (int _=1;;_++)
        {
            Console.ReadKey(); //Wait for user input
            _%=2; //Prevent integer from overflowing at some point
            Console.BackgroundColor = (System.ConsoleColor)_; //Set Console background color to either 0 (black) or 1 (darkblue) depending on if our integer is even
            Console.Clear(); //Clear console window to get rid of input. This also causes the whole console window to change color
        }
    }
}

```

I know it's kind of tricky since it works with keypresses rather than mouseclicks, so let me know if that's allowed. If it's not, I'll happily remove my answer, or write a new one instead!
> 2 votes

# Answer
# Vim: 13 ~~Bytes~~ Keystrokes

```
iq<Esc>:nm a g??<CR>

```

Press `a` and toggle between `q` and `d` (feels like a lever to me ...)

Explanation:

```
 iq<Esc>   " insert a q char
 nm a      " create a normal mapping toggled by a
 g??       " rot13 the current line, q -> d -> q ...
 <CR>      " validate the mapping

```
> 2 votes

# Answer
# Javascript, ~~24~~ ~~23~~ 21

```
for(i=0;;)alert(i=!i)

```
~~```
i=0;while(1)alert(i=!i)

```~~  ~~```
i=0;while(1)alert(++i%2)

```~~

**WARNING: Might cause you to have to force-quit your browser**

This one is a neat solution because it actually is not a check box and has none of the logic of a check box, but on the surface behaves very similar to a check box (toggling change of state on button press) due to exploiting the action-based delay in javascript alerts, and meets all of the criteria of rules defined in the challenge.

Try it here **(\*Might cause you to have to force-quit your browser)**

```
<script>for(i=0;;)alert(i=!i)</script>
```
> 2 votes

# Answer
# C (Win32 Console application), ~~143~~ 131 bytes

```
#include<windows.h>
main(){MSG m;for(CreateWindow("button","",1<<28|3,0,0,8,80,0,0,0,0);GetMessage(&m,0,0,0);DispatchMessage(&m));}

```
> 2 votes

# Answer
# Red, 11 bytes

```
view[check]

```

The above code was rejected by SE as too short for a post, hence this addendum
> 2 votes

# Answer
# Java, 69 bytes

```
a->{a.removeAll();a.add(new java.awt.Checkbox());a.setVisible(1>0);};

```

Just a not-so-self-explanatory `Consumer<Frame>`. It takes a `Frame`, removes everything in it, puts a checkbox, and then makes sure the `Frame` is displayed.
> 1 votes

# Answer
# Coding, 21 bytes

```
>input(checkbox)@type

```

Finally a perfect time to use this language!
> 1 votes

# Answer
# Racket, 98 bytes

```
#lang racket/gui
((λ(f)(new check-box%[parent f][label""])(send f show #t))(new frame%[label""]))

```

At least I have a few bytes on the Clojure answer!
> 1 votes

# Answer
# VBA, 42 bytes

```
ActiveSheet.CheckBoxes.Add(1,1,8,8).Select

```

Best I could get with this!
> 1 votes

# Answer
## Emacs Lisp, 58

```
(and(widget-create'checkbox)(use-local-map widget-keymap))

```
> 1 votes

# Answer
# VB.NET, 67 (program) + 37 (additional switches) = 104

# VB.NET Windows Forms Application, 67 chars

```
Class F
Inherits Form
Dim C=New CheckBox With{.Parent=Me}
End Class

```

Compile it with

```
vbc.exe *.vb /main:F /imports:System.Windows.Forms

```

Not using `/target:winexe` switch. Assume that additional console is ok.

PS: Question about byte count.
> 1 votes

# Answer
# JQuery, 50 Bytes

```
$("<input type=checkbox>").appendTo(document.body)

```
> 1 votes

# Answer
# SAS, 145

```
proc pmenu catalog=work.c;menu m;item i dialog=d;dialog d '&1';text #1 @1 'A';checkbox #2 @1 'B';run;quit;%window w menu=work.c.m '';%display w;

```

This creates and displays a menu with an item that opens a dialogue box with a checkbox. It might be possible to golf it further, but I'm reluctant to try as this has already led to several crashed sessions :(
> 0 votes

# Answer
## C# (Windows Form Application), 82 bytes

```
using System.Windows.Forms;class F:Form{public F(){Controls.Add(new CheckBox());}}

```

*Saved bytes thanks to @Qwertiy*
> 0 votes

# Answer
## C++ with SFML, 401 bytes

-4 bytes thanks to Zacharý

```
#include<SFML\Graphics.hpp>
#include<cassert>
using namespace sf;int main(){RenderWindow w(VideoMode(300,300),"");Texture a,b;assert(a.loadFromFile("a.png")&&b.loadFromFile("b.png"));Sprite p(a),q(b);bool c=0;while(w.isOpen()){Event e;while(w.pollEvent(e)){if(e.type==Event::Closed)w.close();if(e.type==Event::MouseButtonPressed)c=!c;}w.clear(Color::White);if(c)w.draw(q);else w.draw(p);w.display();}}

```

Screenshot of the boxes :

Checked :

And unchecked :

This uses the SFML library The checkbox changes state on a `sf::Event::MouseButtonPressed` event ( left click, right click, middle click... )

If you want to test, after the creation of the render window, you may want to set the framerate limit to 60 fps ( using the line `w.setFramerateLimit(60)` ), so your computer won't burn.

This requires 2 checkboxes images in the directory where the app runs ( `a.png` and `b.png` ). For the reason it uses images, i don't know if my answer is invalid ( standard loophole ? ), but since it's needed to do graphic output...
> 0 votes

# Answer
## Javascript, 14 bytes

`alert(alert())`

In most browsers, opening two alerts causes a checkbox to be added to the second that asks whether the user wants to keep allowing alerts.

I don't see anything in the rules that means it's not ok to first have a button that the user has to push before seeing the checkbox.
> 0 votes

# Answer
## SVG, 79 characters

```
<svg><body xmlns="http://www.w3.org/1999/xhtml"><input type="checkbox"/></body>

```

Yes, there is a closing tag missing, but FireFox and Chrome display it ok.
> 0 votes

# Answer
# Funky 2, 83 Bytes

```
withdraw withnewWindow(){whenonDraw{setColor(a,1)box(0,0,8,8)}whenonMouseDown a=!a}

```

### Cleaned up and commented

```
with draw{                  $# With the draw library
    with newWindow(){       $# Open a new window with the default parameters
        when onDraw{        $# Each draw frame of the window. This can't be placed in onMouseDown due to Funky2 Automatically clearing the window
            setColor(a,1)   $# Set the color to either Green or Yellow depending on if a is 1 or not (Set color automatically adds arguments)
            box(0,0,8,8)    $# Draw a box of size 8 by 8.
        }
        when onMouseDown{   $# When any mouse button is clicked
            a=!a            $# Set a to not a. Conveniently, setColor casts it's argument to a number, so this flips between 0 and 1.
        }
    }
}

```

### Output
> 0 votes

# Answer
# Desmos, 34 bytes

Expressions(27 bytes):

```
min(x,y)<9
C=hsv(0,0,a)
a=1

```

(Make sure to select the color corresponding to `C` for `min(x,y)<9`, set the fill opacity for `min(x,y)<9` to 1, and make sure that the graph is on the default viewport.)

On-click statement(6 bytes):

```
a->1-a

```

(27+6 is 33 bytes, but I have to add one byte because of this.)

Clicking anywhere on the graph will switch the color of the graph from white to black and vice versa.

Try It On Desmos!

Try It On Desmos! - Prettified
> 0 votes

---
Tags: code-golf, interactive
---