title: Write a brain-flak classic interpreter!

text:
# Question
Title: Write a brain-flak classic interpreter!
Brain-Flak (a cross between Brainf\**k and Flak-Overstow) is a stack-based esoteric language. Since this challenge was posted, the language has evolved and updated, but this first revision of the language is known as "brain-flak classic".

You must write a program or function that takes a string of Brain-Flak classic code, and evaluates it. It will also take a (possible empty) list of integers. There are the inputs to the Brain-Flak classic program.

# The Language

Brain-Flak has two stacks, known as 'left' and 'right'. The active stack starts at left. If an empty stack is popped or peeked, it will return 0. There are no variables. When the program starts, each input is pushed on to the active stack in order (so that the last input is on top of the stack).

The only valid characters in a Brain-Flak program are `()[]{}<>`, and they must always be balanced. If there are invalid characters, or the brackets are unmatched, you get undefined behaviour. Anything is valid.

There are two types of functions: *Nilads* and *Monads*. A *nilad* is a function that takes 0 arguments. Here are all of the nilads:

* `()` +1.
* `[]` -1.
* `{}` Pop the active stack.
* `<>` Toggle the active stack.

These are concatenated together when they are evaluated. So if we had a '3' on top of the active stack, this snippet:

```
()(){}

```

would evaluate to `1 + 1 + active.pop()` which would evaluate to 5. `<>` evaluates to 0.

The monads take one argument, a chunk of Brain-Flak code. Here are all of the monads:

* `(n)` Push 'n' on the active stack.
* `[n]` Print 'n' as an int and a newline.
* `{foo}` While active.peek() != 0, do foo. Evaluates to 0¹.
* `<foo>` Execute foo, but evaluate it as 0.

These functions will also return the value inside of them, so

```
(()()())

```

Will push 3 and

```
[()()()]

```

Will print 3 but

```
[(()()())]

```

Will print **and** push 3.

When the program is done executing, each value left on the active stack is printed as an integer, with a newline between. Values on the other stack are ignored.

# Rules:

* Your program must support numbers in the (-128, 127) range, and a stack size of at least 255. If you support larger, great.
* Underflow/overflow is undefined.

# Sample IO:

The empty program:

Input: None

Output: None

Addition. Source:

```
({}{})

```

Input:

```
2, 3

```

Output:

```
5

```

Subtraction. Source:

```
({}<>){({}[])<>({}[])<>}<>

```

Input:

```
2, 3

```

Output:

```
-1

```

Multiplication. Source:

```
({}<>)<>({}[]){({}[])<>(({}))<>}<>{({}<>{})<>}<>

```

Input:

```
7, 8

```

Output:

```
56

```

Fibonacci. Source:

```
<>((()))<>{({}[])<>({}<>)<>(({})<>({}<>))<>}<>

```

Input:

```
5

```

Output:

```
13
8
5
3
2
1
1

```

Truth machine

```
{[({})]}

```

Standard loopholes apply, and the shortest answer in bytes wins.

---

* ¹: *This was actually a mistake on my part.* `{...}` *should evaluate to the sum of all of it's runs, which is IMO one of the coolest features of brain-flak. However, for the purposes of this challenge, assume that* `{...}` *evaluates as 0.*

# Answer
> 7 votes
# Pip `-n`, ~~151~~ ~~148~~ ~~101~~ 98 bytes

```
YRVg;VqR^"{}()<>[]";,8R J,8<>2AL,8("POy|i o0Syl1v0W@y{ }1yPU$+[ ]&@y0 1P$+[ ]"R0" (V{"R1"i}) "^s)y

```

Takes the list of inputs as command-line arguments and the Brain-Flak code from (a line of) stdin. Try it online!

*Edit:* Saved a whole lot of bytes over my original approach by switching to a translate-and-eval strategy.

### Ungolfed and commented

This version also includes some debug output showing the Pip code that results from the translation, as well as the stack contents after execution.

```
;;; Setup ;;;

; y is the active stack, l is the off-stack
; y is initialized from command-line arguments
y:RVg   (reversed to put the last input at the top)
; l is preset to empty list by default

; p is the program (read from stdin)
p:q

; Translate from braces to numbers 0-7 (we do this so that the
; later replacement step won't try to replace the braces in the
; Pip code)
p R: ^"()[]{}<>" 0,8

;;; Replace nilads with the appropriate code ;;;

; () => o (variable preset to 1)
p R: 01 "o"

; [] => v (variable preset to -1)
p R: 23 "v"

; {} => POy|i
; Pop y; return that value OR i (variable preset to 0)
p R: 45 "POy|i"

; <> => (V{Syli})
; Eval the code Syl to swap stacks y and l, then return i (i.e. 0)
p R: 67 "(V{Syli})"

;;; Replace monads with the appropriate code ;;;

; ( ) => yPU$+[ ]&@y
; Sum ($+) the inside and push (PU) the sum onto y; return
; the just-pushed value, which is the first element of y (@y)
; y will always be truthy (nonempty), since we just pushed a value onto it
p R: 0 "yPU$+["
p R: 1 "]&@y"

; [ ] => P$+[ ]
; Sum ($+) the inside, print (P) the sum, and return it
p R: 2 "P$+["
p R: 3 "]"

; { } => (V{W@y{ }i})
; Eval the code W@y{ }, which wraps the inside in curly braces
; and runs it while (W) the first element of y (@y) is truthy
; (i.e. not zero, and not nil from an empty stack)
; Then return i (i.e. 0)
p R: 4 "(V{W@y{"
p R: 5 "}i})"

; < > => (V{ i})
; Eval the inside, then return i (i.e. 0)
p R: 6 "(V{"
p R: 7 "i})"

; Debug: print the resulting translated code and a blank line
Pp.n

;;; Run the code ;;;

; Eval the translated code
(Vp)

; Output the active stack, newline-separated
PyJn

; Debug: print the active stack and the off-stack
P"Active stack: ".RPy
"Off-stack: ".RPl

```

# Answer
> 66 votes
# Brain-Flak Classic, ~~1271~~ ~~1247~~ 1239 bytes

```
<>(()){<>((([][][][][])<(((({}){})(({})({}))[])({}(({})({}({})({}{}(<>)))))[])>{()<{}>}{})<{{}}{}>())}{}<>(<(({()(((<>))<>)}{}{<({}(([][][])((({})({}))[]{})){})>((){[]<({}{})((){[]<({}{}<>((({})({})){}{}){})(<>)>}{}){{}{}<>(<({}{}())>)(<>)}>}{}){(<{}{}{}((<>))<>>)}{}}<>)<{({}[]<({}<>)<>{(<{}>)<>{<>({}[])}{}<>({}<>)(<>)}{}>)}{}<>>)>)<>{(({}[])(){(<{}>)<><(({})[])>[][][][]{()()()()(<{}>)}{}<>}{}<>)<>}<>{}{(({})<({()<<>({}<>)>}{})>([]))((){[](<(({}()()(<>))()()()){(<{}>)<>}>)}{}<>){{}((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[](<{}<>{({}<>)<>}{}(({}))({<{}({}<>)<>>{}(<<>({}[]<>)>)}<><{({}<>)<>}>{})>)}{}){{}{}(<([])>)}>}{}){{}<>{({}<>)<>}{}((({})())<{({}[]<({}<>)<>>)}>{}){({}[]<><({}<><({()<({}[]<({}<>)<>>)>}{}<>)><>)<>({()<({}[]<({}<>)<>>)>}{}<>)>)}<>(<{({}<>)<>}>)}>}{}){{}{}(<(())>)}>}{}){(<{}{}>)<>{({}<>)<>}{}(({}))({<{}({}<>)<>>({})(<<>({}<>)>)}<><{({}<>)<>}>){{}([][][])<>(((<{}>)<>))}}>}{}){{}(<([{}])>)}>}{}){{}((<{}>))}>}{}){{}(({})(<()>)<<>{({}<>)<>}{}({}()<>)<>>)<>(<({}<>)>)<>{({}<>)<>}}{}(<({}<({}<>)<>>{})<>({}<>)>)<>(<({}())>)}{}({}<{({}[]<({}<>)<>>)}{}>){((({}[]<>){(<{}({}<>)>)}{}())<{({}()<({}<>)<>(({})[])>{[][](<{}>)}{})}{}>()){{}(<>)}}{}}{}{({}[]<[{}]>)}{}{({}[]<{}>)}{}

```

Try it online!

*+4 bytes from fixing a bug with the condition in the `{...}` monad, and -36 bytes from various golfs.*

1238 bytes of code, +1 byte for the `-a` flag (which can be combined with the language flag).

This now evaluates `{...}` as zero per the challenge specification. Note that Brain-Flak itself has evaluated `{...}` as the sum of all runs since the May 7, 2016 bugfix two days before this challenge was posted.

The following code interprets Brain-Flak Classic correctly, with `{...}` as the sum of all runs. The only difference between the two interpreters is the placement of one `{}` nilad.

```
<>(()){<>((([][][][][])<(((({}){})(({})({}))[])({}(({})({}({})({}{}(<>)))))[])>{()<{}>}{})<{{}}{}>())}{}<>(<(({()(((<>))<>)}{}{<({}(([][][])((({})({}))[]{})){})>((){[]<({}{})((){[]<({}{}<>((({})({})){}{}){})(<>)>}{}){{}{}<>(<({}{}())>)(<>)}>}{}){(<{}{}{}((<>))<>>)}{}}<>)<{({}[]<({}<>)<>{(<{}>)<>{<>({}[])}{}<>({}<>)(<>)}{}>)}{}<>>)>)<>{(({}[])(){(<{}>)<><(({})[])>[][][][]{()()()()(<{}>)}{}<>}{}<>)<>}<>{}{(({})<({()<<>({}<>)>}{})>([]))((){[](<(({}()()(<>))()()()){(<{}>)<>}>)}{}<>){{}((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[]<({}())((){[](<{}<>{({}<>)<>}{}(({}))({<{}({}<>)<>>{}(<<>({}[]<>)>)}<><{({}<>)<>}>{})>)}{}){{}{}(<([])>)}>}{}){{}<>{({}<>)<>}{}((({})())<{({}[]<({}<>)<>>)}>{}){({}[]<><({}<><({()<({}[]<({}<>)<>>)>}{}<>)><>)<>({()<({}[]<({}<>)<>>)>}{}<>)>)}<>(<{({}<>)<>}>)}>}{}){{}{}(<(())>)}>}{}){(<{}>)<>{({}<>)<>}{}(({}))({<{}({}<>)<>>({})(<<>({}<>)>)}<><{({}<>)<>}>{}){{}([][][])<>(((<{}>)<>))}}>}{}){{}(<([{}])>)}>}{}){{}((<{}>))}>}{}){{}(({})(<()>)<<>{({}<>)<>}{}({}()<>)<>>)<>(<({}<>)>)<>{({}<>)<>}}{}(<({}<({}<>)<>>{})<>({}<>)>)<>(<({}())>)}{}({}<{({}[]<({}<>)<>>)}{}>){((({}[]<>){(<{}({}<>)>)}{}())<{({}()<({}<>)<>(({})[])>{[][](<{}>)}{})}{}>()){{}(<>)}}{}}{}{({}[]<[{}]>)}{}{({}[]<{}>)}{}

```

Try it online!

Input (to either interpreter) is the Brain-Flak Classic program to interpret, then a newline, then a space-separated list of integers. No validation is performed on the input. The newline is required, even if the program or input is blank.

The first step is to parse all of the input, starting with the brackets:

```
# Move to right stack, and push 1 to allow loop to start
<>(())
{
   # While keeping -5 on third stack:
   <>((([][][][][])<

       # Pop bracket or newline k from left stack, and push 0, k-10, k-40, k-60, k-91, k-123 on right stack
       (((({}){})(({})({}))[])({}(({})({}({})({}{}(<>)))))[])

   # Search this list for a zero, and push the number of nonzero entries popped minus 5
   # (thus replacing the 0 if it was destroyed)
   >{()<{}>}{})

   # Remove rest of list, and push the same number plus 1
   # Result is -4 for {, -3 for [, -2 for <, -1 for (, 0 for newline, or 1 for everything else (assumed closing bracket)
   <{{}}{}>())

# Repeat until newline found
}{}<>

```

Then the integers are parsed. This wouldn't normally be required, but the input was taken as ASCII. This does have a silver lining, though: text input allows us to determine the stack height, which simplifies things when we don't have access to the stack height nilad.

Integers are parsed into two numbers on the second stack: one for the absolute value, and one for the sign. These are then moved back to the first stack.

The interpreted stacks are stored below the code on the first stack in the following order: current stack height, current stack, other stack height, other stack. The 0 for the other stack height does not need to be pushed at this point, since it will be an implicit zero the first time it is read.

```
(<((

    # If stack nonempty, register first stack entry.
    {()(((<>))<>)}{}

    # For each byte k of input:
    {

        # Push -3, -13, and k-32
        <({}(([][][])((({})({}))[]{})){})>

        # Evaluate to 1 if space
        # If not space (32):
        ((){[]<

            # If not minus (45):
            ({}{})((){[]<

                # Replace top of right stack (n) with 10*n + (k-48)
                ({}{}<>((({})({})){}{}){})(<>)

            # Else (i.e., if minus):
            >}{}){

                # Remove excess "else" entry and -3
                {}{}

                # Set sign to negative (and destroy magnitude that shouldn't even be there yet)
                <>(<({}{}())>)(<>)}

        # Else (i.e., if space):
        >}{}){

            # Remove working data for byte, and push two more 0s onto right stack
            (<{}{}{}((<>))<>>)

    # Push number of integers found
    }{}}<>)

    # For each integer:
    <{({}[]<

        # Move magnitude back to left stack
        ({}<>)<>

        # If sign is negative, negate
        {(<{}>)<>{<>({}[])}{}<>({}<>)(<>)}{}

    >)}{}

    # Push stack height onto stack
    <>>)

# Push 0
>)

```

The representation of the code is now moved back to the left stack. To make things easier later, we subtract 4 from the opening brackets of nilads, so that each operation has a unique integer from -1 to -8.

```
# For each bracket in the code:
<>{

    # Push k-1 and evaluate to k
    (({}[])()

    # If not closing bracket:
    {

        # Check next bracket (previously checked, since we started at the end here)
        (<{}>)<><(({})[])>

        # Subtract 4 if next bracket is closing bracket
        # Inverting this condition would save 8 bytes here, but cost 12 bytes later.
        [][][][]{()()()()(<{}>)}{}

    <>}{}

    # Push result onto left stack
    <>)

<>}<>{}

```

The main part of the program is actually interpreting the instructions. At the start of each iteration of the main loop, the current instruction is at the top of the left stack, everything after it is below it on the same stack, and everything before it is on the right stack. I tend to visualize this as having a book open to a certain page.

```
{

    (

        # Get current instruction
        ({})

        # Move all code to left stack, and track the current position in code
        <({()<<>({}<>)>}{})>

        # Push -1, signifying that the code will move forward to just before a matching }.
        # In most cases, this will become 0 (do nothing special) before it is acted upon
        ([])

    # Push instruction minus 1
    )

    # If opening bracket:
    ((){[](<

        # Push instruction+1 and instruction+4
        (({}()()(<>))()()())

        # If instruction+4 is nonzero (not loop monad), replace the earlier -1 with 0 to cancel forward seek
        # This would be clearer as {(<{}>)<>(<{}>)<>}, but that would be unnecessarily verbose
        {(<{}>)<>}

    # Else (i.e., if closing bracket):
    >)}{}<>){

# If closing bracket, parse command
# Post-condition for all: if not moving to {, pop two and push evaluation, 0.
# (For nilads, can assume second from top is 0.)
# If moving to {, pop one, push -3, 0, 0.

        # Seven nested if/else statements, corresponding to eight possible instruction.
        # The "else" statements end with 0 already on the stack, so no need to push a 0 except in the innermost if.
        # Each one beyond the first increments the instruction by 1 to compare the result with 0
        # Each instruction will pop the instruction, leaving only its evaluation (with a 0 on top).
        {}((){[]<
        ({}())((){[]<
        ({}())((){[]<
        ({}())((){[]<
        ({}())((){[]<
        ({}())((){[]<
        ({}())((){[](<

            # -7: pop
            # Pop instruction to reveal existing 0 evaluation
            {}

            # Move code out of the way to access stack
            <>{({}<>)<>}{}

            # Duplicate stack height (only useful if stack height is zero)
            (({}))

            (

                # If stack height nonzero
                {

                    # Save stack height on second stack
                    <{}({}<>)<>>

                    # Pop stack
                    {}

                    # Move stack height back and subtract 1
                    (<<>({}[]<>)>)

                }

                # Move code back to normal position
                <><{({}<>)<>}>{}

            # Evaluate as popped entry (0 if nothing popped)
            )

        # (else)
        >)}{}){

            # -6: -1 nilad
            # Just evaluate as -1
            {}{}(<([])>)

        # (else)
        }>}{}){

            # -5: swap nilad
            # Move code out of the way to access stack
            {}<>{({}<>)<>}{}

            # Number of integers to move: stack height + 1 (namely, the stack height and every entry in the stack)
            ((({})())

            # Move to second stack
            <{({}[]<({}<>)<>>)}>{}

            # Do (stack height + 1) times again
            ){({}[]<><

                # Get stack element
                ({}<><

                    # Move alternate (interpreted) stack to second (real) stack, and push length on top of it
                    ({()<({}[]<({}<>)<>>)>}{}<>)

                # Push current stack element below alternate stack
                ><>)

                # Move alternate stack back above newly pushed element
                <>({()<({}[]<({}<>)<>>)>}{}<>)

            >)}

            # Move code back to normal position
            <>(<{({}<>)<>}>)

        # (else)
        }>}{}){

            # -4: 1
            # Just evaluate to 1
            {}{}(<(())>)

        # (else)
        }>}{}){

            # -3: loop
            # Create zero on stack while keeping existing evaluation
            # This becomes (<{}{}>) in the version that meets the challenge spec
            (<{}>)

            # Move code out of the way to access stack
            <>{({}<>)<>}{}

            # Duplicate stack height
            (({}))

            (

                # If stack height nonzero
                {

                    # Save stack height on second stack
                    <{}({}<>)<>>

                    # Peek at top of stack
                    ({})

                    # Move stack height back
                    (<<>({}<>)>)

                }

                # Move code back to normal position
                <><{({}<>)<>}>

            # Look at peeked entry
            # Remove the {} in the version meeting the challenge spec
            {})

            # If peeked entry is nonzero
            {

                # Replace -3 instruction on third stack
                {}([][][])

                # Replace loop indicator to 0 (to be incremented later to 1)
                <>(((<{}>)

                # Create dummy third stack entry to pop
                <>))

            }

        # (else)
        }>}{}){

            # -2: print
            # Just print evaluation without modifying it
            {}(<([{}])>)

        # (else)
        }>}{}){

            # -1: evaluate as zero
            # Just change evaluation to 0
            {}((<{}>))

        # else
        }>}{}){

            # 0: push
            # Get current evaluation (without modifying it)
            {}(({})

                # Create zero on stack as barrier
                (<()>)

                # Move code out of the way to access stack
                <<>{({}<>)<>}{}

                # Increment stack height and save on other stack
                ({}()<>)<>

            # Push evaluation
            >)

            # Move stack height back (and push zero)
            <>(<({}<>)>)

            # Move code back to normal position
            <>{({}<>)<>}

        }{}

        # Update third stack by adding evaluation to previous entry's evaluation
        # Previous entry's instruction is saved temporarily on left stack
        (<({}<({}<>)<>>{})<>({}<>)>)

        # Increment loop indicator
        # If instruction was loop monad and top of stack was nonzero, this increments 0 to 1 (search backward)
        # Otherwise, this increments -1 to 0 (do nothing)
        <>(<({}())>)

    }{}

    # While holding onto loop indicator
    ({}<

        # Go to immediately after executed symbol
        {({}[]<({}<>)<>>)}{}

    >)

    # If looping behavior:
    {

        # Switch stack and check if searching forward
        ((({}[]<>)

        # If so:
        {

            # Move just-executed { back to left stack, and move with it
            (<{}({}<>)>)

        }{}

        # Either way, we are currently looking at the just-executed bracket.
        # In addition, the position we wish to move to is on the current stack.

        # Push unmodified loop indicator as initial value in search
        ())

        # While value is nonzero:
        <{

            # Add 1
            ({}()

                # Move current instruction to other stack
                <({}<>)<>

                # Check whether next instruction is closing bracket
                (({})[])>

                # If opening bracket, subtract 2 from value
                {[][](<{}>)}{}

            )

        }{}>

        # If searching backward, move back to left stack
        ()){{}(<>)}

    }{}

}

```

After exiting the main loop, all of the code is on the right stack. The only things on the left stack are a zero and the two interpreted stacks. Producing the correct output is a simple matter.

```
# Pop the zero
{}

# Output current stack
{({}[]<[{}]>)}{}

# Discard other stack to avoid implicit printing
{({}[]<{}>)}{}

```

# Answer
> 8 votes
# APL, ~~255~~ 257 bytes

```
b←{S←(⌽⍺)⍬
e←{0=⍴⍵:0
v+∇⊃_ v←∇{r←⊂2↓⍵
'()'≡n←2↑⍵:r,1
'[]'≡n:r,¯1
'{}'≡n:r,{i←⊃⊃⊃S⋄S[1]↓⍨←1⋄i}⍬
'<>'≡n:r,0⊣S⌽⍨←1
r←⊂⍵↓⍨i←0⍳⍨(+\c=⍵)-+\')]>}'['([<{'⍳c←⊃⍵]=⍵
i←1↓¯1↓c←i↑⍵
'('=c←⊃c:r,S[1],⍨←⍺⍺i
'['=c:r,+⎕←⍺⍺i
'{'=c:r,{0≠⊃⊃⊃S:∇e i⋄0}⍬
'<'=c:r,0⊣⍺⍺i}⍵}
⎕←⍪⊃S⊣e⍵}

```

This takes the program as its right argument, and the program input as its left argument, i.e:

```
      2 3 b '({}{})'
5
      2 3 b '({}<>){({}[])<>({}[])<>}<>'
¯1
      7 8 b '({}<>)<>({}[]){({}[])<>(({}))<>}<>{({}<>{})<>}<>'
56
      5 b '<>((()))<>{({}[])<>({}<>)<>(({})<>({}<>))<>}<>'
13
 8
 5
 3
 2
 1
 1

```

Ungolfed version: here.

# Answer
> 8 votes
# APL (Dyalog Classic), 146 bytes

```
↑⍕¨s⊣{⍎⍕1 ¯1'(s↓⍨←1)⊢⊃s' '0⊣s t←t s' 's,⍨←+/∇¨a' '⎕←+/∇¨a' '∇{×⊃s:∇⍺⍺¨a⋄0}0' '0⊣+/∇¨a'[(⊃⍵)+4×⍬≢a←1↓⍵]}¨⍎∊(')',⍨'(',¨⍕¨⍳4)[0,4,⍨'([{<'⍳⍞]⊣s←⌽⎕⊣t←⍬

```

Try it online!

one Classic interpreting another :)

# Answer
> 6 votes
# Python 3, 429 bytes

```
import re
S='s+=[v];v=0';T='v+=s.pop()';i=0
d={'()':'v+=1','(':S,')':'a+=[v];'+T,'[]':'v-=1','[':S,']':'print(v);'+T,'<>':'a.reverse()','<':S,'>':T,'{}':'v+=0if a[-1]==""else a.pop()','{':S+';while a[-1]:','}':T}
def r(m):global i;t=m.group();i-=(t=='}');s=' '*i;i+=(t=='{');return''.join(s+r+'\n'for r in d[t].split(';'))
def g(c,*a):
 a,s,v=['']+list(a),[],0;exec(re.sub(r'[<({[]?[]})>]?',r,c));
 while a[-1]!="":print(a.pop())

```

Used like `g('[{}{}]', 2, 3)`

It uses `re.sub` to "compile" the brain-flak source to python and then executes the python. (for debuging, replace `exec` with `print` to get a listing of the python code)

Properly indenting nested while loops eats up a lot of bytes in the code.

# Answer
> 3 votes
## Perl 5.6, ~~419~~ 414 bytes

I've golfed it a bit but there's probably scope for improvement. Newlines and tabs added here for the sake of a bit of readability:

```
use Text::Balanced extract_bracketed;
$s=shift;
@a=reverse@ARGV;
sub p
{
    my($c)=@_;
    my$s=0;
    while(my$n=extract_bracketed($c)){
        $s+='()'eq$n||'{}'eq$n&&shift@a;
        $s-='[]'eq$n;
        @t=@a,@a=@i,@i=@t if'<>'eq$n;
        my$m=chop($n);
        $n=substr($n,1);
        if($n){
            p($n)while'}'eq$m&&$a[0];
            p($n)if'}'ne$m;
            $s+=$v,unshift@a,$v if')'eq$m;
            $s+=$v,print"n=$n m=$m v=$v\n"if']'eq$m;
        }
    }
    $v=$s;
}
p($s);
foreach(@a){
    print"$_\n";
}

```

# Answer
> 3 votes
# Python, 616 bytes

Instructions:

1. Run with python
2. Input list in `[1,2,...]` format, then press enter
3. Paste/write program, then press enter again
4. Done

Basically, what this program does is recursively "compile" the Brain-flak code into nested lists, and recursively interpret that list. There probably is a way to combine the two...

I'll try and rework the logic later.

```
y="([{<)]}>"
w,z,g=print,len,input
def c(s):
 if z(s)<1:return[]
 t,i,o=[],1,0
 t.append(y.index(s[0]))
 while z(t)>0:
  x=y.index(s[i])
  if x<4:t.append(x)
  else:o=t.pop()
  i+=1
 r=[[o,c(s[1:i-1])]]
 r.extend(c(s[i:]))
 return r
p=lambda t:t.pop()if z(t)>0 else 0
k=lambda t:t[z(t)-1]if z(t)>0 else 0
r,l=[],eval(g())
a=l
def i(u):
 v=0
 global a
 for t,n in u:
  if t<1:
   if n:o=i(n);v+=o;a.append(o)
   else:v+=1
  if t==1:
   if n:o=i(n);v+=o;w(o)
   else:v-=1
  if t==2:
   if n:
    while k(a)!=0:i(n)
   else:v+=p(a)
  if t>2:
   if n:i(n)
   elif a==l:a=r
   else:a=l
 return v
i(c(g()))
for n in a:w(n)

```

# Answer
> 1 votes
# Python 2, ~~361~~, 348 bytes

```
c,s=input();s=s,[]
a=s[0]
def w():global a,s;s=s[::-1];a=s[0];return 0
def p(c):a.append(c);return c
def n(c):print c;return c
z=lambda c:0
def l(f):
 global a
 while a and a[-1]:f()
 return 0
for x,y in zip("() ( [] {} <> [ < { } ] >".split(),"+1 +p( -1 +(len(a)and(a.pop())) +w() +n( +z( +l(lambda: ) ) )".split()):c=c.replace(x,y)
exec c
print a

```

Try it online!

-13 bytes saved thanks to @Mr. Xcoder!

# Answer
> 0 votes
# Python 3, 290 bytes

```
def f(s,*a):
 for t in '],) },) >,) [,+3 (,+2 2),1 3),-1 {),+(lAorA).pop() <),<l.reverse()) 2,LlA.appendK 3,LprintK {,+cL <,+L0)( L,(lambda*n: K,(*n)or+nA)( A,[0]'.split():s=s.replace(*t.split(','))
 l=[[*a],[]];c=lambda g:[0,*l[0]][-1]and g()+c(g);exec(s,locals());[*map(print,l[0][::-1])]

```

Try it online!

---
Tags: code-golf, interpreter, balanced-string, stack, brain-flak
---


title: Build a chessboard

text:
# Question
Title: Build a chessboard
Saw this in a PHP challenge. The objective is to make a chessboard with 64 squares (8\*8) with the minimum amount of code. Simple enough, I made mine in PHP in 356 bytes (not impressive, I know) and I would like to see some other aproaches. This can be made in a language of your choice, as long as you keep it vanilla, so no imports. Smallest byte count wins.

The output should look like this:

And my code:

```
<table><?php
$c='black';function p($c,$n){echo'<td style="width:50px;height:50px;background:'.$c.'"></td>';if($n==1){echo"<tr>";}}for($i=1;$i<=64;$i++){if($i%8==0&&$c=="black"){$c="white";$n=1;}elseif($i%8==0&&$c=="white"){$c="black";$n=1;}elseif(isset($n)&&$n==1){$n=0;}elseif($c=="black"){$n=0;$c="white";}elseif($c=="white"){$n=0;$c="black";}p($c,$n);}

```

Or readable:

```
<table><tr>
<?php
$color = 'black';
function printcolor($color, $nl) {

    echo '<td style="width:50px; height:50px; background:' . $color . '"></td>';
    if ($nl == true) {
        echo "</tr><tr>";
    }
}
for ($i=1; $i<=64;$i++) {
    if ($i % 8 == 0 && $color == "black") {
        $color = "white";
        $nl = true;
    } elseif ($i % 8 == 0 && $color == "white") {
        $color = "black";
        $nl = true;
    } elseif (isset($nl) && $nl == true) {
        $nl = false;
    } elseif ($color == "black") {
        $nl = false;
        $color = "white";
        }
    elseif ($color == "white")  {
        $nl = false;
        $color = "black";
    }
    printcolor($color, $nl);
}

```

**Edit:**

Sorry I wasn't very specific at first:

* Squares should have 50px * 50px except for vectorial images.
* Output format or size is not relevant nor it needs to be an image.
* For evaluation purposes the output must be visible such as in an image file or a screenshot
* No libraries written after the challenge was posted

# Answer
> 14 votes
# Octave, ~~20~~ 18 bytes

Thanks to @Bruno for shaving off 2 bytes.

```
imshow(invhilb(8))

```

Result:

This answer uses a technique found here. It also relies on the automatic scaling of images in Octave depending on the size of the figure window.

# Answer
> 27 votes
## vim, ~~47~~ ~~46~~ ~~44~~ 43

crossed out 44 is still regular 44...

```
iP1 400 <C-p><cr><esc>50i1<esc>YpVr0yk3PyG49PyG:m$<cr>p2GyG3P

```

```
i          enter insert mode
P1         signal to NetPPM that we're using black&white (PBM) format
400        width
<C-p>      fancy trick that inserts the other 400 for height
<cr><esc>  exit insert mode on the next line
50i1<esc>  insert 50 '1's (black)
YpVr0      insert 50 '0's (white) by duplicating the line and replacing all chars
yk         copy both lines (yank-up)
3P         paste three times; this leaves us on line two
yG         copy from line 2 to end of file (this is a full row of pixels now)
49P        we need 50 rows of pixels to make a complete "row"; paste 49 times
yG         copy the entire row of the checkerboard
:m$<cr>    move line 2 (the line we're currently on) to the end of the file
           this gives us the "alternating rows" effect
p          we're now on the last line: paste the entire row we copied earlier
2G         hop back to line 2 (beginning of image data)
yG3P       copy the entire image data, paste 3 times

```

Outputs in NetPPM format (PBM):

# Answer
> 18 votes
## CSS, 244 bytes

```
html{background:#fff}body{width:400px;height:400px;background:linear-gradient(45deg,#000 25%,transparent 25%,transparent 75%,#000 75%)0 0/100px 100px,linear-gradient(45deg,#000 25%,transparent 25%,transparent 75%,#000 75%)50px 50px/100px 100px}

```

```
html {
    background: white;
}
body {
    width: 400px;
    height: 400px;
    background:
        linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%) 0px 0px / 100px 100px,
        linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%) 50px 50px / 100px 100px
}
```

Explanation: A 100x100px diagonal linear gradient is created with four stops so that most of the gradient is transparent except for two 50px triangular corners. (See below snippet). Adding a second gradient with a 50x50px offset fills in the missing halves of the squares. Increasing the size of the body then allows the resulting pattern to repeat to fill the entire chessboard.

```
html {
    background: white;
}
body {
    width: 100px;
    height: 100px;
    background: linear-gradient(45deg, black 25%, transparent 25%, transparent 75%, black 75%) 0px 0px / 100px 100px
}
```

# Answer
> 17 votes
## Mathematica, 34 bytes

```
ArrayPlot@Array[Mod[+##,2]&,{8,8}]

```

The output is a vector image and is surrounded in a frame.

Instead of correctly positioning 32 rectangles, we can just generate a binary matrix and make `ArrayPlot` work for us:

# Answer
> 10 votes
# Mathematica, ~~81~~ ~~72~~ 55 bytes

```
Graphics[Rectangle/@Select[Range@8~Tuples~2,2∣Tr@#&]]

```

Image is of a previous version's evaluation, but still looks the same.

# Answer
> 9 votes
# Pure Bash (no external utilities), 133

I saw @Doorknob's comment as a bit of a challenge. Its a bit long, but here goes:

```
echo \# ImageMagick pixel enumeration:400,400,1,rgb
for((;x=p%400,y=p/400,c=1-(x/50^y/50)&1,p++<160000;));{
echo "$x,$y:($c,$c,$c)"
}

```

Output is in Imagemagick's .txt format. Note this is pure Bash. Neither Imagemagick nor any other external utilities are spawned to generate this output. However, the output may be redirected to a .txt file and viewed with the ImageMagick `display` utility:

This image format is nice because not only is it pure text, it is little more than a list of all pixels (x, y and colour value), one per line. It is a fairly simple matter to derive all pixel values arithmetically in one big loop.

---

# Previous answer, 167

```
echo "\"400 400 2 1\"
\"  c white\"
\"b c black\""
printf -vf %50s
a="$f${f// /b}"
o=("\"$a$a$a$a\"" "\"${f// /b}$a$a$a$f\"")
for i in {0..399};{
echo "${o[i/50%2]}"
}

```

Output is in the X\_PixMap text image file format, which may also be viewed with the ImageMagick `display` utility.

Note I've taken as much out of the XPM format as I could such that `display` would still accept it. I was able to take out all the boilerplate with the exception of the `"` double quotes around each line. No idea what other - if any - utilities will accept this.

# Answer
> 7 votes
## PowerShell + browser of your choice, ~~149~~ 143 bytes

The inability to use imports is really tough, as all of the GDI calls (i.e., the stuff PowerShell uses to draw) are buried behind imports in .NET ...

```
"<table><tr>"+((1..8|%{$a=$_;-join(1..8|%{'<td style="width:50px;height:50px'+("",";background:#000")[($a+$_)%2]+'"></td>'})})-join'</tr><tr>')

```

Edit - saved six bytes thanks to @NotThatCharles

This uses two for-loops from `1..8` to generate a big-ol' HTML string, similar to the PHP example provided, and output it onto the pipeline. Each time through we calculate whether to append `;background:#000` for the black backgrounds by taking our current position on the board modulo 2.

To use, redirect the output into the file of your choice (e.g., with something like `> chessboard.htm`) and then launch that in the browser of your choice. For the screenshot below, I used "c.htm" and Firefox.

# Answer
> 7 votes
# Octave, 48 bytes

```
imwrite(kron(mod((t=0:7)+t',2),ones(50)),'.png')

```

This works exactly the same as my Matlab answer, but there is no `spiral` in Octave. Instead we use a feature that Matlab does not have: We can use the assignment of `t` already as an expression, and later use `t` again in the same expression.

(This is the rescaled version, I do not want to clutter the answers here=)

# Answer
> 6 votes
# Python 3, ~~365~~, ~~288~~, ~~270~~, 256 bytes

Thanks @Razetime, @mehbark and @Amazeryogo for the suggestions

```
from turtle import *
B=range
H=Screen()
A=Turtle()
def F():
    for C in B(4):A.fd(30);A.lt(90)
    A.fd(30)
for D in B(8):
    A.up();A.setpos(0,30*D);A.pd()
    for G in B(8):
        if(D+G)%2==0:E='black'
        else:E='white'
        A.fillcolor(E);A.begin_fill();F();A.end_fill()

```

Try it online!

Admittedly not good:) first contribution

# Answer
> 5 votes
# MATL, 11 (27) bytes

```
8:t!+Q2\TYG

```

This produces the following figure. It doesn't have an intrinsic size; it's automatically scaled depending on the size of the figure window. This seems to be allowed by the challenge.

### Explanation

```
8:      % row vector [1,2,...8]
t!      % duplicate and transpose into column vector
+       % 8x8 matrix with all pairwise additions
Q       % add 1
2\      % modulo 2. Gives 8x8 matrix of zeros and ones
TYG     % draw image

```

---

If autoscaling is not allowed:

```
'imshow'8:t!+Q2\50t3$Y"0#X$

```

produces the following figure with 50x50-pixel squares

### Explanation

```
'imshow'   % name of Matlab function
8:t!+Q2\   % same as above. Produces 8x8 matrix of zeros and ones
50t3$Y"    % repeat each element 50 times in each dimension
0#X$       % call imshow function with above matrix as input

```

# Answer
> 5 votes
# Pyth, ~~28~~ 26 bytes

```
J*4+*50]255*50]0.wm_mxkdJJ

```

Explanation

```
J                          - Autoassign J = V
           *50]0           - 50*[0]
    *50]255                - 50*[255]
   +                       - ^^+^
 *4                        - 4*^
                .w         - write_greyscale(V)
                  m      J - [V for d in J]
                   _       - reversed(V)
                    m   J  - [V for k in J]
                     xkd   - k^d

```

Python equivalent

```
J = 4*(50*[255]+50*[0])
write_greyscale([[k^d for k in J][::-1] for d in J])

```

Try it here (just the colour values)

Output:

# Answer
> 5 votes
# PHP + CSS + HTML, 136 bytes

Taking the table aproach to a higher level:

```
<table><?for(;++$i<9;)echo'<tr>',str_repeat(["<td b><td>","<td><td b>"][$i&1],4);?><style>td{width:50px;height:50px}[b]{background:#000}

```

It generates the following code:

```
<table><tr><td><td b><td><td b><td><td b><td><td b><tr><td b><td><td b><td><td b><td><td b><td><tr><td><td b><td><td b><td><td b><td><td b><tr><td b><td><td b><td><td b><td><td b><td><tr><td><td b><td><td b><td><td b><td><td b><tr><td b><td><td b><td><td b><td><td b><td><tr><td><td b><td><td b><td><td b><td><td b><tr><td b><td><td b><td><td b><td><td b><td><style>td{width:50px;height:50px}[b]{background:#000}
```

It relies heavily on browsers' kindness and CSS.

# Answer
> 5 votes
# Jelly, 26 bytes

```
400R%2ẋ€50FU;$ẋ4;;;1j⁶;”PU

```

Since Jelly has no support for images built in, we print a PPM image.

Try it online! (smaller board for speed, raw PPM)

### Results

### How it works

```
400R%2ẋ€50FU;$ẋ4;;;1j⁶;”PU  Main link. No arguments.

400                         Set the left argument to 400.
   R                        Yield [1, ..., 400].
    %2                      Compute the parity of each integer.
      ẋ€50                  Replace each parity by an array of 50 copies of itself.
          F                 Flatten the resulting, nested list.
                            This creates the first rank of the board.
             $              Combine the two atoms to the left:
           U                  Reverse the array of parities.
            ;                 Concatenate the reversed array with the original.
                            This creates the first two ranks of the board.
              ẋ4            Repeat the resulting list four times.
                            This creates all eight ranks of the board.
                ;           Append 400, the link's left argument.
                 ;          Append 400, the link's left argument.
                  ;1        Append 1.
                    j⁶      Join, separating by spaces.
                      ;”P   Append the character 'P'.
                         U  Reverse the resulting list.

```

### Non-competing version (24 bytes)

The newest Jelly interpreter that predates this post didn't vectorize `x` properly. With the latest version, 2 additional bytes can be saved.

```
400R%2x50U;$ẋ4;;;1j⁶;”PU

```

The only difference is that `x50` yields a flat list (with every original element repeated 50 times), so `F` is no longer necessary.

# Answer
> 5 votes
# FFmpeg, 78 ~~82 100~~ bytes

Finally got around to cleaning the board.

```
ffplay -f lavfi color=s=400x400,geq='255*mod(trunc(X/50)+trunc(Y/50)+1,2):128'

```

---

**Older**:

```
ffmpeg -f lavfi -i "color=tan@0:256x256,format=ya8" -vf "scale=400:-1:alphablend=checkerboard" .jpg

```

Will exit with error, but after producing image below.

(board's collected some dust)

# Answer
> 4 votes
# Matlab, 47 (24) bytes

```
imwrite(kron(mod(spiral(8),2),ones(50)),'.png')

```

This works exactly the same as my Octave answer, but I was able to use `spiral` which saved one byte. `spiral(n)` makes an `nxn` matrix and fills it spiraling with the first `n^2` integers.

If vectorgraphics are allowed, we could do it in 24 bytes:

```
imshow(mod(spiral(8),2))

```

(This is the rescaled version, I do not want to clutter the answers here=)

# Answer
> 4 votes
HTML with utf-8 - 66b

```
<div style="font:100 50px/48px serif">▚▚▚▚<br>▚▚▚▚<br>▚▚▚▚<br>▚▚▚▚
```

▚ is short-direct utf for entity **&# 9626 ;**

Unicode Character 'QUADRANT UPPER LEFT AND LOWER RIGHT' (U+259A)

silly me, was looking for a 1 utf-8 char solution -would have been... 1b!

# Answer
> 4 votes
# APL (Dyalog Extended), ~~51~~ 30 bytes

```
'P1'
2⍴400
50/50⌿(⍳8)⌽8 8⍴'01'

```

Try it online!

Outputs a netpbm image. Save the result to a .pbm file and view here.

Since the output is too large for tio, here's the generated output.

-21 bytes(!) from Adám.

Here's the output converted to png:

Try it online!

# Answer
> 3 votes
# CJam, 27 bytes

```
"P1"400__,2f%50e*_W%+4*~]S*

```

Try it online! (smaller board for speed, raw PPM)

### Results

### How it works

```
"P1"                        e# Push that string.
    400__                   e# Push three copies of 400.
         ,                  e# Turn the last one into [0 ... 399].
          2f%               e# Compute the parity of each integer.
             50e*           e# Repeat each parity 50 times.
                            e# This creates the first rank of the board.
                 _W%        e# Create a reversed copy of the resulting array.
                    +       e# Concatenate the original with the reversed array.
                            e# This creates the first two ranks of the board.
                     4*     e# Repeat the resulting array four times.
                            e# This creates all eight ranks of the board.
                       ~    e# Dump all of its items (the pixels) on the stack.
                        ]   e# Wrap the entire stack in an array.
                         S* e# Join that array, separating them by spaces.

```

# Answer
> 3 votes
# Desmos, 136 bytes

```
ceil(sin(x))\left\{6<x<29\right\}>=ceil(sin(y))\left\{0<y<26\right\}
ceil(sin(x))\left\{3<x<27\right\}<=ceil(sin(y))\left\{0<y<24\right\}

```

This was the first thing I thought of when I saw this challenge, hopefully it's not stretching it too far.

# Answer
> 2 votes
## PHP \>=5.4, ~~175~~ ~~159~~ ~~149~~ 116 Bytes

```
<table><tr><? for(;@++$i<65;)echo'<td width=50 height=50 ',$i+@$m&1?:'bgcolor=0','>',$i%8<1?'<tr '.($m=@!$m).'>':'';

```

```
<table><tr><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><tr 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><tr ><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><tr 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><tr ><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><tr 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><tr ><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><tr 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><td width=50 height=50 bgcolor=0><td width=50 height=50 1><tr >
```

## Notes

* Shaved 16 bytes - Thanks @insertusernamehere
* Shaved 10 bytes - Thanks @msh210
* Shaved 30 bytes - Thanks @Ismael Miguel

# Answer
> 2 votes
## PHP, ~~166~~ ~~158~~ 155 bytes

Works in PHP 7.0.2 (short-tags enabled) and Chrome 48.0.2564.97 m

```
<table><tr><? while(++$i<=8){while(++$j<=8){echo"<td style=background-color:".($i%2==0?($j%2==1?0:""):($j%2==0?0:"")).";padding:9></td>";}echo"<tr>";$j=0;}

```

# Answer
> 2 votes
# iKe, 24 bytes

```
,(;cga;t=\:t:2!-20!!160)

```

The core of the technique is to generate a list of x coordinates, divmod them and then take an equality cross-product to generate an appropriate bitmap. Using smaller examples for illustrative purposes:

```
  !8
0 1 2 3 4 5 6 7

  -2!!8
0 0 1 1 2 2 3 3

  2!-2!!8
0 0 1 1 0 0 1 1

  t=\:t:2!-2!!8
(1 1 0 0 1 1 0 0
 1 1 0 0 1 1 0 0
 0 0 1 1 0 0 1 1
 0 0 1 1 0 0 1 1
 1 1 0 0 1 1 0 0
 1 1 0 0 1 1 0 0
 0 0 1 1 0 0 1 1
 0 0 1 1 0 0 1 1)

```

try it here. Technically iKe works on a logical 160x160 pixel canvas, but in full-screen mode (the default when following a saved link) this is upscaled by 3x. I think this is still following the spirit of the question, as the program could assemble a much larger bitmap with the same character count; it just comes down to an arbitrary display limitation.

## Update:

iKe isn't primarily designed for golf, but livecoding still benefits from brevity and sane defaults. As a result of tinkering with this problem, I've decided to permit it to use a default palette if none is provided. This particular solution could now be expressed with:

```
,(;;t=\:t:2!-20!!160)

```

Saving (an ineligible) 3 bytes.

# Answer
> 2 votes
# Perl 5 - 80

Generates a .PBM file:

```
print 'P1'.' 400'x2 .$".(((0 x50 .1 x50)x4 .$")x50 .((1 x50 .0 x50)x4 .$")x50)x4

```

# Answer
> 2 votes
# GIMP, 539 bytes

```
gimp -i -b '(let* ((i (car (gimp-image-new 400 400 1))) (d (car (gimp-layer-new i 400 400 2 "b" 100 0)))) (gimp-image-insert-layer i d 0 -1) (define (t x y) (gimp-selection-translate i x y)) (define (x) (t 100 0)) (define (X) (t -100 0)) (define (y) (t 50 50)) (define (Y) (t -50 50)) (define (f) (gimp-edit-fill d 1)) (define (r) (f) (x) (f) (x) (f) (x) (f) (y)) (define (R) (f) (X) (f) (X) (f) (X) (f) (Y)) (gimp-image-select-rectangle i 2 0 0 50 50) (r) (R) (r) (R) (r) (R) (r) (R) (gimp-file-save 1 i d "c.png" "c.png") (gimp-quit 0))'

```

Ungolfed Scheme script-fu:

```
(let* ((i (car (gimp-image-new 400 400 GRAY)))
       (d (car (gimp-layer-new i 400 400 GRAY-IMAGE "b" 100 NORMAL-MODE))))

  (gimp-image-insert-layer i d 0 -1)
  (define (t x y) (gimp-selection-translate i x y))
  (define (x) (t 100 0))
  (define (X) (t -100 0))
  (define (y) (t 50 50))
  (define (Y) (t -50 50))
  (define (f) (gimp-edit-fill d BACKGROUND-FILL))
  (define (r) (f) (x) (f) (x) (f) (x) (f) (y))
  (define (R) (f) (X) (f) (X) (f) (X) (f) (Y))

  (gimp-image-select-rectangle i CHANNEL-OP-REPLACE 0 0 50 50)
  (r) (R) (r) (R) (r) (R) (r) (R)
  (gimp-file-save RUN-NONINTERACTIVE i d "c.png" "c.png")
  (gimp-quit 0))

```

In batch mode, create a blank image, create a 50x50 rectangular selection, fill it, and then repeatedly move it around the image, filling in squares. Then save to `c.png` and exit.

Output:

# Answer
> 2 votes
# , ~~40~~ 38 bytes

*Edit: -2 bytes thanks to Robin Ryder*

```
image(matrix(1:0,9,8)[-1,],c=1:0,ax=F)

```

Try it at rdrr.io

This nicely exploits R's argument-recycling to fill a `matrix()` with dimensions of `9,8` with values of `1:0` recycled to fill it. We then use negative indexing `[-1,]` to chop-off the first row.

The `image()` function converts a matrix directly into a coloured image. Here we specify the `c`olor as `1:0` (black & white), and the `ax`es as `F`ALSE.

# Answer
> 2 votes
# AppleSoft Basic, 146 bytes

The best (standard) resolution available on the Apple II is `HGR2` mode, at 280x192 pixels, so the squares are 24x24. Verified at https://www.calormen.com/jsbasic/

```
0HGR2:HCOLOR=3:A=0:B=167:GOSUB8:A=24:B=191:GOSUB8:END
8FORI=A TOB STEP48:FORJ=A TOB STEP48:FORK=0TO23:HPLOTI+K,J TOI+K,J+23:NEXT:NEXT:NEXT:RETURN

```

image credit: Apple II Basic Bot on twitter

If we totally ignore resolution & use `GR` mode, 107 bytes:

```
1GR:COLOR=15:A=0:B=7:GOSUB8:A=1:B=8:GOSUB8:END
8FORI=A TOB STEP2:FORJ=A TOB STEP2:PLOTI,J:NEXT:NEXT:RETURN

```

# Answer
> 1 votes
# JavaScript, 150

This can definitely be golfed. It creates HTML.

```
for(i=0;i<8;)console.log(`<b style=margin-${['lef','righ'][i++%2]}t:50;width:50;height:50;display:inline-block;background:#000></b>`.repeat(4)+'<br>')

```

# Answer
> 1 votes
# Ruby with Shoes, 97 characters

```
Shoes.app(width:400){64.times{|i|stack(width:50,height:50){background [white,black][(i/8+i)%2]}}}

```

Sample output:

# Answer
> 1 votes
# Lua + LÖVE, ~~138~~ ~~113~~ ~~112~~ 106 characters

```
function love.draw()for i=0,31 do
love.graphics.rectangle("fill",i%8*50,(i-i%8)/8*100+i%2*50,50,50)end
end

```

Sample output:

# Answer
> 1 votes
## PowerShell + GDI, 346 bytes

```
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$f=New-Object Windows.Forms.Form
$f.width=$f.height=450
$g=$f.CreateGraphics()
$f.add_paint({0..7|%{$y=$_;0..7|%{$g.FillRectangle((New-Object Drawing.SolidBrush ("white","black")[($_+$y)%2]),(new-object Drawing.Rectangle ($_*50),($y*50),50,50))}}})
$f.showDialog()

```

(newlines count same as semicolon, so newlines for readability)

As opposed to my other answer, this one uses the .NET assemblies to call GDI+ function calls. Interestingly, it's about twice the length.

The first two lines load the `System.Windows.Forms` and `System.Drawing` assemblies. The first is used for the literal window and the canvas thereon, the second is used for the drawing object (in this code, a brush) that create the graphics on the canvas.

We then create our form `$f` with the next line, and set its `width` and `height` to be `450`. Note that this isn't `50*8`, since these numbers correspond to the border-to-border edge of the forms window, including titlebar, the close button, etc.

The next line creates our canvas `$g` by calling the empty constructor. This defaults to the upper-left of the non-system area of the form being equal to `0,0` and increasing to the right and downward, perfect for our needs.

The next line is the actual call that draws the graphics, with `$f.add_paint({...})`. We construct the graphics calls by double-for looping from `0..7` and carrying a helper variable `$y` through each outer loop. Each inner loop, we tell our canvas to `.FillRectangle(...,...)` to draw our squares. The first parameter constructs a new `SolidBrush` with a color based on where we're at on the board. Other options here could be a hatch, a gradient, etc. The second parameter is a new `Rectangle` object starting at the specified x `$_*50` and `$y*50` coordinates and extending for `50` in each direction. Remember that `0,0` is the top-left.

The final line just displays the output with `.showDialog()`.

Note that since we're creating a *form* object, and PowerShell is all about the pipeline, closing the pop-up form will pass along a `System.Enum.DialogResult` object of `Cancel`, since that's technically what the user did. Since we're not capturing or otherwise doing anything with that result, the word `Cancel` will be displayed to STDOUT when the program concludes, as it was left on the pipeline.

# Answer
> 1 votes
# J, ~~33~~31 bytes

I used a trick with binary.

```
   load'viewmat'
   viewmat 8 8$#:43605

```

... because 43605 in binary is 1010101001010101 (we use `#:` primitive to get it). Primitive `$` shapes this array of binary digits into a matrix specified with the dimensions `8 8`. And `viewmat` is just a system library.
The window is fully resizable.

Thanks to @FrownyFrog for shortening it to:

```
   load'viewmat'
   viewmat#:8$170 85

```

# Answer
> 1 votes
# Excel VBA, 82 Bytes

Anonymous VBE immediate window function that takes no input and outputs a checkerboard to the range `A1:H8` on the ActiveSheet object

```
Cells.RowHeight=48:[B1:B8,D1:D8,F1:F8,H1:H8].Interior.Color=0:[A2,A4,A6,A8].Delete

```

This function works by first creating 4 black columns in the range `B1:B8,D1:D8,F1:F8,H1:H8` and then offsetting the coloring in rows `2,4,6 and 8` to the left by one cell.

### Sample Output

# Answer
> 1 votes
# 05AB1E, 21 bytes

Outputs a PBM image.

```
„P1Ž1‘D‚T50×{Ƶ%×Â«4×»

```

Try it online!

**Commented**:

```
„P1                   # push the string "P1"
   Ž1‘                # push 400
      D‚              # duplicate and pair to [400, 400]
        T             # push 10
         50×          # repeat this 50 times as a string => "1010 ... 10"
            {         # sort the string                  => "00...011...1"
             Ƶ%×      # repeat it 200 times
                      # this is now a string of length 20000 which represents the top rank
                Â     # bifurcate: push the string and a reversed copy
                 «    # concatenate both, this is now the top two ranks
                  4×  # repeat this string 4 times
                    » # join the stack on newlines
                      # this joins all lists on spaces: [400, 400] -> "400 400"

```

This image was converted to png, here is the original output.

# Answer
> 1 votes
# Funky 2, 79 bytes

```
draw.newImageData(400,400).mapPixels((x,y)=>[c=1-(x//50+y//50)%2c,c]).export"o"

```

Or, if any size tiles is allowed...

# Funky 2, 67 bytes

```
draw.newImageData(8,8).mapPixels((x,y)=>[c=1-(x+y)%2c,c]).export"o"

```

This produces a file called `o` which is a PNG file.

## Breakdown

```
draw.newImageData(400,400)  $ Create the 8x8 chessboard at 50x50 pixels per square
.mapPixels((x,y)=>          $ Map each pixel in the image according to a function
    [ c = 1-(x//50+y//50)%2 $ This is the x added to the y of the chess tile, mod 2.
                            $ We take the result from 1 as otherwise 0, 0 is black.
    c,c ]                   $ Take the result and use it in G and B
                            $ Funky2 doesn't require a , for arguments where it is unambiguous
).export"o"                 $ Write the image to a file called "o", defaultly a PNG file.

```

# Answer
> 1 votes
# Scratch 3 (557 bytes)

Sb3 file - 4.15kb

The file can be found here - https://drive.google.com/file/d/1RJ8gaVUMKGW0xdC1tQSJqy0fvGsIp8n0/view?usp=sharing

You need to have scratch installed on the system.

Scratchblocks syntax - 557 bytes

```
when gf clicked
wait(0.4)seconds
go to x:(140)y:(140
stamp
repeat(3
change y by(-80
stamp
end
go to x:(140)y:(140
change x by(-40
change y by(-40
stamp
repeat(3
change y by(-80
stamp
end
go to x:(140)y:(140
change x by(-80
change y by(0
stamp
repeat(3
change y by(-80
stamp
end
go to x:(140)y:(140
change x by(-200
change y by(-40
stamp
repeat(3
change y by(-80
stamp
end
go to x:(140)y:(140
change x by(-240
change y by(0
stamp
repeat(3
change y by(-80
stamp
end
go to x:(140)y:(140
change x by(-280
change y by(-40
stamp
repeat(3
change y by(-80
stamp
end

```

:)

# Answer
> 1 votes
# Java 8, 142 bytes

```
import java.awt.*;v->new Frame(){public void paint(Graphics g){for(int i=32;i-->0;)g.fillRect(i%4*100+58-i%8/4*50,i/4*50+38,50,50);}{show();}}

```

Screenshot of the output:

**Explanation:**

```
import java.awt.*;         // Required import for Frame and Graphics
v->                        // Method with empty unused parameter and Frame return-type
  new Frame(){             //  Create a new Frame
    public void paint(Graphics g){
                           //   Overwrite its paint method
      for(int i=32;i-->0;) //    Loop `i` in the range (32,0]:
        g.fillRect(        //     Draw a solid rectangle, with:
                           //     (the color is black by default)
                           //      The x-coordinate of the top-left corner is:
          i%4*100          //       `i` modulo-4, multiplied by 100
          +58              //       Plus 50 since the first square is white
                           //       Plus 8 for the Frame's border
          -i%8/4*50,       //       Minus `i` modulo-8, integer-divided by 4, multiplied by 50
                           //      The y-coordinate of the top-left corner is:
          i/4*50           //       `i` integer-divided by 4 multiplied by 50
          +38,             //       Plus 8 for the Frame's border
                           //       Plus 30 for the Frame's title bar
          50,50);}         //      With a size of 50x50 pixels
    {                      //   And in an inner code-block:
      show();}}            //    Show the Frame

```

# Answer
> 1 votes
# JavaScript (V8), 129 bytes

```
q=()=>{for(s="",i=72;i--;)s+=i%9?`<canvas height="50"width="50"style="background:#${i%2?'eee':'000'}"></canvas>`:'<br>';return s}

console.log(q())
```

Try it online!

Function that returns an html chess board. Used a light grey instead of white for visibility sake.

Explanation:

q=()=>{for(s="",i=72;i--;)s+=i%9?`<canvas height="50"width="50"style="background:#${i%2?'eee':'000'}"></canvas>`:'
';return s}
q=()=>    // Function definition
     {for(s="",i=72;i--;)  // Loop 72 times, while we're at it, initialise an empty string.
         s+=i%9?  // Add the following to the string:
           // IF not the 9th tile:
             <canvas height="50"width="50"style="background:#${i%2?'eee':'000'}"></canvas>
           // IF is the 9th tile:

return s
```
</code></pre>

# Answer
> 1 votes
# CSS, 115 bytes

Using `repeating-conic-gradient` we can make a repeating chessboard pattern pretty efficiently in CSS without specifying any markup (but relying on the browser's default DOM structure):

```
*{background:#fff}*>*{width:400px;height:400px;background:repeating-conic-gradient(#000 0%25%,#fff 0%50%)0%0/25%25%

```

```
*{background:#fff}*>*{width:400px;height:400px;background:repeating-conic-gradient(#000 0%25%,#fff 0%50%)0%0/25%25%
```

## Explanation:

```
*{background:#fff}

```

This applies a background to all visible elements (being the `<html>` and `<body>`). This is needed to avoid the `<body>` background from stretching to fit the viewport width, which happens if the `<html>` element has no background.

```
*>*

```

Select all elements descendants of other elements. The only visible element this applies to is the `<body>`.

```
width:400px;height:400px;

```

Set chessboard dimensions

```
repeating-conic-gradient(
    #000 0%25%,
    #fff 0%50%
)

```

Creates a conic gradient shape with a black first quarter (from 0% to 25% or 0 to 90 deg), a white second quarter (from 25% to 50%, or 90 deg to 180deg) and repeats this way of coloring through the whole circle, resulting in four squares.

```
0%0/25%25%

```

Positioned at 0% 0% (upper left corner) and the size is set to 25%, relative to the body dimensions. This gives the conic gradient a full width/height of 100px, making each of the square/cell 50px.

## HTML and CSS alternative, 98 bytes

The above can be shortened slightly by relying on three bytes of HTML, although that won't really be CSS-only:

```

p{width:400px;height:400px;background:repeating-conic-gradient(#000 0%25%,#fff 0%50%)0%0/25%25%

```

```
p{width:400px;height:400px;background:repeating-conic-gradient(#000 0%25%,#fff 0%50%)0%0/25%25%
```

```

```

# Answer
> 0 votes
## SELECT., ~~8844~~ 8278 bytes

```
(9,9,50)EXP.SELECT.EXP.RIGHT.SELECT.LEFT.EXP.RIGHT.SELECT.LEFT.EXP.RIGHT.SELECT.LEFT.EXP.RIGHT.SELECT.LEFT.EXP.RIGHT.SELECT.LEFT.EXP.RIGHT.SELECT.LEFT.EXP.RIGHT.SELECT.LEFT.LOG.RIGHT.SELECT.LEFT.LOG.RIGHT.SELECT.EXP.LEFT.SELECT.RIGHT.EXP.LEFT.SELECT.RIGHT.LOG.RIGHT.SELECT.EXP.LEFT.SELECT.RIGHT.LOG.RIGHT.SELECT.EXP.LEFT.LEFT.SELECT.RIGHT.RIGHT.LOG.RIGHT.SELECT.LEFT.LEFT.LEFT.EXP.SELECT.EXP.RIGHT.SELECT.LOG.LEFT.SELECT.EXP.RIGHT.SELECT.RIGHT.EXP.SELECT.EXP.SELECT.EXP.LEFT.SELECT.RIGHT.LOG.LEFT.LEFT.SELECT.RIGHT.RIGHT.LOG.LEFT.LEFT.SELECT.RIGHT.RIGHT.RIGHT.EXP.SELECT.EXP.RIGHT.SELECT.LEFT.LOG.RIGHT.SELECT.LEFT.LOG.RIGHT.SELECT.RIGHT.EXP.SELECT.LEFT.LOG.RIGHT.SELECT.EXP.LEFT.SELECT.LOG.RIGHT.SELECT.RIGHT.EXP.SELECT.EXP.LEFT.SELECT.RIGHT.LOG.LEFT.SELECT.LOG.RIGHT.SELECT.EXP.LEFT.SELECT.RIGHT.RIGHT.EXP.SELECT.LEFT.LO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GHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.LOG.RIGHT.SELECT.EXP.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.LEFT.SELECT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.RIGHT.LOG.RIGHT.SELECT.EXP.LEFT.LEFT.SELECT.RIGHT.RIGHT.EXP.LEFT.SELECT.RIGHT.LOG.RIGHT.SELECT.LEFT.END.

```

Sure it's long, but the first two versions I generated for this task were twice as long.

### Output:

### How it Works:

Here's the program used to generate it:

```
init(9,9,50)
makenum(8)
square()
dec()
loop("main",computei=True)
go(1)
makenum(8)
go(1)
copyfrom(-2)
intdiv(-1)
add(-5)           # n%8 blah blah blah blah n//8 k^(n//8) k^(n%8) (n//8+n%8)
go(1)
makeneg1()
exptarget(-1)
go(1)
ifnonpositive("drawtest")
go(1)
makenum(-4,-4)    # n%8 blah blah blah blah n//8 k^(n//8) k^(n%8) n//8+n%8 (-1)^(n//8+n%8) 4 1/2 I k^(-4I) -1 (-4-4I)
go(1)
multiply(-4,-11)   # n%8 blah blah blah blah n//8 k^(n//8) k^(n%8) n//8+n%8 (-1)^(n//8+n%8) 4 1/2 I k^(-4I) -1 -4-4I (nI//8)
add(-16)          # n%8 blah blah blah blah n//8 k^(n//8) k^(n%8) n//8+n%8 (-1)^(n//8+n%8) 4 1/2 I k^(-4I) -1 -4-4I nI//8 k^(nI//8) k^(n%8) (n%8+nI//8)
add(-4)           # n%8 blah blah blah blah n//8 (-1)^(n%8) 4 1/2 I k^(-4I) -1 -4-4I nI//8 k^(nI//8) k^(n%8) n%8+nI//8 k^(n%8+nI//8) k^(-4-4I) ((n%8-4)+I(n//8-4))
output()
endif("drawtest")
go(1)
endloop("main")
writetofile("chessboard4")

```

In other words, loop n from 0 to 63, drawing a square at (n%8-4) + (n//8-4)i if (-1)^(n//8 + n%8) is not positive.

# Answer
> 0 votes
# JavaScript (ES6), 147

```
for(i=0;++i<72;)document.write(`<div style="${i%9?'':(++i,'clear:both;')}float:left;width:50px;height:50px;background:#${i&1?'fff':'000'}"></div>`)
```

# Answer
> 0 votes
# Python, 57 bytes

```
c=50*"1"+50*"0"
print"P1 400 400 "+4*(200*c+200*c[::-1])

```

`c` is a line of 50 white and 50 black pixels, `200*c` is a row with a white in the front, `200*c[::-1]` the reverse.

Output as PPM, usage:

```
python golf_chess.py > chess.ppm

```

# Answer
> 0 votes
# C, 157 Bytes

```
#include <stdio.h>
x,q,a;FILE*f;w(){f=fopen("a","w");fprintf(f,"P1400 400 ");for(;a++<8;)for(q=0;q++<400;)for(x=0;x++<50;)fprintf(f,"%d",(q+a)%2);fclose(f);}

```

This generate the file `a`, one PBM file.
You should add the `.pmb` extension

### Full Program

```
#include <stdio.h>
x,q,a;FILE*f;w(){f=fopen("a","w");fprintf(f,"P1400 400 ");for(;a++<8;)for(q=0;q++<400;)for(x=0;x++<50;)fprintf(f,"%d",(q+a)%2);fclose(f);}
main(){w();}

```

## C, Shorter Version (98 Bytes)

```
x,q,a;w(){printf("P1400 400 ");for(;a++<8;)for(q=0;q++<400;)for(x=0;x++<50;)printf("%d",(q+a)%2);}

```

This version print in the STDOUT the file. So you have to redirect it in the file manually.

# Answer
> 0 votes
**Mathematica 43 bytes**

```
ArrayPlot@Partition[Range[0,7]~Mod~2,8,1,1]
ArrayPlot@ArrayPad[{{0,1},{1,0}},3,"Periodic"]

```

# Answer
> 0 votes
# LibreLogo, 121 bytes

> LibreLogo produces a vector graphic that can be exported to SVG.

**Code:**

```
x=90 pu fc 0 repeat 64[ y=repcount if y%2=0[ square 1 ]if y%16=0[ rt x fd 1 rt x ][ if y%8=0[ lt x fd 1 lt x ][ fd 1 ] ]]

```

**Result**:

**Result (Expanded):**

**Explanation:**

```
x = 90                        ; x                  = 90°
pu                            ; Pen Up
fc 0                          ; Fill Color         = #000
repeat 64 [                   ; Repeat 64 Times
    y = repcount              ; y                  = Loop Index
    if y % 2 = 0 [
        square 1              ; Draw 1pt Square
    ]
    if y % 16 = 0 [
        rt x                  ; Turn Right 90°
        fd 1                  ; Move Forward 1pt
        rt x                  ; Turn Right 90°
    ] [
        if y % 8 = 0 [
            lt x              ; Turn Left 90°
            fd 1              ; Move Forward 1pt
            lt x              ; Turn Left 90°
        ] [
            fd 1              ; Move Forward 1pt
        ]
    ]
]

```

# Answer
> 0 votes
# Tcl/Tk, 130 bytes

```
time {incr j
time {grid [text .t[incr i]_$j -bg [expr ([incr n]+$j)%2?"#000":"#FFF"] -wi 6 -he 3] -row $j -column $i} 8
set i 0} 8

```

Could not get exactly 50 pixels per square, so I went to a round-up!

# Answer
> 0 votes
# Haskell, 95 bytes

```
f s="Be7#"*>s<*[1..50]
main=mapM putStrLn$"P1\n400 400":f(concat.f<$>[["0 ","1 "],["1 ","0 "]])

```

Outputs to stdout a portable bitmap (PBM), shown below at half size.

Try it online!

# Answer
> 0 votes
# C (gcc), ~~74~~ 71 bytes

-3 bytes thanks to ceilingcat

Outputs a PBM file to STDOUT.

```
i;main(){for(;i<16e4;i++)puts(i?L"01"+(i/'N '^i/50)%2:"P1 400 400 0");}

```

Try it online!

# Answer
> 0 votes
# Processing, 66 bytes

`for(int x=64;x-->0;square(x/8*12,x%8*12,12))fill((x/8&1^x&1)*255);`

# Answer
> 0 votes
# x86 machine code, IBM PC, 30 bytes

```
00000000: b006 cd10 b40c 99b1 ff8a c1c0 e805 32c3  ..............2.
00000010: cd10 8ada c0eb 04e2 f0fe c279 eac3       ...........y..

```

**Listing**

```
B0 06       MOV  AL, 6          ; BIOS set video mode 6 (640x200 CGA, 1 bpp)
CD 10       INT  10H
B4 0C       MOV  AH, 0CH        ; BIOS draw graphics pixel function
99          CWD                 ; Y counter DL = 0 (incrementing)
        Y_LOOP:
B1 FF       MOV  CL, 255        ; X counter CL = 255 (decrementing)
        X_LOOP:
8A C1       MOV  AL, CL         ; AL = column square number
C0 E8 05    SHR  AL, 5          ; AL = CL / 32
32 C3       XOR  AL, BL         ; alternate pixel colors
CD 10       INT  10H            ; draw pixel at [CX, DX]
8A DA       MOV  BL, DL         ; BL = row square number
C0 EB 04    SHR  BL, 4          ; BL = DL / 16
E2 F0       LOOP X_LOOP         ; loop X 255 times
FE C2       INC  DL
79 EA       JNS  Y_LOOP         ; loop Y 127 times
C3          RET

```

Standalone executable DOS COM program. Draws using the BIOS `INT 10h` routines in CGA graphics mode 6 (640x200 black and white). Due to the PAR of this mode (3.2:1), the squares are 32x16 pixels to be roughly square when aspect corrected.

# Answer
> 0 votes
# JavaScript (Node.js), 101 bytes

Does this count?

```
console.log([...Array(8)].map((v,i)=>[...Array(8)].map((b,y)=>(i+y)%2?"⬛":"⬜").join``).join`\n`)

```

Try it online!

---
Tags: code-golf, graphical-output
---


title: Boustrophedonise

text:
# Question
Title: Boustrophedonise
Related but very different.

A boustrophedon is a text where every other line of writing is flipped or reversed, with reversed letters.

In this challenge, we will just reverse every other line, but leave the actual characters used intact. You may chose which lines to reverse, as long as it is every other one.

You may take the text in any suitable format as long as you support zero or more lines of printable ASCII, each with zero or more characters.

### Examples:

```
["Here are some lines","of text for you","to make a","boustrophedon"]:

["Here are some lines","uoy rof txet fo","to make a","nodehportsuob"] or ["senil emos era ereH","of text for you","a ekam ot","boustrophedon"]

["My boustrophedon"]:

["My boustrophedon"] or ["nodehportsuob yM"]

[]:
[]

["Some text","","More text","","","Last bit of text"]:

["Some text","","More text","","","txet fo tib tsaL"] or ["txet emoS","","txet eroM","","","Last bit of text"]

```

# Answer
# APL (Dyalog Classic), 4 bytes

```
⊢∘⌽\

```

The input is a vector of character vectors.

is a function that reverses a vector (when  is applied monadically).

is "*dex*" - a function that returns its right argument. When composed () with another function `f` it forces the latter to be monadic as `A ⊢∘f B` is equivalent to `A ⊢ (f B)` and therefore `f B`.

`\` is the *scan* operator. `g\A B C ...` is the vector `A (A g B) (A g (B g C)) ...` where `g` is applied dyadically (infix notation). Substituting `⊢∘⌽` for `g` it simplifies to:

```
A (A ⊢∘⌽ B) (A ⊢∘⌽ (B ⊢∘⌽ C)) ...
A (⌽B) (⌽⌽C) ....
A (⌽B) C ....

```

The reversals at even positions (or odd, depending on how you count) cancel out.

Try it online!
> 23 votes

# Answer
# Haskell, 26 bytes

```
zipWith($)l
l=id:reverse:l

```

Try it online! Usage example: `zipWith($)l ["abc","def","ghi"]` yields `["abc","fed","ghi"]`.

**Explanation:**

`l` is an infinite list of functions alternating between the `id`entity function and the `reverse` function.

The main function zips `l` and the input list with the function application `$`, that is for an input `["abc", "def", "ghi"]` we get `[id$"abc", reverse$"def", id$"ghi"]`.
> 13 votes

# Answer
# Husk, 4 bytes

```
z*İ_

```

Takes and returns a list of strings (the interpreter implicitly joins the result by newlines before printing). The first string is reversed. Try it online!

## Explanation

```
z*İ_  Implicit input.
  İ_  The infinite list [-1,1,-1,1,-1,1..
z     Zip with input
 *    using multiplication.

```

In Husk, multiplying a string with a number repeats it that many times, also reversing it if the number is negative.
> 13 votes

# Answer
# JavaScript (ES6), Firefox, 43 bytes

This version abuses the sort algorithm of **Firefox**. It generates garbage on Chrome and doesn't alter the strings at all on Edge.

```
a=>a.map((s,i)=>[...s].sort(_=>i&1).join``)

```

### Test cases

```
let f =

a=>a.map((s,i)=>[...s].sort(_=>i&1).join``)

console.log(f(["Here are some lines","of text for you","to make a","boustrophedon"]))
console.log(f(["My boustrophedon"]))
console.log(f([]))
```

Or Try it online! (SpiderMonkey)

---

# JavaScript (ES6), 45 bytes

```
a=>a.map(s=>(a^=1)?s:[...s].reverse().join``)

```

### Test cases

```
let f =

a=>a.map(s=>(a^=1)?s:[...s].reverse().join``)

console.log(f(["Here are some lines","of text for you","to make a","boustrophedon"]))
console.log(f(["My boustrophedon"]))
console.log(f([]))
```
> 7 votes

# Answer
# Haskell, 27 bytes

```
foldr((.map reverse).(:))[]

```

Try it online!

## Haskell, 30 bytes

```
f(a:b:c)=a:reverse b:f c
f a=a

```

Try it online!

Recursion FTW.
> 6 votes

# Answer
# Perl 5, 17 + 2 (-pl) = 19 bytes

odd lines reversed

```
$_=reverse if$.%2

```

even lines reversed

```
$_=reverse if$|--

```

After @Martin's comment : input needs to have a trailing linefeed.

try it online
> 6 votes

# Answer
# APL (Dyalog Unicode), 10 bytes

```
⌽¨@{2|⍳≢⍵}

```

Works both ways:

Try it online! with `⎕IO←1`

Try it online! with `⎕IO←0`

### How it works:

```
⌽¨@{2|⍳≢⍵} ⍝ tacit prefix fn
   {   ≢⍵} ⍝ Length of the input
      ⍳    ⍝ generate indexes from 1 (or 0 with ⎕IO←0)
    2|     ⍝ mod 2; this generates a boolean vector of 0s (falsy) and 1s (truthy)
  @        ⍝ apply to the truthy indexes...
⌽¨         ⍝ reverse each element

```
> 6 votes

# Answer
# 05AB1E, ~~5~~ 4 bytes

```
εNFR

```

Try it online!

**Explanation**

```
ε     # apply to each element (row)
 NF   # index times do:
   R  # reverse

```
> 5 votes

# Answer
# , 85 bytes

```
for(i in seq(l<-strsplit(readLines(),"")))cat("if"(i%%2,`(`,rev)(l[[i]]),"\n",sep="")

```

Try it online!

Input from stdin and output to stdout.

Each line must be terminated by a linefeed/carriage return/CRLF, and it prints with a corresponding newline. So, inputs need to have a trailing linefeed.
> 4 votes

# Answer
# K (oK), ~~17~~ 14 bytes

**Solution:**

```
@[;&2!!#x;|]x:

```

Try it online!

**Example:**

```
@[;&2!!#x;|]x:("this is";"my example";"of the";"solution")
("this is"
"elpmaxe ym"
"of the"
"noitulos")

```

**Explanation:**

Apply `reverse` at odd indices of the input list:

```
@[;&2!!#x;|]x: / the solution
            x: / store input as variable x
@[;      ; ]   / apply @[variable;indices;function] (projection)
          |    / reverse
       #x      / count (length) of x, e.g. 4
      !        / til, !4 => 0 1 2 3
    2!         / mod 2, 0 1 2 3 => 0 1 0 1
   &           / where true, 0 1 0 1 => 1 3

```

**Notes:**

* switched out `&(#x)#0 1` for `&2!!#x` to save 3 bytes
> 3 votes

# Answer
# APL (Dyalog), 12 bytes

```
⍳∘≢{⌽⍣⍺⊢⍵}¨⊢

```

Try it online!
> 3 votes

# Answer
# Jelly, ~~5~~ 4 bytes

```
U¹ƭ€

```

Try it online!

Thanks *HyperNeutrino* for -1 bytes! (actually because I never knew how `ƭ` works due to lack of documentation, this time I got lucky)
> 3 votes

# Answer
# Python 2, ~~40~~ 36 bytes

*-4 bytes thanks to @Mr.Xcoder*

```
def f(k):k[::2]=map(reversed,k[::2])

```

Try it online!

Outputs by modifying the input list

---

# Python 2, 43 bytes

```
f=lambda k,d=1:k and[k[0][::d]]+f(k[1:],-d)

```

Try it online!
> 3 votes

# Answer
# , 9 bytes

```
(,|.&.>)/

```

Reduce from right to left, reversing all strings in the result and prepending the next string as is.

Try it online!

We can do **6** using ngn’s approach, but there will be extra spaces:

```
]&|./\

```

Try it online!
> 3 votes

# Answer
# Alumin, 66 bytes

```
hdqqkiddzhceyhhhhhdaeuzepkrlhcwdqkkrhzpkzerlhcwqopshhhhhdaosyhapzw

```

Try it online!

```
FLAG: h
hq
  CONSUME A LINE
  qk
  iddzhceyhhhhhdaeuze
  pk
  rlhcw
  REVERSE STACK CONDITIONALLY
  dqkkrhzpkzerlhcwqops

  OUTPUT A NEWLINE
  hhhhhdao
syhapzw

```
> 3 votes

# Answer
# T-SQL, 65 bytes

Our standard input rules allow SQL to input values from a pre-existing table, and since SQL is inherently unordered, the table must have row numbers to preserve the original text order.

I've defined the table with an identity column so we can simply insert lines of text sequentially (not counted toward byte total):

```
CREATE TABLE t
    (i int identity(1,1)
    ,a varchar(999))

```

So to select and reverse alternating rows:

```
SELECT CASE WHEN i%2=0THEN a
ELSE reverse(a)END
FROM t
ORDER BY i

```

Note that I can save 11 bytes by excluding the `ORDER BY i`, and that is *likely* to return the list in the original order for any reasonable length (it certainly does for the 4-line example). But SQL only *guarantees* it if you include the `ORDER BY`, so if we had, say, 10,000 rows, we would definitely need this.
> 2 votes

# Answer
# , 4 bytes

```
òjæ$

```

Try it online!

```
ò      ' <M-r>ecursively (Until breaking)
 j     ' Move down (breaks when we can't move down any more)
  æ$   ' <M-f>lip the line to the end$

```
> 2 votes

# Answer
# Perl 6, 44 bytes

```
lines.map: ->\a,$b?{a.put;.flip.put with $b}

```

Try it

```
lines               # get the input as a list of lines
.map:
-> \a, $b? {        # $b is optional (needed if there is an odd number of lines)
  a.put;            # just print with trailing newline
  .flip.put with $b # if $b is defined, flip it and print with trailing newline
}

```
> 2 votes

# Answer
Comma delimited:

# Stax, 12 bytes

```
ü«äì╠▒╕█╬pεû

```

Run and debug it

input: ABC,def,GHI,jkl,MNO,pqr,STU

Newline delimited:

# Stax, 8 bytes

```
Çε÷┘)¼M@

```

Run and debug it

input:

```
ABC
def
GHI
jkl
MNO
pqr
STU

```

output for both:

```
CBA
def
IHG
jkl
ONM
pqr
UTS

```
> 2 votes

# Answer
# Brachylog, 4 bytes

```
i↔ⁱ⁾

```

Try it online!

Doesn't feel *entirely* honest to call this generator a 4-byter considering it costs 3 more bytes to actually use it.

```
i       Take an element from the input paired with its 0-index,
 ↔ ⁾    and reverse the element
  ⁱ     repeatedly
   ⁾    a number of times equal to the index.

```
> 2 votes

# Answer
# C#, 64 54 + 18 bytes

Try It Online!

```
a=>a.Select((x,i)=>i%2<1?x:string.Concat(x.Reverse())).ToArray()

```

Saved 10 bytes by returning `IEnumerable`
> 1 votes

# Answer
# Pyth, 6 bytes

```
.e@_Bb

```

**Try it here!**

* `.e` ~ Enumerated map. `k` is the index, `b` is the current element.
* `_Bb` ~ Bifurcate `b` with its reverse.
* `@` ~ Modular index in ^ with `k`.
> 1 votes

# Answer
## Alice, 13 bytes

```
M%/RM\
d&\tO/

```

Try it online!

Input via separate command-line arguments. Reverses the first line (and every other line after that).

### Explanation

```
       At the beginning of each loop iteration there will always be zero
       on top of the stack (potentially as a string, but it will be
       converted to an integer implicitly once we need it).
M      Push the number of remaining command-line arguments, M.
%      Take the zero on top of the stack modulo M. This just gives zero as
       long as there are arguments left, otherwise this terminates the
       program due to the division by zero.
/      Switch to Ordinal mode.
t      Tail. Implicitly converts the zero to a string and splits off the
       last character. The purpose of this is to put an empty string below
       the zero, which increases the stack depth by one.
M      Retrieve the next command-line argument and push it as a string.
/      Switch back to Cardinal mode.
d      Push the stack depth, D.
&\R    Switch back to Ordinal mode and reverse the current line D times.
O      Print the (possibly reversed) line with a trailing linefeed.
\      Switch back to Cardinal mode.
       The instruction pointer loops around and the program starts over
       from the beginning.

```
> 1 votes

# Answer
# Python 2, 45 bytes

```
lambda k:[r[::i%-2|1]for i,r in enumerate(k)]

```

Try it online!

# Python 2, 46 bytes

```
f=lambda k:k and[k[0][::len(k)%-2|1]]+f(k[1:])

```

Try it online!
> 1 votes

# Answer
# Actually, 7 bytes

```
;r'R*♀ƒ

```

Explanation:

```
;r'R*♀ƒ
;r       range(len(input))
  'R*    repeat "R" n times for n in range
     ♀ƒ  call each string as Actually code with the corresponding input element as input (reverse each input string a number of times equal to its index)

```

Try it online!
> 1 votes

# Answer
# Tcl, 61 bytes

```
proc B L {lmap e $L {expr [incr i]%2?"$e":"[string rev $e]"}}

```

Try it online!
> 1 votes

# Answer
# Standard ML (MLton), 51 bytes

```
fun$(a::b::r)=a::implode(rev(explode b)):: $r| $e=e

```

Try it online! Usage example: `$ ["abc","def","ghi"]` yields `["abc","fed","ghi"]`.

**Explanation:**

`$` is a function recursing over a list of strings. It takes two strings `a` and `b` from the list, keeps the first unchanged and reverses the second by transforming the string into a list of characters (`explode`), reversing the list (`rev`), and turning it back into a string (`implode`).
> 1 votes

# Answer
# Stacked, 18 bytes

```
[{x i:x$revi*}map]

```

Try it online!

This simply reverses each string in the array according to its position.

## Alternative, 24 bytes

```
[:#':>#,tr[...$rev*]map]

```

Same approach, but generates indices manually.
> 1 votes

# Answer
# Red, 61 bytes

```
f: func[s][forall s[if odd? length? s[reverse s/1]print s/1]]

```

Try it online!
> 1 votes

# Answer
# Jelly, 5 bytes

```
UJḤ$¦

```

Try it online!*

*\*Jelly outputs nested lists joined by spaces, and there is no native string type. Strings in Jelly are lists of characters, and that's why they're displayed that way. If you want them to be merged by spaces, Try this.*
> 1 votes

# Answer
# Charcoal, 9 bytes

```
ＥＮ⎇﹪ι²⮌ＳＳ

```

Try it online! Link is to verbose version of code. Note: Charcoal doesn't know the length of the list, so I've added it as an extra element. Explanation:

```
 Ｎ          First value as a number
Ｅ           Map over implicit range
    ι       Current index
     ²      Literal 2
   ﹪        Modulo
  ⎇         Ternary
       Ｓ    Next string value
      ⮌     Reverse
        Ｓ   Next string value
            Implicitly print array, one element per line.

```
> 1 votes

# Answer
# Retina, 18 bytes

```
{O$^`\G.

*2G`
2A`

```

Try it online! Explanation: The first stage reverse the first line, then the second stage prints the first two lines, after which the third stage deletes them. The whole program then repeats until there is nothing left. One trailing newline could be removed at a cost of a leading `;`.
> 1 votes

# Answer
# CJam, 11 bytes

```
{2/Waf.%:~}

```

Try it online! (CJam array literals use spaces to separate elements)

Explanation:

```
{              Begin block, stack: ["Here are some lines" "of text for you" "to make a" "boustrophedon"]
 2/            Group by 2:         [["Here are some lines" "of text for you"] ["to make a" "boustrophedon"]]
   W           Push -1:            [["Here are some lines" "of text for you"] ["to make a" "boustrophedon"]] -1
    a          Wrap in array:      [["Here are some lines" "of text for you"] ["to make a" "boustrophedon"]] [-1]
     f.%       Vectorized zipped array reverse (black magic):
                                   [["senil emos era ereH" "of text for you"] ["a ekam ot" "boustrophedon"]]
        :~     Flatten:            ["senil emos era ereH" "of text for you" "a ekam ot" "boustrophedon"]
          }

```

Explanation for the `Waf.%` "black magic" part:

* `W` is a variable preinitialized to `-1`. `a` wraps an element in an array, so `Wa` is `[-1]`.
* `%` pops a number `n` and an array `a` and takes every `n`th element of the array. When `n` is negative, it also reverses it, meaning that `W%` reverses an array.
* `.` followed by a binary operation applies that operation to corresponding elements of an array, so `[1 2 3] [4 5 6] .+` is `[5 7 9]`. If one array is longer than the other, the elements are kept without modification, meaning that `Wa.%` reverses the first element of an array.
* `f` followed by a binary operation will take an element from the stack and then act like `{<that element> <that operation>}%`, that is, go through each element in the array, push its element, push the element first popped from the stack, run the operation, and then collect the results back into an array. This means that `Wa.f%` reverses the first element of every element in the array.
> 1 votes

# Answer
# Wolfram Language (Mathematica), 33 bytes

```
Fold[StringReverse@*Append,{},#]&

```

Try it online!

## How it works

`StringReverse@*Append`, when given a list of strings and another string as input, adds the string to the end of the list and then reverses all of the strings.

`Fold`ing the input with respect to the above means we:

* Reverse the first line.
* Add the second line to the end and reverse both of them.
* Add the third line to the end and reverse all three.
* Add the fourth line to the end and reverse all four.
* And so on, until we run out of lines.

Each line gets reversed one time fewer than the previous line, so the lines alternate direction.
> 1 votes

# Answer
# MATL, 7 bytes

```
"@gNo?P

```

Try it online!

Takes a cell array of strings, and leaves the result on the stack.

### Explanation

```
"         % Loop over cell array
 @g     %   Push new string, and 'unwrap' it from its cell array.
     No?  %   Yes? Maybe so? (push stack size N, check if odd o, if so,...
        P %     Flip

```

As the implicit print function in MATL does not display an empty line for an empty item on the stack, we explicitly end the if-statement and loop and print the stack in the TIO footer:

```
]]X#

```

But this is not part of the program, as per the IO default
> 1 votes

# Answer
# C,  ~~118~~   ~~103~~  101 bytes

*Thanks to @gastropner for saving 15 bytes and thanks to @ceilingcat for saving a byte!*

```
i;f(l,n)char**l;{for(;n--;++l,n&1&&puts(""))for(i=strlen(*l);(n&1||!puts(*l))*i;putchar((*l)[--i]));}

```

Try it online!

# C, 147 bytes

```
i,j;f(char*s){char t[strlen(s)];for(i=0;;t[j++]=*s++)if(!*s|*s==10){t[j]=0;i=!i;for(i&&(j=!puts(t));j;j||puts(""))putchar(t[--j]);if(!*s++)break;}}

```

Try it online!
> 1 votes

# Answer
# Swift, ~~90~~ ~~85~~ ~~82~~ 72 bytes

-10 bytes thanks to @Mr.Xcoder

```
func f(a:[String]){print(a.reduce([]){$0.map{"\($0.reversed())"}+[$1]})}

```
> 1 votes

# Answer
# Ruby, 19 + 2 = 21 bytes

+2 bytes for `-nl` flags.

```
$.%2<1&&$_.reverse!

```

Try it online!

## Explanation

Practically identical to the Perl 5 answer, though I hadn’t seen that one when I wrote this.

With whitespace, the code looks like this:

```
$. % 2 < 1 && $_.reverse!

```

The `-p` option makes Ruby effectively wrap your script in a loop like this:

```
while gets
  # ...
  puts $_
end

```

The special variable `$_` contains the last line read by `gets`, and `$.` contains the line number.

The `-l` enables automatic line ending processing, which automatically calls `chop!` on each input line, which removes the the `\n` before we reverse it.
> 1 votes

# Answer
# GNU sed, 31 + 1 = 32 bytes

+1 byte for `-r` flag.

```
G
:
s/(.)(.*\n)/\2\1/
t
s/.//
N

```

Try it online!

## Explanation

```
G                   # Append a newline and contents of the (empty) hold space
:
  s/(.)(.*\n)/\2\1/   # Move the first character to after the newline
  t                   # If we made the above substitution, branch to :
s/.//               # Delete the first character (now the newline)
N                   # Append a newline and the next line of input

```
> 1 votes

# Answer
# Röda, 33 bytes

```
{enum|[_[::-1]]if[_%2=0]else[_1]}

```

Try it online!

Explanation:

```
{
 enum|     /* Zip elements in the stream with [0,1,...] */
           /* For each string _1 and index _2: */
 [_[::-1]] /*  Push _1 reversed */\
 if[_%2=0] /*   if the index is even */
 else[_1]  /*  else push _1 */
}

```
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), ~~89~~ 80 bytes

```
R	X =1 - X
	N =INPUT	:F(END)
	OUTPUT =EQ(X) N :S(R)
	OUTPUT =REVERSE(N) :(R)
END

```

Try it online!
> 1 votes

# Answer
# Befunge-93, 48 bytes

```
 <~,#_|#*-+92:+1:
#^_@  >:#,_"#"40g!*40p91+,~:1+

```

Try It Online

Prints first line in reverse. Has a trailing newline.

Basically, it works by alternating between printing as it gets input and storing the input on the stack. When it reaches a newline or end of input, it prints out the stack, prints a newline, and modifies the character at 0,4 to be either a # or a no-op to change the mode. If it was the end of input, end the program
> 1 votes

# Answer
# JavaScript (ES6), Firefox, 42 bytes, optimized from Arnauld's

```
a=>a.map(s=>[...s].sort(_=>a,a=!a).join``)

```
> 1 votes

# Answer
# Clean, 59 bytes

```
import StdEnv
@t=[if(n rem 2<1)s(reverse s)\\s<-t&n<-[0..]]

```

Try it online!
> 1 votes

# Answer
# Zsh+coreutils, 31 bytes

```
for s;((i^=1))&&<<<$s||rev<<<$s

```

Try it online!

Repeated xoring will switch `i` between 0 and 1, so we alternate our output. Because the ternary chains our commands together, surrounding `{` `}` are unnecessary.

## Zsh+coreutils, 23 bytes (almost correct)

```
for a b;<<<$a&&rev<<<$b

```

Try it online!

`for` sets `b` to the empty string if there are no more arguments. This unfortunately means that for an odd number of inputs, an extra empty line will be printed at the end.
> 1 votes

# Answer
# Japt `-m`, ~~4~~ 3 bytes

I/O as an array of lines.

```
zVÑ

```

Try it

```
zVÑ     :Implicit map of each string at 0-based index V in input array
z       :Rotate 90 degrees clockwise
 EÑ     :V*2 times

```
> 1 votes

# Answer
## Pip, 16 bytes

```
Flg{Po?lRVlo!:o}

```

This loops over each line and reverses it based on the value of variable `o`(Predefined to 1), which is inverted each time the loop runs.

Try it online!

```
Fi,#gPi%2?RVg@ig@i

```

This one is based on the indices of each line instead.
> 1 votes

# Answer
# Jelly, 3 bytes

```
UÐe

```

Try it online!

(or `UÐo`, reversing the other lines.)

```
U      (Vectorized) reverse
 Ðe    the even numbered lines.

```

Essentially Mr. Xcoder's 5-byter, but with what I assume is a newer addition to the language.
> 1 votes

# Answer
# Vyxal, 3 bytes

```
yRY

```

Try it Online!

Look ma, no Unicode!

```
y   # Uninterleave
 R  # Vectorised reverse
  Y # Interleave

```
> 1 votes

# Answer
# PHP, 54 bytes

```
function(&$a){foreach($a as&$s)$i++&1&&$s=strrev($s);}

```

function works on argument (call by reference)
> 0 votes

# Answer
# Julia 0.6, 34 bytes

```
~x=x[2:2:end]=reverse.(x[2:2:end])

```

Try it online!

Function modifying the input in place.
> 0 votes

# Answer
# Java 8, 53 bytes

```
a->{for(int i=1;i<a.length;i+=2)a[i]=a[i].reverse();}

```

Reverses every odd 0-indexed item.
Input as an array of `StringBuffers`. Modifies the input-array instead of returning a new one to save bytes.

Try it online.

**Explanation:**

```
a->{                       // Method with StringBuffer-array parameter and no return-type
  for(int i=1;i<a.length;  //  Loop `i` in the range `[1, input_length)
      i+=2)                //    And increase `i` by 2 after every iteration
    a[i]=a[i].reverse();}  //   Reverse the StringBuffer at index `i`

```
> 0 votes

# Answer
# Python 3, 46 bytes

```
lambda l:[u[::(-1)**i]for i,u in enumerate(l)]

```

Try it online!
> 0 votes

# Answer
# Thunno 2, 4 bytes

```
ıṅ{r

```

Attempt This Online!

#### Explanation

```
ıṅ{r  # Implicit input
ı     # Map over the input list:
 ṅ    #  Push the 0-based iteration index
  {   #  That many times repeat:
   r  #   Reverse the string
      # Implicit output

```
> 0 votes

---
Tags: code-golf, array, typography, text-processing
---