title: Draw ASCII boxes in boxes

text:
# Question
Title: Draw ASCII boxes in boxes
# Problem

given input `a,b,c`

where `a,b,c` are positive even integers

and `a > b > c`

Make a box of any allowed character with dimensions `a x a`

Center a box of a different allowed character with dimensions `b x b` within the previous

Center a box of another different allowed character with dimensions `c x c` within the previous

Allowed Characters are ASCII characters are in `[a-zA-z0-9!@#$%^&*()+,./<>?:";=_-+]`

Input `a=6, b=4, c=2`

```
######
#****#
#*@@*#
#*@@*#
#****#
######

```

Input `a=8, b=6, c=2`

```
########
#******#
#******#
#**@@**#
#**@@**#
#******#
#******#
########

```

Input `a=12, b=6, c=2`

```
############
############
############
###******###
###******###
###**@@**###
###**@@**###
###******###
###******###
############
############
############

```

# Rules

* **Shortest code wins**
* Remember that you can choose which char to print within the range given
* Trailing newlines accepted
* Trailing whitespace accepted
* functions may return string with newlines, string array, or print it

# Answer
> 8 votes
# Charcoal, 14 bytes

```
Ｆ#*@ＵＯ÷Ｎ²ι‖Ｃ←↑

```

Try it online! Link is to verbose version of code.

# Answer
> 7 votes
# Jelly,  ~~20~~  19 bytes

-1 byte using the quick ``` to avoid a link, as suggested by Erik the Outgolfer.

```
H»þ`€Ḣ>Ð€HSUṚm€0m0Y

```

A full program taking a list `[a,b,c]` printing the boxes using `a:2 b:1 c:0`
... in fact, as is, it will work for up to **10** boxes, where the innermost box is `0` (for example).

**Try it online!**

### How?

```
H»þ`€Ḣ>Ð€HSUṚm€0m0Y - Main link: list of boxes, B = [a, b, c]
H                   - halve B = [a/2, b/2, c/2]
    €               - for €ach:
   `                -   repeat left argument as the right argument of the dyadic operation:
  þ                 -     outer product with the dyadic operation:
 »                  -       maximum
                    - ... Note: implicit range building causes this to yield
                    -       [[max(1,1),max(1,2),...,max(1,n)],
                    -        [max(2,1),max(2,2),...,max(2,n)],
                    -        ...
                    -        [max(n,1),max(n,2),...,max(n,n)]]
                    -       for n in [a/2,b/2,c/2]
     Ḣ              - head (we only really want n=a/2 - an enumeration of a quadrant)
         H          - halve B = [a/2, b/2, c/2]
       Ð€           - map across right with dyadic operation:
      >             -   is greater than?
                    - ...this yields three copies of the lower-right quadrant
                    -    with 0 if the location is within each box and 1 if not
          S         - sum ...yielding one with 0 for the innermost box, 1 for the next, ...
           U        - upend (reverse each) ...making it the lower-left
            Ṛ       - reverse ...making it the upper-right
             m€0    - reflect €ach row (mod-index, m, with right argument 0 reflects)
                m0  - reflect the rows ...now we have the whole thing with integers
                  Y - join with newlines ...making a mixed list of integers and characters
                    - implicit print - the representation of a mixed list is "smashed"

```

# Answer
> 7 votes
# Python 2, ~~107~~ 103 bytes

```
a,b,c=input()
r=range(1-a,a,2)
for y in r:
 s=''
 for x in r:m=max(x,y,-x,-y);s+=`(m>c)+(m>b)`
 print s

```

Full program, prints boxes with `a=2`,`b=1`,`c=0`

Slightly worse answer, with list comprehension (104 bytes):

```
a,b,c=input()
r=range(1-a,a,2)
for y in r:print''.join(`(m>c)+(m>b)`for x in r for m in[max(x,y,-x,-y)])

```

# Answer
> 5 votes
# C#, ~~274~~ 232 bytes

```
using System.Linq;(a,b,c)=>{var r=new string[a].Select(l=>new string('#',a)).ToArray();for(int i=0,j,m=(a-b)/2,n=(a-c)/2;i<b;++i)for(j=0;j=n&i+m<n+c&j+m>n&j+m<=n+c?"@":"*");return r;}

```

Terrible even for C# so can definitely be golfed but my mind has gone blank.

Full/Formatted version:

```
using System;
using System.Linq;

class P
{
    static void Main()
    {
        Func<int, int, int, string[]> f = (a,b,c) =>
        {
            var r = new string[a].Select(l => new string('#', a)).ToArray();

            for (int i = 0, j, m = (a - b) / 2, n = (a - c) / 2; i < b; ++i)
                for (j = 0; j = n & i + m < n + c &
                        j + m > n & j + m <= n + c ? "@" : "*");

            return r;
        };

        Console.WriteLine(string.Join("\n", f(6,4,2)) + "\n");
        Console.WriteLine(string.Join("\n", f(8,6,2)) + "\n");
        Console.WriteLine(string.Join("\n", f(12,6,2)) + "\n");

        Console.ReadLine();
    }
}

```

# Answer
> 3 votes
# JavaScript (ES6), ~~174~~ ~~170~~ 147 bytes

```
a=>b=>c=>(d=("#"[r="repeat"](a)+`
`)[r](f=a/2-b/2))+(e=((g="#"[r](f))+"*"[r](b)+g+`
`)[r](h=b/2-c/2))+(g+(i="*"[r](h))+"@"[r](c)+i+g+`
`)[r](c)+e+d

```

---

## Try it

```
fn=
a=>b=>c=>(d=("#"[r="repeat"](a)+`
`)[r](f=a/2-b/2))+(e=((g="#"[r](f))+"*"[r](b)+g+`
`)[r](h=b/2-c/2))+(g+(i="*"[r](h))+"@"[r](c)+i+g+`
`)[r](c)+e+d
oninput=_=>+x.value>+y.value&&+y.value>+z.value&&(o.innerText=fn(+x.value)(+y.value)(+z.value))
o.innerText=fn(x.value=12)(y.value=6)(z.value=2)
```

```
label,input{font-family:sans-serif;}
input{margin:0 5px 0 0;width:50px;}
```

```
a: <input id=x min=6 type=number step=2>b: <input id=y min=4 type=number step=2>c: <input id=z min=2 type=number step=2>

```

---

## Explanation

```
a=>b=>c=>            :Anonymous function taking the 3 integers as input via parameters a, b & c
(d=...)              :Assign to variable d...
("#"[r="repeat"](a)  :  # repeated a times, with the repeat method aliased to variable r in the process.
+`\n`)               :  Append a literal newline.
[r](f=a/2-b/2)       :  Repeat the resulting string a/2-b/2 times, assigning the result of that calculation to variable f.
+                    :Append.
(e=...)              :Assign to variable e...
(g=...)              :  Assign to variable g...
"#"[r](f)            :    # repeated f times.
+"*"[r](b)           :  Append * repeated b times.
+g+`\n`)             :  Append g and a literal newline.
[r](h=b/2-c/2)       :  Repeat the resulting string b/2-c/2 times, assigning the result of that calculation to variable h.
+(...)               :Append ...
g+                   :  g
(i=...)              :  Assign to variable i...
"*"[r](h)            :    * repeated h times.
+"@"[r](c)           :  @ repeated c times
+i+g+`\n`)           :  Append i, g and a literal newline.
[r](c)               :...repeated c times.
+e+d                 :Append e and d.

```

# Answer
> 3 votes
# Haskell, 126 bytes

```
f a b c=r[r["#*@"!!(v c+v b)|x<-[1..d a],let v k|x>a#k&&y>a#k=1|2>1=0]|y<-[1..d a]]where r x=x++reverse x;d=(`div`2);x#y=d$x-y

```

Try it online!

# Answer
> 3 votes
# , ~~70, 44~~, 42 bytes

```
Àé#@aÄÀG@b|{r*ÀG@c|{r@òjdòÍ.“.
ç./æ$pYHP

```

Try it online!

~~This is hideous. Eww.~~ Much better. Still not the shortest, but at least *somewhat* golfy.

Saved two bytes thanks to @nmjmcman101!

Hexdump:

```
00000000: c0e9 2340 61c4 c047 4062 7c16 7b72 2ac0  ..#@a..G@b|.{r*.
00000010: 4740 637c 167b 7240 f26a 64f2 cd2e 932e  G@c|.{r@.jd.....
00000020: 0ae7 2e2f e624 7059 4850                 .../.$pYHP

```

# Answer
> 2 votes
# MATL, ~~26~~ ~~23~~ ~~22~~ ~~20~~ 18 bytes

```
2/t:<sPtPh!Vt!2$X>

```

Input is a column vector `[a; b; c]`. Output uses characters `2`, `1`, `0`.

**Try it online!**

As an aside, it works for up to ten boxes, not just three. Here's an example with five boxes.

# Answer
> 2 votes
# C (gcc), 97 bytes

```
x,y;f(a,b,c){for(y=1-a;y<a;y+=2,puts(""))for(x=1-a;x<a;x+=2)printf(x/c|y/c?x/b|y/b?"#":"*":"@");}

```

Try it online!

# Answer
> 1 votes
# Mathematica, 49 bytes

```
Print@@@Fold[#~CenterArray~{#2,#2}+1&,{{}},{##}]&

```

Takes input `[c, b, a]`. The output is `a=1, b=2, c=3`.

### How?

```
Print@@@Fold[#~CenterArray~{#2,#2}+1&,{{}},{##}]&
                                                &  (* Function *)
        Fold[                        ,{{}},{##}]   (* Begin with an empty 2D array.
                                                      iterate through the input: *)
                                    &              (* Function *)
             #~CenterArray~{#2,#2}                 (* Create a 0-filled array, size
                                                      (input)x(input), with the array
                                                      from the previous iteration
                                                      in the center *)
                                  +1               (* Add one *)
Print@@@                                           (* Print the result *)

```

# Answer
> 1 votes
# Japt `-h`, 19 bytes

Takes input in reverse (`c,b,a`) and outputs an array of lines using `=` for the outer box, `!` for the middle one and `-` for the inner one.

```
Æç-
4Æ=Õû¦gXz)NÅgXz

```

Try it

```
Æç-\n4Æ=Õû¦gXz)NÅgXz     :Implicit input of integers U=c, V=b & W=a
Æ                        :Map the range [0,U)
 ç-                      :  Repeat "-" U times
   \n                    :Reassign to U
     4Æ                  :Map each X in the range [0,4)
       =                 :  Reassign to U ...
        Õ                :  Transpose U
         û               :  Centre pad each element with (1) to length (2)
          ¦              :    "!=" (1)
           g             :    Get character at index (1)
            Xz           :    X floor divided by 2 (1)
               )         :    End index (1)
                N        :    Array of all inputs, i.e. [U,V,W] (2)
                 Å       :    Slice off the first element (2)
                  gXz    :    As above (2)
                         :Implicit output of last element of resulting array

```

# Answer
> 0 votes
# Mathematica, 173 bytes

```
(d=((a=#1)-(b=#2))/2;e=(b-(c=#3))/2;z=1+d;x=a-d;h=Table["*",a,a];h[[z;;x,z;;x]]=h[[z;;x,z;;x]]/.{"*"->"#"};h[[z+e;;x-e,z+e;;x-e]]=h[[z+e;;x-e,z+e;;x-e]]/.{"#"->"@"};Grid@h)&

```

**input**

> \[12,6,2\]

# Answer
> 0 votes
# PHP\>=7.1, 180 bytes

In this case i hate that variables begin with a `$` in PHP

```
for([,$x,$y,$z]=$argv;$i<$x*$x;$p=$r%$x)echo XYZ[($o<($l=$x-$a=($x-$y)/2)&$o>($k=$a-1)&$p>$k&$p<$l)+($o>($m=$k+$b=($y-$z)/2)&$o<($n=$l-$b)&$p>$m&$p<$n)],($o=++$i%$x)?"":"\n".!++$r;

```

PHP Sandbox Online

# Answer
> 0 votes
# Python 2, 87 bytes

```
a,_,_=t=input();r=~a
exec"r+=2;print sum(10**x/9*10**((a-x)/2)*(r*r<x*x)for x in t);"*a

```

Try it online!

Arithmetically computes the numbers to print by adding numbers of the form `111100`. There's a lot of ugliness, probably room for improvement.

# Answer
> 0 votes
# Java 10, ~~265~~ ~~252~~ ~~218~~ ~~181~~ 172 bytes

```
 (a,b,c)->{int r[][]=new int[a][a],t=a-b>>1,u=a-c>>1,x=b*b;for(;x-->0;r[x/b+t][x%b+t]=1)if(x<c*c)r[x/c+u][x%c+u]=8;var s="";for(var q:r){for(int Q:q)s+=Q;s+="\n";}return s;}

```

-34 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it online.

```
(a,b,c)->{                  // Method with three integer parameters and String return-type
  int r[][]=new int[a][a],  //  Create a grid with dimensions `a` by `a`,
                            //  filled with 0s by default
      t=a-b>>1,             //  Calculate (a-b)/2
      u=a-c>>1,             //  Calculate (a-c)/2 as well
  x=b*b;for(;x-->0;         //  Loop `x` in the range (b*b, 0]:
    r[x/b+t][x%b+t]=1;      //   Fill the cells for the second square with 1s
    if(x<c*c)               //   And if `x` is smaller than c*c:
      r[x/c+u][x%c+u]=8;    //    Also start filling the center square cells with 8s
  var s="";                 //  Then create a return-String, starting empty
  for(var q:r){             //  Loop over the rows of the matrix:
    for(int Q:q)            //   Inner loop over the columns of the row:
      s+=Q;                 //    Append the current digit to the result-String
    s+="\n";}               //   Append a trailing new-line after every row
  return s;}                //  Return the result-String

```

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

Anonymous function returning a multi line string. Characters 0,1,2

```
(a,b,c)=>eval("for(o='',i=-a;i<a;o+=`\n`,i+=2)for(j=-a;j=c|i<-c|j>=c|j<-c)+(i>=b|i<-b|j>=b|j<-b)")

```

*Less golfed*

```
(a,b,c)=>{
  for(o='',i=-a;i<a;o+=`\n`,i+=2)
    for(j=-a;j=c|i<-c|j>=c|j<-c)+(i>=b|i<-b|j>=b|j<-b)
  return o
}

```

```
var F=
(a,b,c)=>eval("for(o='',i=-a;i<a;o+=`\n`,i+=2)for(j=-a;j=c|i<-c|j>=c|j<-c)+(i>=b|i<-b|j>=b|j<-b)")

function update()
{
  var [a,b,c]=I.value.match(/\d+/g)
  O.textContent=F(a,b,c)
}

update()

```

```
a,b,c <input id=I value='10 6 2' oninput='update()'>

```

# Answer
> 0 votes
# PHP \>= 5.6, 121 bytes

```
for($r=A;$p?:$p=($z=$argv[++$i])**2;)$r[((--$p/$z|0)+$o=($w=$w?:$z)-$z>>1)*$w+$p%$z+$o]=_BCD[$i];echo chunk_split($r,$w);

```

Run with `-nr` or test it online.

<sup>Combined loops again ... I love them!</sup>

**breakdown**

```
for($r=A;                           # initialize $r (result) to string
    $p?:$p=($z=$argv[++$i])**2;)    # loop $z through arguments, loop $p from $z**2-1 to 0
    $r[((--$p/$z|0)+$o=
        ($w=$w?:$z)                     # set $w (total width) to first argument
        -$z>>1)*$w+$p%$z+$o]            # calculate position: (y+offset)*$w+x+offset
        =_BCD[$i];                      # paint allowed character (depending on $i)
echo chunk_split($r,$w);            # insert newline every $w characters and print

```

# Answer
> 0 votes
# Canvas, 14 bytes

```
#*@Ｈ╶：＊ｌ⁸∔½：╋｝

```

Try it here!

---
Tags: code-golf, ascii-art
---


title: Splinter metagolf

text:
# Question
Title: Splinter metagolf
# The language

Splinter is an esoteric programming language where data is stored in 'splinters'. There are three different types of syntax:

* Simple character output: `\character`, outputs a character
* Splinter storage: `(splinter name){code}`, stores the code into the splinter with the correct name for later use as is. Note that these can be nested.
* Splinter reference: `(splinter name)`, evaluates the code of the splinter with the correct name.

`(splinter name)` just means the name, with no parentheses.

Here's an interpreter.

Splinter's computational class is a push-down automata, meaning it's one step behind Turing-Completeness. There are 26 splinters, one for each *capital* letter.

Because of the ability to store data in these 'splinters', Splinter programs can be interesting to compress.

Your challenge is to create a program that, when given a string as input, outputs a as-short-as-possible Splinter program that outputs that.

# Scoring

Your score is the combined length of your program run on the intended text of all of these:

Never gonna give you up
What a wonderful world
Hamlet's monologue
Something monkey-related
Gettysburg Adress
There was an old lady
Bears
House that Jack built
Buffalo buffalo buffalo

### The bear link is fixed now

# Answer
# Excel plus VBA, score 8210

## VBA code

```
Sub splinter()

    substart = Timer()
    Application.ScreenUpdating = False
    [F2] = [E2]
    For i = 65 To 90
        maxsavings = 0
        maxsavingsj = 0
        [L1] = i
        [G1] = 255
        maxmatch = [j1]
        For j = 2 To 254
            [G1] = j
            If [j1] = maxmatch Then Exit For

        If [L2] > maxsavings Then
                maxsavings = [L2]
                maxsavingsj = j
            End If
        Next j
        If maxsavings <= 0 Then Exit For
        [G1] = maxsavingsj
        [F2] = [M2]
    Next i
    Application.ScreenUpdating = True
    MsgBox (Timer() - substart & " seconds")
End Sub

```

## Excel Cells

```
D2=MID(B2,SEQUENCE(LEN(B2)),1)
E2=CONCAT(IF((CODE(D2#)<65)+(CODE(D2#)>90),"\","!")&D2#)
F1=LEN(F2)
G2=SEQUENCE(F1-G1+1)
H2=MID(F2,G2#,G1)
I1=XLOOKUP(J1,J2#,I2#)
I2=UNIQUE(FILTER(H2#,NOT((RIGHT(H2#)="\")+(RIGHT(H2#)="!")+NOT(ISERROR(FIND("?",H2#)))+ISERROR(MATCH(LEFT(H2#),O4:O31,0)))))
J1=MAX(J2#)
J2=COUNTIF(P2#,I2#)
L2=IFERROR(F1-LEN(M2),0)
M1=CHAR(L1)
M2=M1&"{"&I1&"}"&SUBSTITUTE(F2,I1,M1)
O2=SUBSTITUTE(F2,"!","\")
O4:O31= {\,!,A..Z}
P2=FILTER(H2#,NOT(ISERROR(FIND(LEFT(H2#),CONCAT(O4:O31)))))

```

Link to Spreadsheet

VBA doesn't work with Office online so the spreadsheet will have to be downloaded to run the macro.

The spreadsheet is set up where cell I1 contains the string of length G2 that will result in the greatest shortening of the string. Cell M2 shows the result of replacing the string in I1 with the letter in M1.

The VBA loops through the letters A through Z, looks for the value of G1 that results in the greatest reduction in size. There is a special case if it reaches the string limit of 255. After it finds the best change it copies the result in M2 to cell F2.

One quirk of Excel is certain matches are not case sensitive so I had to use !(letter) for capitals and convert back to \ at the very end.

* Rick Roll 772
* Wonderful 602
* Hamlet 1553
* Monkey 865
* Lincoln 1410
* Old Lady 462
* Bear 1932
* Jack 573
* Buffalo 41
> 3 votes

# Answer
# Python 3, score: ~~11069~~ 10495

This algorithm is very slow but I'm pretty sure it's close to optimal depending on the parameters *MIN\_SPLINTER\_SIZE* and *MAX\_SPLINTER\_SIZE*, though it takes quite long even when only set to 2, 120

```
import sys
import dataclasses

@dataclasses.dataclass
class Splinters:
    """
    The splinters class is the basic source code unit. Variables is a list of variables in order. Each variable is a
    string formatted like data. Variables may only contain variables with lower indexes than themselves.

    Data is a list. Each item may either be a literal string or a index of a variable to include.
    """
    variables: list
    data: list

    def reduce_text(self, text, pipe):
        """
        Print a section of test to the pipe. Variables will be replaced by the appropriate numbers. Should only
        be called from result()"""
        for text_part in text:
            if isinstance(text_part, str):
                pipe.write(''.join('\\' + i for i in text_part))
            else:
                pipe.write(chr(ord('A') + text_part))

    def result(self, pipe):
        """
        Output the formatted code to the pipe
        """
        for index, variable in enumerate(reversed(self.variables)):
            pipe.write(f'{chr(ord("A") + len(self.variables) - 1 - index)}{{')
            self.reduce_text(variable, pipe)
            pipe.write('}')
        self.reduce_text(self.data, pipe)

MINIMUM_SPLINTER_LENGTH = 2  # Minimum length of a splinter
MAX_SPLINTER_LENGTH = 120  # Maximum length of a splinter

def add_to_tree(tree, value):
    """
    Adds a single string to a tree
    :param tree: The tree dict object to add the string too
    :param value: The string value to add to the tree
    :return: None
    """
    k = tree
    for char in value:
        ok = k
        if char in k:
            n, k = ok[char]
            ok[char] = n + 1, k
        else:
            ok[char] = 1, {}
            n, k = ok[char]

def get_from_tree(tree, value):
    """
    Get a single value from the tree. Fixes duplicate items
    :param tree: The tree value
    :param value: The string to look up
    :return: How often this string has been added to the tree
    """
    k = tree
    n = 0
    for char in value:
        if char in k:
            n, k = k[char]
        else:
            return 0
    return n - sum(i[0] for i in k.values())

def add_string_to_tree(tree, string):
    """
    Adds every substring of a string to the tree
    :param tree: The tree
    :param string: The string to add
    :return: None
    """
    for substring in get_substrings(string):
        add_to_tree(
            tree,
            substring
        )

def recursively_add_splinter_to_dict(tree: dict, splinters: Splinters):
    """
    Adds every string in a splinter to a tree
    :param tree: The tree to add it to
    :param splinters: A splinter object to add to the tree
    :return: None
    """
    for variable in splinters.variables:
        for string in variable:
            if isinstance(string, str):
                add_string_to_tree(tree, string)
    for string in splinters.data:
        if isinstance(string, str):
            add_string_to_tree(tree, string)

def get_substrings(string):
    """
    Iterate over all valid substrings of a string
    :param string: The string
    :return: A generator over substrings between MIN_SPINTER_LENGTH and MAX_SPLINTER_LENGTH
    """
    for index, char in enumerate(string):
        for previous_value in range(max(0, index - MAX_SPLINTER_LENGTH), index - MINIMUM_SPLINTER_LENGTH + 2):
            yield string[previous_value:index + 1]

def get_splinter_substrings(splinter):
    """
    Iterate over all possible substrings in a splinter
    :param splinter: The splinters object
    :return: A generator over all the substrings
    """
    for variable in splinter.variables:
        for string in variable:
            if isinstance(string, str):
                yield from get_substrings(string)
    for string in splinter.data:
        if isinstance(string, str):
            yield from get_substrings(string)

def get_best_splinter(splinters: Splinters):
    """
    Find the best splinter in terms of bytes saved
    :param splinters: The splinters object
    :return: The most optimal substring to make a variable
    """
    tree = {}
    recursively_add_splinter_to_dict(tree, splinters)

    best_substring = None
    best_score = 0
    for substr in get_splinter_substrings(splinters):
        nrof_items = get_from_tree(tree, substr)
        if nrof_items >= 2:
            score = (nrof_items - 1) * len(substr)
            if score > best_score:
                best_substring = substr
                best_score = score
                best_number = nrof_items
    if best_score <= 3:
        return None
    return best_substring

def reduce_text(text, substring, index):
    """
    Replaces all instances of substring with the variable
    :param text: the text to look in
    :param substring: text to replace
    :param index: what it should be replaced with
    :return:
    """
    if not isinstance(text, str):
        return text,
    elif substring in text:
        return text[:text.index(substring)], index, *reduce_text(text[text.index(substring) + len(substring):],
                                                                 substring, index)
    else:
        return text,

def reduce_splinter(splinters: Splinters, substring):
    """
    Replaces all instances of a substring in a splinters object with a variable, and also add the variable.
    :param splinters:
    :param substring:
    :return: None, modifies splinters in place
    """
    new_variable_index = len(splinters.variables)
    for index, variable in enumerate(splinters.variables):
        splinters.variables[index] = [y for ys in variable for y in reduce_text(ys, substring, new_variable_index)]
    splinters.data = [y for ys in splinters.data for y in reduce_text(ys, substring, new_variable_index)]
    splinters.variables.append((substring,))

def get_splinters(data, pipe):
    """
    Performs 26 iterations of get_best_splinter, and outputs the result to pipe
    :param data: The input text
    :param pipe: The pipe to write the output to
    :return: None
    """
    splinters = Splinters(
        variables=[],
        data=[data, ]
    )
    for i in range(26):
        best_splinter = get_best_splinter(splinters)
        if best_splinter is None:
            break
        reduce_splinter(splinters, best_splinter)
    return splinters.result(pipe)

if __name__ == "__main__":
    with open(sys.argv[1]) as f:
        data = f.read().strip()
    get_splinters(data, sys.stdout)

```

Score breakdown:

```
processing:  hamlet.txt
     hamlet.txt 2013
processing:  wonderfull_world.txt
     wonderfull_world.txt 747
processing:  jaxt_house.txt
     jaxt_house.txt 754
processing:  getysburg.txt
     getysburg.txt 1803
processing:  give_you_up.txt
     give_you_up.txt 1028
processing:  bear.txt
     bear.txt 2472
processing:  monkey.txt
     monkey.txt 1103
processing:  old_lady.txt
     old_lady.txt 533
processing:  buffalo.txt
     buffalo.txt 42
total:  10495

```

Edit: Saved 601 bytes with bug when a splinter appeared near the end of a string
> 10 votes

# Answer
# Jelly, 76 bytes, score 8611

```
 ṡĠị$ḢṭFL’×ʋ¥LƊ€ɗⱮ20Ẏ1ị>3ƲƇḢÐṀṪṪ
”\;ⱮØ{jWƊ};"œṣɗj¹;@ɗ‘ɼịØA¤ɗŻṛ?Ç$1ịȧ®<26¤Ʋ¿ḟ0

```

Try it online!

A full program taking a string and printing the Splinter program. The TIO link can be used for all 9 required test cases by modifying the first argument from 1 to 9 for the relevant case.

1. We're no strangers to love -\> 997
2. I see trees of green, red roses, too, -\> 611
3. To be, or not to be: that is the question: -\> 1553
4. sandor weores monkeyland -\> 864 l
5. Four score and seven years ago our fathers brought forth -\> 1400
6. There was an old lady who swallowed a fly. -\> 489
7. The other day, -\> 1965
8. This is the house that Jack built. -\> 691
9. Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo -\> 41
> 7 votes

# Answer
# Python 3, score: 18074

```
import sys

data = sys.stdin.read()
o = "".join("\\" + c for c in data)

splinters = ""
kt = 65

for _ in range(26):
	for l in range(len(data) // 2, -1, -1):
		for k in range(len(data) - l):
			q = data[k:k + l]
			if "\0" in q: continue
			if data.count(q) > 1:
				spc = "".join("\\" + c for c in q)
				splinters += chr(kt) + "{" + spc + "}"
				data = data.replace(q, "\0")
				o = o.replace(spc, chr(kt))
				kt += 1
				break
		else:
			continue
		break
	else:
		continue
	break

print(len(splinters + o), file = sys.stderr)

print(splinters + o)

```

Try it online!

* NGGYU: 2103
* WAWW: 944
* TBONTB: 2724
* MONKE: 1579
* 4S&7YA: 2525
* TWAOL: 1343
* BEAR: 4245
* TITHTJB: 2540
* BBBBBBB: 71

This is just an extremely naive solution that takes the longest block and splinters it each time. No nested splintering is implemented. It's already quite slow.
> 4 votes

# Answer
# Python 3, score: 24252

```
# splinter

def splinter(inp):
    print(*["\\" + x for x in inp], sep = "")

splinter("Hello, World!")

```

Try it online!

Just a baseline program, appends a "\\" to each character in the input, although for the input, I noticed the bear program was just a duplicate of the old lady one, so I omitted that. If I got the score wrong, let me know and I'll fix it.

(Edit) Updated to include bear text + I doubled the char count not the byte count because the Gettysburg text has some unicode in it.
> 3 votes

# Answer
# Excel, score 13524

```
D2=MID(B2,SEQUENCE(LEN(B2)),1)
E2=CODE(D2#)
F2=SORT(UNIQUE(E2#))
G2=COUNTIF(E2#,F2#)
H2=SORTBY(F2#,$G$2#,-1)
I2=IF(ROW(H2#)<28,CHAR(ROW(H2#)+63),"\"&CHAR(H2#))
J2=XLOOKUP(E2#,H2#,I2#)
K2=I2:I27&"{\"&CHAR(H2:H27)&"}"
L2=CONCAT(K2#,J2#)

```

Link to Spreadsheet

This counts the occurrence of each character, assigns the 26 most common to splinters and the rest are set to `\character`.

* Rick Roll 2049
* Wonderful 766
* Hamlet 1685
* Monkey 1082
* Lincoln 1602
* Old Lady 1304
* Bear 2437
* Jack 2496
* Buffalo 103
> 3 votes

# Answer
# , score 8298

```
find_best_split_for_length <- function(text, length, randomise = FALSE) {
  starts <- 1:(nchar(text) - length + 1)
  backslashes <- cumsum(nchar(strsplit(text, "\\", fixed = TRUE)[[1]]) + 1)
  backslashes <- backslashes[-length(backslashes)]
  starts <- starts[!(((starts - 1) %in% backslashes) | ((starts + length - 1) %in% backslashes))]
  text_split <- vapply(starts, function(start)substr(text, start, start + length - 1), character(1))
  groups <- split(seq_len(length(text_split)), text_split)
  group_savings <- (lengths(groups) - 1L) * vapply(groups, function(group)nchar(text_split[[group[1]]]) - 1L, integer(1))
  best_saving <- max(c(group_savings, 0L))
  which_best <- which(group_savings == best_saving)
  if (randomise) {
    best_split <- which_best[sample(length(which_best), 1)]
  } else {
    best_split <- which_best[length(which_best)]
  }
  list(saving = best_saving, split = names(best_split))
}

find_best_split <- function(text, max_length = 70, randomise = FALSE) {
  splits <- lapply(1:min(nchar(text) %/% 2, max_length), find_best_split_for_length, text = text, randomise = randomise)
  split_savings <- vapply(splits, function(split) split$saving, integer(1))
  best_splits <- which(split_savings == max(split_savings))
  if (randomise) {
    best_split <- best_splits[sample(length(best_splits), 1)]
  } else {
    best_split <- best_split[length(best_split)]
  }
  splits[[best_split]]
}

splinter_encode <- function(text, max_length = 70, randomise = FALSE) {
  text <- gsub("(.)", "\\\\\\1", text)
  i <- 1
  done <- FALSE
  while (i <= 26 && !done) {
    best_split <- find_best_split(text, max_length, randomise = randomise)
    if (best_split$saving < 5) {
      done <- TRUE
    } else {
      # cat(best_split$split, "\n\n", sep = "")
      placeholder <- intToUtf8(64 + i)
      text <- paste0(placeholder, "{", best_split$split, "}", gsub(best_split$split, placeholder, text, fixed = TRUE))
      i <- i + 1
    }
    # cat(nchar(text), "\n\n", sep = "")
  }
  text
}

splinter_multilength_encode <- function(text, max_lengths = c(seq(10, 70, 5))) {
  encodes <- vapply(max_lengths, splinter_encode, text = text, character(1))
  encodes[which.min(nchar(encodes))]
}

splinter_randomised_encode <- function(text, min_max_length = 10, max_length = 70, n_tries = 10, seed = NULL) {
  if (!is.null(seed)) {
    set.seed(seed)
  }
  seeds <- sample(2^31, n_tries)
  encodes <- sapply(seeds, function(cur_seed) {
    set.seed(cur_seed)
    splinter_encode(text, max_length = if (min_max_length == max_length) min_max_length else sample(min_max_length:max_length, 1), randomise = TRUE)
  })
  which_smallest <- which.min(nchar(encodes))
  list(
    seed = seeds[which_smallest],
    min_max_length = min_max_length,
    max_length = max_length,
    length = nchar(encodes[which_smallest]),
    encoded_text = encodes[which_smallest]
  )
}

```

Try it online!

A recoded version of my Jelly answer, partly since it runs quicker (and so it's possible to try more possibilities for the max length) and partly for those wondering how the Jelly answer worked.

The score above (and detailed below) is based on using the `splinter_randomised_encode()` function and quite a lot of tries to give the following.

### We're no strangers to love -\> 863

```
Z{\s}Y{O\dE}X{\r}W{E\g}V{\
}U{E\kON\w}T{E\hN\wE\I\'\mE\fGG\l\iO\gV}S{\a}R{V\IE\j\uZPE\wSOOSEPG\l\lKD}Q{\i\vGFE\u\p}P{\t}O{\n}N{\o}M{GS\c\hENP\hGXE\fNXEZNE\lNO\gV\YN\uXE\hGSJE\p\lS\yE\iP}L{V\(\ON\h\)A\g\i\vG\,EOG\vGXWNOOSW\i\vGV\(\GQ\)}K{FT\GNPPSE\mS\kGFE\uO\dGXZPSO\d}J{XP\'ZE\bGGOES\c\h\iO\gIP\hGWS\mGESY\wG\'XGWNOOS}I{H\bNP\hUE\w\hSP\'ZE\bGGOWN\iO\gENOV\WGUE}H{E\b\uPV\YN\u\'XGEPNNEZ\h\yEPNEZS\yE\iPV\IOZ\i\dGE\wGE}G{\e}F{E\yN\u}E{\ }D{VCN\d\b\yGAPG\l\lESE\l\iGESY\h\uXPF}C{A\gQA\lGPFE\dN\wOAX\uB\yAZS\yWN}B{OESXN\uYSY\dGZGXPFA\mS\kGFE\cX}A{V\NG\vGXWNOOSE}\WG\'XGEONEZPXSO\gGXZEPNE\lN\vGV\YN\uUEP\hGEX\u\lGZESYZNE\dNE\IV\AE\f\u\l\lE\cN\m\m\iP\mGOP\'ZE\w\hSPE\I\'\mEP\h\iO\k\iO\gEN\fV\YN\uE\wN\u\l\dO\'PWGPEP\h\iZ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}O{\ }N{T\hSTO}M{A\fSV\m\eVOZW\wX\n\gO\hXZO\cP\k\e\pTJ}L{ST\eA\mSUT}K{\wWVVXRA\cSTC\kXUURAVSTO}J{AVWWZT\eVON\cVW\wROX\nA\mP\wW\k\eAHE}I{\
\
\T\hXZOXZ}H{\j\u\d\g\eOSUUOZ\hS\v\e\nYOZ\hP\mSVVXRFG}G{X\d\e\nOSUUO\fWVUP\mXU\kRD}F{A\mS\nOSUUOTSTT\eVRYOTP\kXZZRA\mS}E{CKCLB}D{A\cW\wO\wXT\hA\cV\u\m\pURO\hPTWZZRA\dW\gO}C{\
\T\hSTO}B{CUS\yOX\nQ}A{OT\h\eO}\T\hXZOXZQIA\mSUTOBIAVSTOCLBIA\cSTOC\kXUURAVSTCLOBIA\dW\gOEIDEIA\mSGNKNLBIFGNKNLBIAHEIJIMIA\hWVZ\eYA\hW\u\n\dYA\hP\b\eUW\n\gROTWM

```

### Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo -\> 41

```
C{A\ \BA}B{\u\f\f\a\l\o}A{B\ \bB}\BC\ \bC

```
> 3 votes

---
Tags: code-challenge, metagolf, test-battery
---


title: KEYBOARD FOR MONKE!

text:
# Question
Title: KEYBOARD FOR MONKE!
## Flavortext

So...this is awkward. It seems I accidentally turned into a monkey last night after eating one too many banana sundaes. This has made many things inconvenient, especially typing. You see, monkeys only need the following characters: uppercase letters (`A-Z`), space, comma (`,`), exclamation mark (`!`), and question mark (`?`). For all other purposes, the Stack Overflow keyboard is enough for copy-pasting a.k.a. monkey see, monkey do. Furthermore, since we are superior to humans and do not have opposable thumbs, we can use our thumbs for more than just the space bar. Finally, monkeys absolutely hate typing consecutive characters with the same finger, so typing combos such as "dee" and "un" on a QWERTY keyboard is very annoying.

## Task

That's why I've made a new ergonomic keyboard that looks like this, and your task is to assign its keys.

Left paw Right paw

Every finger is used for the three keys in one column and only those keys (so the left pinky would be used for the first column and the right thumb for the sixth).

You will be given a string representative of what I usually type, and will design a keyboard according to the following requirements:

* It will be in the shape of the blank keyboard above.
* It will contain the characters `ABCDEFGHIJKLMNOPQRSTUVWXYZ ,!?` (note the space) and only those characters.
* None of the strings in the input will cause me to type consecutive characters using the same finger.

Here's an example:

```
Input: 'I LIKE BANANAS! WHERE BANANA?!'

```

A valid keyboard would be:

``I````L````A````N````R`` ``D````F````G````J````M``
``E````K````!````S````?`` ``Z````O````P````Q````T``
``B````Y````W````H````C`` ``,````U````V````X``

An invalid keyboard would be:

``I````E````A````N````R`` ``D````F````G````J````M``
``L````K````!````S````?`` ``Z````O````P````Q````T``
``B````W````H````C`` ``,````U````V````X````Y``

This violates the third requirement, because to type `LI` in `I LIKE BANANAS!`, I would have to use my left pinky twice for consecutive characters: once for `L` on the middle row and once for `I` on the top row. I would also have to use my left ring finger twice while typing `KE`.

## Rules

* The input will always consist only of the characters `ABCDEFGHIJKLMNOPQRSTUVWXYZ ,!?`, just like the keyboard.
* You may assume that a valid keyboard exists for the input.
* You may input and output in any reasonable format.

## Test cases

The output of each test case is formatted the same as the examples above, but without `<kbd>` and spaces between the two paws' keys. An underscore (`_`) is used instead of a space for clarity.

```
'Input'

Keyboard

'I HAVE A TAIL AND YOU DO NOT! WHY?! I PITY YOU!'

I_HAVETLND
Y?OUWPBCF,
!GJKMQRSXZ

'REJECT MODERNITY, RETURN TO MONKE! EAT BANANA!'

RECOD!BQSX
JNKI,FGAV?
TM_YUHLPWZ

```

Here is a validator kindly provided by tsh.

# Answer
# Perl 5, 134 bytes

```
sub f{@k=(A..Z,$",',','!','?');splice@k,rand@k,0,pop@k for 1..1e3;@p{@k}=0..29;join('',map$p{$_}%10,split//,$_[0])=~/(.)\1/?f(pop):@k}

```

Try it online!

```
sub f{
  @k=(A..Z,' ',',','!','?');          #put valid keys in array @k
  splice@k,rand@k,0,pop@k for 1..1e3; #shuffle array @k in random order
  @p{@k}=0..29;                       #assign a position 0-29 to each key
  join('',map$p{$_}%10,split//,$_[0]) #make string of each input char mapped...
                                 #to its key position modulus 10 = column number
    =~ /(.)\1/                   #check if two adjacent column numbers exists...
                                 #for current input
    ?  f(pop)                    #if yes, try new keyboard on same input
    :  @k                        #if no, return current random valid keyboard...
                                 #as an array of 30 chars
}

```

This approach tries random keyboards until it hits a valid one for the current input string. In a test of 1000 runs of both the given test strings, a valid keyboard was found at the 20th trial on average.
> 10 votes

# Answer
# Jelly, 18 bytes

```
30Œ!ðiⱮ’:3nƝẠðƇḢs3

```

Try It Online!

-1 byte thanks to caird coinheringaahing

This should work in theory. However, it is \\$O(N! \times NM)\\$ where \\$N\\$ is the size of the alphabet and \\$M\\$ is the size of the input.

You can try this for a restricted alphabet of "ABCDEF" here.

```
30Œ!ðiⱮ’:3nƝẠðƇḢs3   Main Link; accept a list of numbers from 1 to 30 on the left
30Œ!                 Get all permutations of 1..30
    ð        ðƇ      Filter to keep; map over a dyad, which feeds the input to the right
     iⱮ              Get the index of each input in the permutation
       ’             Decrement to get into the range 0..29
        :3           Floor divide by 3
          nƝ         For each overlapping pair, check if the column indices are inequal
            Ạ        Are all inequal? (Filter will keep these)
               Ḣ     Take the first valid permutation
                s3   Divide it into non-overlapping chunks of length 3

```

Borrowing Kjetil's idea to use random permutations (which I actually had, but I wasn't sure if it'd be valid), we get the following solution, which is way faster (as in you can actually run it):

# Jelly, 18 bytes

```
iⱮ³’:3=ƝẸ
30RẊÇ¿s3

```

Try It Online!

-1 byte thanks to caird coinheringaahing by observing that we can bind the input to the right of the index link to avoid needing a combinator that we would've needed from binding it to the link reference call in the while loop.

You can translate test cases from words to numbers here and translate the output back to text here.

```
iⱮ³’:3=ƝẸ    Helper Link; check if a permutation is invalid
iⱮ³          Get the index of each input in the permutation
   ’         Decrement to get into the range 0..29
    :3       Floor divide by 3
      =Ɲ     For each overlapping pair, check if the column indices are equal
        Ẹ    Are any equal?
30RẊÇ¿s3     Main Link
30R          1..30
     ¿       While
    Ç        The permutation is invalid
   Ẋ         Shuffle it
      s3     Divide it into non-overlapping chunks of length 3

```

Unfortunately, I have to explicitly bind the input as the right argument to `ç` because otherwise the while loop will Fibonacci.
> 4 votes

# Answer
# Haskell, 181 bytes

```
import Data.List
f[]=[]
f(a:b:c:x)=[a,b,c]:f x
g(a:b:x)=(a,b):g(b:x)
g _=[]
q s=head$filter(\x->not$any(\(a,b)->any(\r->a`elem`r&&b`elem`r)$f x)$g s)$permutations$['A'..'Z']++"?!, "

```

Try it online

Goes through all permutations and picks the first one that does not have any adjacent characters on the same column. Output is flattened. It should work in theory with an awful complexity of O(SNS!) where S the size of the alphabet and N the length of input.
> 4 votes

# Answer
# JavaScript (ES6), 136 bytes

*-16 bytes thanks to @tsh*

Expects an array of characters. Returns a random keyboard as an array of 3 strings.

```
f=a=>a.some(c=>p==(p=k.indexOf(c)%10),p=k=[...'ABCDEFGHIJKLMNOPQRSTUVWXYZ ,!?'].sort(_=>Math.random()-.5))?f(a):k.join``.match(/.{10}/g)

```

Try it online!
> 3 votes

# Answer
# Python 3, 163 bytes

```
s=input()
l=k=''.join({}.fromkeys(s).keys())
while any(x+y in l for x,y in zip(k,k[1:])):k=''.join({*k})
print(k+''.join({*'ABCDEFGHIJKLMNOPQRSTUVWXYZ ,!?'}-{*k}))

```

Try it online!

Returns keyboard transposed flat and joined
> 3 votes

---
Tags: code-golf, string, keyboard
---


title: Fold a string into a triangle

text:
# Question
Title: Fold a string into a triangle
Given a string whose length is divisible by 4, make a triangle as demonstrate below.

If the string is `abcdefghijkl`, then the triangle would be:

```
   a
  b l
 c   k
defghij

```

If the string is `iamastringwithalengthdivisiblebyfour`, then the triangle would be:

```
         i
        a r
       m   u
      a     o
     s       f
    t         y
   r           b
  i             e
 n               l
gwithalengthdivisib

```

If the string is `thisrepresentationisnotatriangle`, then the triangle would be:

```
        t
       h e
      i   l
     s     g
    r       n
   e         a
  p           i
 r             r
esentationisnotat

```

## Notes

* The string will only consist of characters from `a` to `z`.
* Leading/Trailing whitespaces and newlines are allowed as long as the shape is not broken.
* A list of strings as output is allowed.

This is . Shortest answer in bytes wins. Standard loopholes apply.

# Answer
> 7 votes
# Charcoal, ~~25~~ ~~22~~ 21 bytes

```
≔÷Ｌθ⁴λ↙…θλ→✂θλ±λ↖✂θ±λ

```

Try it online! Link is to verbose version of code. Simply slices the string into three parts and prints them in the appropriate directions. Edit: Saved 3 bytes by using integer division and slicing. Saved a further byte by using `CycleChop` instead of `Slice` for the head of the string. Edit: Charcoal now supports drawing arbitrary text along the edge of a polygon, simplifying the code to 12 bytes:

```
ＧＨ↙→→↖⊕÷Ｌθ⁴θ

```

Try it online! Link is to verbose version of code.

# Answer
> 6 votes
## JavaScript (ES6), ~~119~~ ~~117~~ ~~108~~ 105 bytes

```
s=>(l=s.length/4,S=' ',g=([c,...s],p)=>S.repeat(l)+c+(l--?p+s.pop()+`
`+g(s,p?p+S+S:S):s.join``))(s+S,'')

```

### Formatted and commented

```
s => (                            // given the input string s:
  l = s.length / 4,               // l = length of side edge - 1
  S = ' ',                        // S = space (defining S costs 6 bytes but saves 7)
  g = (                           // g = recursive function which takes:
       [c,                        //   - c = next character
           ...s],                 //   - s = array of remaining characters
                  p) =>           //   - p = middle padding string
    S.repeat(l) + c + (           // append left padding + left character
      l-- ?                       // if side edges are not complete:
        p + s.pop() + '\n' +      //   append middle padding + right character + Line Feed
        g(s, p ? p + S + S : S)   //   and do a recursive call with updated middle padding
      :                           // else:
        s.join``                  //   append all remaining characters and stop recursion
    )                             //   (this is the bottom edge)
  )(s + S, '')                    // initial call to g()

```

### Test cases

```
let f =

s=>(l=s.length/4,S=' ',g=([c,...s],p)=>S.repeat(l)+c+(l--?p+s.pop()+`
`+g(s,p?p+S+S:S):s.join``))(s+S,'')

console.log(f('abcdefghijkl'))
console.log(f('iamastringwithalengthdivisiblebyfour'))
console.log(f('thisrepresentationisnotatriangle'))
```

# Answer
> 6 votes
# 05AB1E, 23 bytes

```
ćsIg4÷GćsÁćsŠN·<ú«s}».C

```

Try it online!

**Explanation**

```
ć                        # extract head of input
 s                       # swap the remaining string to top of stack
  Ig4÷G                  # for N in [1...len(input)/4-1] do:
       ć                 # extract head
        sÁ               # swap remaining string to top of stack and rotate right
          ć              # extract head
           sŠ            # reorder stack as tail, head, remaining
             N·<ú        # prepend N-1 spaces to tail
                 «s      # concatenate with head and swap remaining string to top
                   }     # end loop
                    ».C  # join by newlines and center

```

# Answer
> 4 votes
# C#, 260 bytes

```
namespace System{using static Console;class P{static void Main(){var d=ReadLine();int e=d.Length/4,x=e,y=0,g=0,i=0;Action<int,int>a=(p,q)=>{SetCursorPosition(p,q);Write(d[g++]);};for(;i<e;i++)a(x--,y++);for(i=0;i<e*2;i++)a(x++,y);for(i=0;i<e;i++)a(x--,y--);}}}

```

Really wanted to use `SetCursorPosition`.

Ungolfed:

```
namespace System {
    using static Console;

    class P {
        static void Main() {
            var d = ReadLine();
            int e = d.Length / 4, x = e, y = 0, g = 0, i = 0;
            Action<int, int> a = (p, q) => { SetCursorPosition(p, q); Write(d[g++]); };
            for (; i < e; i++)
                a(x--, y++);
            for (i = 0; i < e * 2; i++)
                a(x++, y);
            for (i = 0; i < e; i++)
                a(x--, y--);
        }
    }
}

```

# Answer
> 3 votes
# Mathematica, 164 bytes

```
(b=Length[c=Characters@#];k=Column[#,Alignment->Center]&;T=Table;k@{#&@@c,k@T[""<>{c[[i+2]],T[" ",2i+1],c[[-i-1]]},{i,0,(a=b/4)-2}],""<>T[c[[i]],{i,a+1,b/2+1+a}]})&

```

**input**

> \["iamastringwithalengthdivisiblebyfour"\]

# Answer
> 3 votes
# GNU sed, ~~178~~ ~~158~~ 132 + 1 = 133 bytes

+1 byte for `-r` flag.

```
s/(.)(.*)(.)/ \1\n\2;\3/
:
s/( *)(.\n.)(.*)(...);(.*)(.)/\1\2\1  \6\n\3;\4\5/m
t
:A
s/(.*\n)( *)(.*);/ \2;\1\2\3/m
tA
s/. (.)$/\1/gm

```

Try it online!

## Explanation

In previous revisions I used a lot of bytes dealing with math, special cases, and cleanup, even though intuitively I was sure they could be avoided. I've since managed to do so, mostly.

Suppose we have the input `abcdEFGHIJKLMnop`. The letters `EFGHIJKLM` will be the bottom of the triangle, so I've capitalized them as a visual aid.

First we prepare the input by putting the first character on its own line (preceded by a space) and inserting a cursor (`;`) before the last character:

```
s/(.)(.*)(.)/ \1\n\2;\3/

```

Now we have:

```
 a
bcdEFGHIJKLMno;p

```

Now, in a loop, we're going to do a few things to the last line: 1. Copy the spaces from the previous line and insert them after the first character, plus two; 2. Move the last character to right after the spaces, followed by a newline; and 3. Move the cursor three characters to the left.

```
:
  s/( *)(.\n.)(.*)(...);(.*)(.)/\1\2\1  \6\n\3;\4\5/m
  t

```

Here's the result of each iteration:

```
 a
b   p
cdEFGHIJKL;Mno

 a
b   p
c     o
dEFGHI;JKLMn

 a
b   p
c     o
d       n
EF;GHIJKLM

```

You can see the pyramid begin to take shape. You can also see what the cursor was for: In each iteration it moved left three characters, and when there are no longer three characters to its left, it breaks the loop, which happens to be just when we've reached the "bottom" of the pyramid.

Now we're going to do a similar operation but in reverse. In a loop, we'll copy the spaces from the beginning of the line with the cursor to the beginning of the preceding line, plus one, in the process moving the cursor up to that line.

```
:A
  s/(.*\n)( *)(.*);/ \2;\1\2\3/m
  tA

```

Here are a couple iterations and the end result:

```
 a
b   p
c     o
 ;d       n
EFGHIJKLM

 a
b   p
  ;c     o
 d       n
EFGHIJKLM

...

    ; a
   b   p
  c     o
 d       n
EFGHIJKLM

```

We're all done now, except for some extra characters: A `;` and extra space on the first line, and two spaces in the "middle" of the pyramid on the next three lines. A simple substitution gets rid of them:

```
s/. (.)$/\1/gm

```

All done!

```
    a
   b p
  c   o
 d     n
EFGHIJKLM

```

# Answer
> 3 votes
# Python 3, 120 bytes

First golf, figured I might as well learn some Python along the way.

```
a=input()
l=len(a)//4
print(l*" "+a[0])
for i in range(1,l):print((l-i)*" "+a[i]+(2*i-1)*" "+a[4*l-i])
print(a[l:3*l+1])

```

Try it online!

**Explanation:**

The first character is printed by itself after `len(a)//4` spaces, then the first and last `i`-th characters starting from the second are printed, separated by `2*i - 1` spaces.

Finally, the remaining substring is printed.

# Answer
> 2 votes
# Python 2, ~~100 97~~ 96 bytes

* Jacoblaw saved 1 byte: integer division is unnecessary

```
a=input()+" "
k=j=len(a)/4
while j:print j*" "+a[0]+(2*(k-j)-1)*" "+a[-1];a=a[1:-1];j-=1
print a

```

Try it online!

### Explanation:

One smart thing I've done here is padded the input with a space at the end, such that the first character pairs with it and this can be pushed into the loop (and since trailing whitespaces are allowed)

```
abcdefghijkl[space]
To print [0] [-1]            Output=>[spaces]a[another_calculated_spaces(=0 here)][space]
Strip at both ends(a[1:-1])
bcdefghijkl
To print [0] [-1]            Output=>[spaces]b[another_calculated_spaces]l
Strip at both ends(a[1:-1])
and so on.

```

The number of loops to follow is associated with `len(word)//4`. In the final step, the whole remaining string is printed(this forms the base of the triangle). The spaces follow a simple pattern; the first set of spaces go-on decreasing by 1, while second set of spaces go on increasing by 2.

# Answer
> 2 votes
# Haskell, 136 bytes

```
i#x=x<$[1..i]
f s|let h=div l 4;l=length s=unlines$[(h-i)#' '++(s!!i):(2*i-1)#' '++[(s++" ")!!(l-i)]|i<-[0..h-1]]++[drop h$take(l-h+1)s]

```

Try it online!

# Answer
> 2 votes
# C#, 172 bytes

```
int i=0,n=s.Length;var p="";p=new string(' ',n/4)+s[i]+"\r\n";for(i=1;i<n/4;i++){p+=new string(' ',n/4-i)+s[i]+new string(' ',i*2-1)+s[n-i]+"\r\n";}p+=s.Substring(i,n/2+1);

```

Try it online!

# Answer
> 2 votes
# C 225 bytes

```
p(c){putchar(c);}S(n){while(n--)p(' ');}main(int c,char**v){int i= strlen(v[1]),n=i/4,r;char*s=v[1],*e=&s[i-1];S(n);p(*s++);p('\n');for (r=1;r<n;r++){S(n-r);p(*s++);S(2*r-1);p(*e--);p('\n');}e++;while (s!=e)p(*s++);p('\n');}

```

**explained**

```
p(c){putchar(c);}        // p is alias for putchar
S(n){while(n--)p(' ');}  // S prints n spaces
main(int c,char**v){
    int i= strlen(v[1]), // counter
        n=i/4,           // num rows in figure - 1
        r;               // current row
    char*s=v[1],         // start char
        *e=&s[i-1];      // end char
    S(n);p(*s++);p('\n');// print first row
    for (r=1;r<n;r++){
        S(n-r);p(*s++);S(2*r-1);p(*e--);p('\n'); // print middle rows
    }
    e++;while (s!=e)p(*s++);p('\n'); // print last row
}

```

# Answer
> 2 votes
# Ruby, 106 bytes

```
i=-1
s= ~/$/
sub /./,"#{' '*l=s/4}\\0
"
(l-1).times{sub /^(\w)(.*)(.)/,"#{' '*l-=1}\\1#{' '*i+=2}\\3
\\2"}

```

Try it online!

# Answer
> 1 votes
# Octave, 87 bytes

```
@(s,x=(n=nnz(s))/4)[[' ';flip(diag(s(1:x))')]' [' ';diag(s(n:-1:n-x+2))];s(x+1:n-x+1)];

```

\*In a windows machine the above code produces the correct result however in tio I added some code to correct it.

Explanation:

```
[' ';flip(diag(s(1:x))')]'        %left side
[' ';diag(s(n:-1:n-x+2))]         %right side
s(x+1:n-x+1)                      %bottom side

```

Try it online!

# Answer
> 1 votes
# PHP\>=7.1, 122 Bytes

```
for(;$i*2<$w=strlen($a=$argn)/2;$e=$a[-++$i])echo str_pad(str_pad($a[$i],$i*2).$e,$w+1," ",2),"
";echo substr($a,$i,$w+1);

```

PHP Sandbox Online

# PHP\>=7.1, 124 Bytes

```
for(;$i*2<$w=strlen($a=$argn)/2;$e=$a[-++$i],$s.=$s?"  ":" ")echo str_pad("",$w/2-$i)."$a[$i]$s$e
";echo substr($a,$i,$w+1);

```

PHP Sandbox Online

# Answer
> 1 votes
# AWK, 129 bytes

```
{n=split($0,a,"")
printf"%"(w=n/4+1)"s\n",a[++i]
for(;++i<w;)printf"%"(w-i+1)"s%"2*i-2"s\n",a[i],a[n-i+2]
$0=substr($0,i,i+w-1)}1

```

Try it online!

I should think this could be golfed a bit more, just not seeing it.

# Answer
> 1 votes
# Retina, 99 bytes

```
^(.)(?=(....)+)
$#2$*  $1¶$#2$*
( ( *).)(.*)(.)$
$1 $4¶$2$3
+`(( +).¶ ( *).)(.*)(.)$
$1$2  $5¶$3$4

```

Try it online! Explanation: The first two stages generate the first two lines, but after that no special-casing is necessary and each subsequent line can be generated automatically:

```
thisrepresentationisnotatriangle

        t
       hisrepresentationisnotatriangle

        t
       h e
      isrepresentationisnotatriangl

        t
       h e
      i   l
     srepresentationisnotatriang

...

        t
       h e
      i   l
     s     g
    r       n
   e         a
  p           i
 r             r
esentationisnotat

```

# Answer
> 1 votes
# Java 11, ~~213~~ ~~211~~ 178 bytes

```
s->{int n=s.length()/4,i=1;var r=" ".repeat(n)+s.charAt(0)+"\n";for(;i<n;r+=" ".repeat(n-i)+s.charAt(i)+" ".repeat(i*2-1)+s.charAt(n*4-i++)+"\n");return r+s.substring(i,n*2-~i);}

```

-2 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it online.

```
s->{                               // Method with String parameter and String return-type
  int n=s.length()/4,              //  The length of the input divided by 4
      i=1;                         //  And an index-integer, starting at 1
  var r=                           //  Result-String which starts as:
        " ".repeat(n)              //   Leading spaces
        +s.charAt(0)               //   + the first character
        +"\n";                     //   + a new-line
  for(;i<n;                        //  Loop `i` in the range [1, `n`):
      r+=                          //   And append the result-String with:
         " ".repeat(n-i)           //    Leading spaces
         +s.charAt(i)              //    + the character of the left diagonal line
         +" ".repeat(i*2-1)        //    + center spaces
         +s.charAt(n*4-i++)        //    + the character of the right diagonal line
         +"\n");                   //    + a new-line
  return r                         //  Return the result-String
         +s.substring(i,n*2+i+1);} //   + the bottom part of the triangle

```

# Answer
> 1 votes
# Vyxal `C`, 29 bytes

```
4/÷ḣ‟+^ṘYṘ2ẇṘḣð£ƛ¥j¥ðd+£;J^JJ

```

Try it Online!

No canvas builtins! Because Vyxal doesn't have those. ?

-9 thanks to Aaron Miller.

# Answer
> 0 votes
# Perl 5, 76 bytes

74 bytes of code +2 for `-F`

```
say$"x($l=@F/4),shift@F;say$"x$l,shift@F,$"x($#i+=2),pop@F while--$l;say@F

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 14 bytes

```
g4/>x<‚ĆI527SΛ

```

Try it online (no test suite since there isn't a way to clean the Canvas).

**Explanation:**

```
g         # Take the length of the (implicit) input
          #  i.e. "thisrepresentationisnotatriangle" → 32
 4/       # Divide it by 4
          #  i.e. 32 → 8
   >      # Increase it by 1
          #  i.e. 8 → 9
    x     # Double it (without popping the value itself)
          #  i.e. 9 → 9 and 18
     <    # Decrease this doubled value by 1
          #  i.e. 18 → 17
      ‚   # Pair them together: [length/4+1, (length/4+1)/2-1]
          #  i.e. 9 and 17 → [9,17]
       Ć  # Enclose it, appending its head to itself: [l/4+1, (l/4+1)/2-1, l/4+1]
          #   i.e. [9,17] → [9,17,9]
I         # Push the input-string again
527S      # Push 527 as digit-list: [5,2,7]
Λ         # Use the Canvas builtin with these three arguments
          # (after which the result is output implicitly)

```

*Canvas explanation:*

The Canvas builtin takes three arguments:
1. The lengths of the lines to 'draw', which in this case is the list \\$\[\frac{l}{4}+1, \frac{\left(\frac{l}{4}+1\right)}{2}-1, \frac{l}{4}+1\]\\$.
2. The string to 'draw', which in this case is the input. 3. The directions, which in this case is `[5,2,7]`. These will be the directions `[↙,→,↖]`.

With these arguments, it will draw as follows (let's take the string `"thisrepresentationisnotatriangle"` as example again):

```
9 characters ("thisrepre") in direction 5 (↙)
        t
       h
      i
     s
    r
   e
  p
 r
e

17-1 characters ("sentationisnotat") in direction 2 (→):
        t
       h
      i
     s
    r
   e
  p
 r
esentationisnotatr

9-1 characters ("riangle") in direction 7 (↖):
(NOTE: "riangle" are only 7 characters instead of 8, since the string isn't any longer,
       which won't cause problems and is actually convenient for our desired output)
        t
       h e
      i   l
     s     g
    r       n
   e         a
  p           i
 r             r
esentationisnotat

```

See this 05AB1E tip of mine for a more in-depth explanation of the Canvas builtin.

---
Tags: code-golf, string, ascii-art
---


title: XOR two strings

text:
# Question
Title: XOR two strings
Given two strings as input, return the result of XORing the code-points of one string against the code points of the other.

For each character in the first input string, take the code-point (e.g. for `A`, this is 65) and XOR the value against the corresponding index in the second string and output the character at the code-point of the result. If one string is longer than the other, you **must return the portion of the string beyond the length of the shorter**, as-is. (Alternatively, you may pad the shorter string with `NUL` bytes, which is equivalent.)

See the following JavaScript code for an example:

```
const xorStrings = (a, b) => {
  let s = '';

  // use the longer of the two words to calculate the length of the result
  for (let i = 0; i < Math.max(a.length, b.length); i++) {
    // append the result of the char from the code-point that results from
    // XORing the char codes (or 0 if one string is too short)
    s += String.fromCharCode(
      (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0)
    );
  }

  return s;
};

```

Try it online!

## Test cases

```
Input                         Output

['Hello,', 'World!']          '\x1f\x0a\x1e\x00\x0b\x0d'
['Hello', 'wORLD']            '?*> +'
['abcde', '01234']            'QSQWQ'
['lowercase', "9?'      "]    'UPPERCASE'
['test', '']                  'test'
['12345', '98765']            '\x08\x0a\x04\x02\x00' _not_ 111092
['test', 'test']              '\x00\x00\x00\x00'
['123', 'ABCDE']              'pppDE'
['01', 'qsCDE']               'ABCDE'
['`c345', 'QQ']               '12345'

```

## Rules

* The two input strings will only ever be code-points 0-255.
* This is so the shortest solution, in each language, wins.

# Answer
> 11 votes
# Jelly, 4 bytes

```
O^/Ọ

```

Try it online!

Takes input as a list of the two strings, e.g. `['abcde', '01234']`.

### How?

```
O    # ord: cast to number (automatically vectorizes)
 ^/  # Reduce by XOR. XOR automatically applies to corresponding elements
         and pads as desired to work if the two strings are different lengths
   Ọ # chr: cast to character (vectorizes once again)

```

# Answer
> 8 votes
# Raku, 4 bytes

```
*~^*

```

Try it online!

Raku has a built-in operator for XORing strings, along with string AND, OR and bitshift. This is a Whatever lambda that takes two parameters.

# Answer
> 6 votes
# perl -Mfeature=say,bitwise -nl, 22 bytes

```
$.%2?($;=$_):say$;^.$_

```

Try it online!

This is way more characters than I first hoped for. If it weren't for those pesky newlines, the 9 character `say<>^.<>` would do.

## How does it work?

For odd input lines, it saves the current line of input (without the trailing newline due to the `-n` and `-l` switches) into `$;`. For even lines, it `xor`s the previous line (`$;`) and the current line (`$_`), and prints it. The `^.` operator does required bitwise string operation.

# Answer
> 5 votes
# APL (Dyalog Unicode), 15 bytes

```
80⎕DR≠⌿↑11⎕DR¨⎕

```

Try it online!

As the OP clarified that the input codepoints will be in the range of 0-255, it is possible to manipulate the underlying data bits directly. Such a string is guaranteed to have data type `80` (8-bit char array), so we convert it to data type `11` (1-bit boolean array) to access the bits, XOR them, and convert back to data type `80`.

```
80⎕DR≠⌿↑11⎕DR¨⎕  ⍝ Full program, input: two string literals on a line
        11⎕DR¨⎕  ⍝ Convert each string literal to bit array
       ↑         ⍝ Promote to matrix, padding with 0 as needed
     ≠⌿          ⍝ Bitwise XOR
80⎕DR            ⍝ Convert back to 8-bit char array

```

---

# APL (Dyalog Extended), 17 bytes

```
⎕UCS⊥≠⌿⍤2⊤↑⎕UCS¨⎕

```

Try it online!

Well, the task involves converting char to charcode and back AND converting from/to binary, but all current implementations having  have some quirks so it can't be used here. So here is the very literal implementation of the task.

```
⎕UCS⊥≠⌿⍤2⊤↑⎕UCS¨⎕  ⍝ Full program, input: two string literals on one line
           ⎕UCS¨⎕  ⍝ Convert to codepoints
          ↑        ⍝ Promote into a 2-row matrix, padding zeros as necessary
                   ⍝ (doing on characters give spaces which is 0x20, not 0)
         ⊤  ⍝ Convert each number to binary
     ≠⌿⍤2   ⍝ Bitwise XOR
    ⊥       ⍝ Convert the binary back to integers
⎕UCS        ⍝ Convert the integers back to chars

```

# Answer
> 5 votes
# , 14 bytes

```
XOR@,:&.(3&u:)

```

Try it online!

### How it works

```
XOR@,:&.(3&u:)
        (3&u:) strings -> code points
      &.       do right part, then left part, then the inverse of the right part
    ,:         pad shorter one with zeros by making a table
XOR@           XOR the code points
        (3&u:) revert back code points -> string

```

# Answer
> 5 votes
# C (gcc), <sup>~~60~~\\$\cdots\\$ ~~55~~</sup> 54 bytes

Saved ~~2~~ 4 bytes thanks to AZTECCO!!!

Saved ~~a~~ 2 bytes thanks to ceilingcat!!!

```
#define f(a,b)for(;*a+*b;b+=!!*b)a+=putchar(*a^*b)!=*b

```

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~8~~ 7 bytes

thanks to Kevin Cruijssen for a byte!

```
Ç0ζε`^ç

```

Try it online!

### Commented

```
	 implicit input          ["QQ", "`c345"]

Ç        convert to charcodes    [[96, 99, 51, 52, 53], [81, 81]]
  ζ      Zip with filler ...     [[96, 81], [99, 81], [51, "0"], [52, "0"], [53, "0"]]
 0       ... zero
   ε     Map ...                   [96, 81]
    `      Dump on stack           96, 81
     ^     XOR                     49
      ç    Convert to character    "1"

         implicit output         ["1", "2", "3", "4", "5"]

```

# Answer
> 4 votes
# Excel, ~~158 153~~ 108 bytes

(Not counting closing parens)

## Compatibility Notes:

* Minimum version: `CONCAT()` came to be in later versions of Excel 2016 (from `CONCATENATE()`).

## The Formulae

* Inputs: `A1`, `B1`
* A2: `=MIN(LEN(A1:B1))`, 14
* B2: `=LEN(A1)-LEN(B1)`, 15

Code (124):

```
=CONCAT(CHAR(BITXOR(CODE(MID(A1,SEQUENCE(A2),1)),CODE(MID(B1,SEQUENCE(A2),1)))))&RIGHT(IF(B2>0,A1,B1),ABS(B2))

```

One unfortunate caveat is that Excel ignores non-printable characters in cells. Alternatively, if you'd rather I use "\xXX" characters, I have this:

```
=CONCAT("\x"&DEC2HEX(BITXOR(CODE(MID(A1,SEQUENCE(A2),1)),CODE(MID(B1,SEQUENCE(A2),1))),2))&RIGHT(IF(B2>0,A1,B1),ABS(B2))

```

at 118 bytes. This just prints all XOR'ed characters as "\xXX" characters and leaves the trailing characters alone. Eg: `Hello!` and `World!!` produce `\x3F\x2A\x3E\x20\x2B\x00!`

### How it Works:

1. The `SEQUENCE(A2)` effectively creates a range of (1..A2). As far as I can tell, I cannot re-use this by caching it in a cell, which is why I had to use it twice.
2. Each item is then converted to numbers with `CODE()` and `BITXOR()`ed against each other.
3. The `CHAR()` converts this to a character, while `DEC2HEX(...,2)` converts it to a 2 width 0-padded hex number.
4. `CONCAT()` puts the array together
5. `RIGHT(...)` tacks on the trailing characters of the longer string.

# Answer
> 4 votes
# Python 3.8, 71 bytes

```
f=lambda a,b:chr(ord(a[0])^ord(b[0]))+f(a[1:],b[1:])if a and b else a+b

```

Try it online!

# Answer
> 3 votes
# Java 10, 109 bytes

```
(a,b)->{int A=a.length,B=b.length;if(A<B){var t=a;a=b;b=t;A^=B^(B=A);}for(;A-->0;)a[A]^=A<B?b[A]:0;return a;}

```

I/O as arrays of characters.

Try it online.

**Explanation:**

```
(a,b)->{             // Input as 2 character arrays as parameters as well as return-type
  int A=a.length,    //  `A`: the length of the first array `a`
      B=b.length;    //  `B`: the length of the second array `b`
  if(A<B){           //  If the length of `a` is smaller than `b`:
    var t=a;a=b;b=t; //   Swap the arrays `a` and `b`
    A^=B^(B=A);}     //   And also swap the lengths `A` and `B`
                     //  (`a`/`A` is now the largest array, and `b`/`B` the smallest)
  for(;A-->0;)       //  Loop index `A` in the range [`A`, 0):
    a[A]^=           //   Bitwise-XOR the `A`'th value in `a` with, and implicitly cast
                     //   from an integer codepoint to a character afterwards:
      A<B?           //    If index `A` is still within bounds for `b`:
       b[A]          //     XOR it with the `A`'th codepoint of `b`
      :              //    Else:
       0;            //     XOR it with 0 instead
  return a;}         //  Return the modified `a` as result

```

Note that we cannot use a currying lambda `a->b->` here, because we modify the inputs when swapping and they should be (effectively) final for lambdas.

# Answer
> 3 votes
# Factor, 48 bytes

```
: f ( s s -- s ) 0 pad-longest [ bitxor ] 2map ;

```

Try it online!

# Answer
> 2 votes
# JavaScript (Node.js), 66 bytes

```
f=(a,b)=>b[a.length]?f(b,a):(B=Buffer)(a).map((c,i)=>c^B(b)[i])+''

```

Try it online!

# Answer
> 2 votes
# Scala, 64 bytes

```
(a,b)=>(""/:a.zipAll(b,'\0','\0').map(x=>x._1^x._2))(_+_.toChar)

```

Try it online!

Run with

```
val f: ((String,String)=>String) = ...
println(f("01","qsCDE"))
...

```

Uses `zipAll` to zip the input strings with null bytes as padding, then XORs, finally using `foldLeft` shorthand `/:` to turn the whole thing back into a string.

# Answer
> 2 votes
# Japt, 6 bytes

```
cÈ^VcY

```

Try it

```
cÈ^VcY     :Implicit input of strings U & V
c          :Map the charcodes in U
 È         :by passing each one at index Y through the following function
  ^        :  Bitwise XOR with
   VcY     :  Charcode at index Y in V

```

# Answer
> 2 votes
# Lua, 105 bytes

```
i,a,b=0,...print(a:gsub('.',load'i=i+1return a.char((...):byte()~(b:sub(i,i):byte()or 0))')..b:sub(#a+1))

```

Try it online!

Taking two strings as arguments, this program calls per-character replace on one of them with essentially XOR function, then appends potentially missing fragment from second string (occurs if it is longer) and prints the result. TIO includes test suite.

# Answer
> 2 votes
# PHP, 36 bytes

```
[,$a,$b]=$argv;echo"$a\r$b\r",$a^$b;

```

Usage:

```
$ php -r '[,$a,$b]=$argv;echo"$a\r$b\r",$a^$b;' -- 'ABCDE' '123';echo
> pppDE

```

Explanation: first output string A, then carriage return `\r`, output string B, then another carriage return, then output the XOR (which truncates to the shorter of the 2 strings). Any characters of the longer string will have already been printed.

# PHP 7.4, 32 bytes

Using new arrow function syntax.

```
fn($a,$b)=>($a|$b^$b)^($a^$a|$b)

```

Explanation: In PHP binary operators, only the `|` will keep the longest string length and pad with `NUL`s. So we XOR string B with itself, leading to a string with NUL bytes of the same length as B, then OR that with A. This will pad A with NUL bytes and use the length of B, if B is longer than A. We do the same with B, and only *then* XOR.

Edits:

* arrow function variant
* missed the requirement of outputting the longest string

# Answer
> 2 votes
# Vyxal, 4 bytes

```
C÷꘍C

```

Try it Online!

Because Vyxal auto-pads lol.

## Explained

```
C÷꘍C
C     # convert each character in each string to it's ordinal value
 ÷꘍   # bitwise xor each item
   C  # and convert the result back to characters

```

Alternatively, using Keg mode:

### Vyxal `K`, 1 byte

Try it Online!

# Answer
> 1 votes
# Charcoal, 33 bytes

```
Ｆ⌈ＥθＬι«Ｆθ«≔ζη≔∧‹ιＬκ℅§κιζ»℅⁻｜ηζ＆ηζ

```

Try it online! Link is to verbose version of code. Takes input as an array of two strings. Explanation:

```
Ｆ⌈ＥθＬι«

```

Loop over the longer length of the strings.

```
Ｆθ«

```

Loop over the strings.

```
≔ζη

```

Save the result of the previous loop, if any.

```
≔∧‹ιＬκ℅§κιζ

```

Get the ordinal at the current index, if that is less than the current string.

```
»℅⁻｜ηζ＆ηζ

```

Emulate bitwise XOR by subtracting the bitwise AND from the bitwise OR, then convert back to a character.

# Answer
> 1 votes
# Python 2, ~~80~~ ~~72~~ 69 bytes

```
lambda*a:''.join(map(lambda x,y:chr(ord(x or'\0')^ord(y or'\0')),*a))

```

Try it online!

Uneven lengths are annoying...

# Answer
> 1 votes
# PowerShell, ~~86~~ 81 bytes

```
$k=[char[]]($args[1]);([byte[]]([char[]]($args[0])|%{$_-bxor$k[$i++%$k.Length]}))

```

Try it online!

-5 bytes thanks to @mazzy

# Answer
> 1 votes
# C (gcc),  ~~44~~  43 bytes

```
x(o,r)char*o,*r;{*o|*r&&x(o+1,r+1,*o^=*r);}

```

Try it online!

Uses recursion, note that to print strings containing the null byte one will have to manage the strings as arrays. (See the footer of the link for an example)

# C (gcc),  ~~50~~  49 bytes

```
x(o,r)char*o,*r;{*o|*r&&x(o+!!*o,r+!!*r,*o^=*r);}

```

Try it online!

Slightly safer version (doesn't read past end of strings, requires enough memory to exist past them though - a la `strcpy`).

# C (gcc),  ~~61~~  60 bytes

```
x(b,o,r)char*b,*o,*r;{*o|*r&&x(b+1,o+!!*o,r+!!*r,*b=*r^*o);}

```

Try it online!

As safe as any standard C function taking a buffer, at the cost of a few more bytes.

-1 byte from each thanks to ceilingcat!

# Answer
> 1 votes
# Stax, 7 bytes

```
ôM◙L╞@←

```

Run and debug it

# Answer
> 1 votes
# Husk, 11 bytes

```
ż§oc-¤nc¤vc

```

Try it online!

Unfortunately Husk doesn't have a bitwise XOR command (that I could find), so we need to do: arg1 OR (`v`) arg2 minus arg1 AND (`n`) arg2, costing an extra 5 bytes...

# Answer
> 1 votes
# x86 machine code, 29 bytes

Machine code:

```
00000034: 31 d2 e3 08 8a 11 41 41 84 d2 e1 fe ac 84 c0 75  1.....AA.......u
00000044: 06 e3 09 89 ce 31 c9 30 d0 aa eb e4 c3           .....1.0.....

```

Commented assembly:

```
        .intel_syntax noprefix
        .globl .strxor
        // Doesn't follow standard calling convention.
        // Input:
        //      EDI: Output buffer large enough for longest string
        //      ESI, ECX: Null terminated strings to XOR
        // Output:
        //      NON-null terminated string stored in EDI.
.strxor:
.Lloop:
        // Always clear EDX.
        xor     edx, edx
        // We mark the end of the shorter string
        // by setting ECX to null.
        jecxz   .Lskip_ecx
.Lno_skip_ecx:
        // Read a byte from ECX into DL.
        mov     dl, byte ptr [ecx]
        // Increment twice because LOOPZ decrements.
        inc     ecx
        inc     ecx
        // Was it '\0'?
        test    dl, dl
        // If so, set ECX to NULL by using LOOPZ in place.
        // CMOVZ ECX, EAX also works, but needs P6.
        // This works with i386 and is the same size.
.Lclear_ecx:
        loopz   .Lclear_ecx
.Lskip_ecx:
        // Load from ESI and autoincrement
        lods    al, byte ptr [esi]
        // Test for '\0'
        test    al, al
        jnz     .Lno_swap
.Lswap: // '\0' found
        // If ECX is null, we are at the end of both strings.
        jecxz   .Lend
        // Otherwise, we swap ESI and ECX, and then clear ECX.
        // Set ESI to ECX.
        mov     esi, ecx
        // And set ECX to NULL.
        xor     ecx, ecx
        // fallthrough
.Lno_swap:
        // XOR the two bytes together
        xor     al, dl
        // Store to EDI and autoincrement
        stos    byte ptr [edi], al
        // Loop unconditionally.
        jmp     .Lloop
.Lend:
        ret

```

Try it online!

The code reads two null terminated strings from `esi` and `ecx`, and stores the NON null terminated string in `edi`.

The logic is probably easier to see in the equivalent C code.

```
void strxor(char *dst, const char *src1, const char *src2)
{
    for (;;) {
        char x = '\0';
        if (src2 != NULL) {
            x = *src2++;
            if (x == '\0') { // eos
                src2 = NULL;
            }
        }
        char y = *src1++;
        if (y == '\0') {
            if (src2 == NULL) { // both eos
                return;
            } else { // src2 is longer
                src1 = src2;
                src2 = NULL;
            }
        }
        *dst++ = x ^ y;
    }
}

```

I don't null terminate because null bytes naturally show up in the output and it saves a byte.

I may also add a version with explicit lengths which accepts null bytes, but the solution would be significantly less elegant.

# Answer
> 1 votes
# Perl 5, 14 bytes

```
sub f{pop^pop}

```

Try it online!

# Answer
> 0 votes
# Scala 3, ~~30~~ 29 bytes

```
a=>b=>a zipAll(b,0,0)map(_^_)

```

Try it online

# Scala 2, ~~41~~ ~~39~~ 38 bytes

Used infix notation to turn `.map` into just `map`

```
a=>b=>a zipAll(b,0,0)map(a=>a._1^a._2)

```

Inputs and output are lists of integers

Try it online

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


# Question
Title: Hamiltonian levencycle of 1-dup permutations
The word "levencycle" is inspired by cyclic levenquine challenge.

## Definitions

A **1-dup permutation** of order \\$n\\$ is some permutation of \\$1, \cdots, n\\$ plus one duplicate number in the range.

For example, 1-dup permutations of order 3 include `1, 3, 2, 2` and `3, 2, 1, 3`. There are 36 distinct 1-dup permutations of order 3, and \\$\frac{(n+1)!\cdot n}{2}\\$ of those of order \\$n\\$ in general.

A **Hamiltonian levencycle** combines the concept of Hamiltonian cycle (a cycle going through all vertices in a given graph) and Levenstein distance (minimal edit distance between two strings). Informally, it is a cycle going through all possible sequences by changing only one number at once.

For example, the following is a Hamiltonian levencycle of order 2: (the connection from the last to the start is implied)

```
(1, 1, 2) -> (1, 2, 2) -> (1, 2, 1) -> (2, 2, 1) -> (2, 1, 1) -> (2, 1, 2)

```

For order 3, found by automated search using Z3:

```
(1, 1, 2, 3) -> (1, 2, 2, 3) -> (1, 2, 1, 3) -> (1, 2, 3, 3) ->
(1, 2, 3, 2) -> (1, 3, 3, 2) -> (1, 1, 3, 2) -> (3, 1, 3, 2) ->
(3, 1, 2, 2) -> (3, 1, 2, 1) -> (3, 1, 2, 3) -> (2, 1, 2, 3) ->
(2, 1, 1, 3) -> (2, 1, 3, 3) -> (2, 1, 3, 2) -> (2, 1, 3, 1) ->
(2, 2, 3, 1) -> (1, 2, 3, 1) -> (3, 2, 3, 1) -> (3, 2, 1, 1) ->
(3, 2, 2, 1) -> (3, 3, 2, 1) -> (1, 3, 2, 1) -> (2, 3, 2, 1) ->
(2, 3, 3, 1) -> (2, 3, 1, 1) -> (2, 3, 1, 2) -> (2, 3, 1, 3) ->
(2, 2, 1, 3) -> (3, 2, 1, 3) -> (3, 2, 1, 2) -> (3, 1, 1, 2) ->
(3, 3, 1, 2) -> (1, 3, 1, 2) -> (1, 3, 2, 2) -> (1, 3, 2, 3)

```

## Challenge

Given an integer \\$n \ge 2\\$, output a Hamiltonian levencycle of 1-dup permutations of order \\$n\\$. The output format is flexible. Assume that such a cycle exists; for values of \\$n\\$ where it does not exist, the behavior is undefined (you may do whatever you want).

Standard rules apply. The shortest code in bytes wins.

# Answer
> 5 votes
# Jelly, 110 bytes

```
ñ-ị$X⁸ṣU2¦jɗ
0ịị®ḟ
Œ!⁸œṖþẎṣ€Ẏ¥þ⁸Q€;@"Ẏ¥þ@";þ`ạ/Þ€;"Q¥U$ƊẎḅQ¥€⁸ṢFỤ’:‘sʋ1ịLƊƲ©ṛ1ç`X;@ṛÑ¥¹?Ɗ,®Ẉ⁻/Ɗ¿Ñç0ċ1¬Ɗ¿ƲịḢ€Ɗḃ

```

Try it online!

A full program that takes an integer and returns a list of lists of integers. Not written primarily to be compact but for efficiency and speed. Can solve the problem for n=5 in around 5 seconds on TIO and gets most of the way for n=6 within 60 seconds. This uses a modified version of the algorithm described in the post linked by Jonah. However, that lost only covered a Hamiltonian path and so there’s an additional bit to ensure a cycle is found. The code to find the Levenstein neighbours is also longer than minimal so that it completes in time - a more naive but shorter solution for that bit still completes within a few seconds for n=5 but rapidly becomes unworkable for bigger n.

Full explanation to follow.

# Answer
> 5 votes
# Wolfram Language (Mathematica), 172 bytes

```
(DeleteDuplicates[Flatten[Table[Permutations[Join[{i},Range[#]]],{i,Range[#]}],1]]//FindHamiltonianPath[AdjacencyGraph[Table[If[1==EditDistance[i,j],1,0],{i,#},{j,#}]]]&)&;

```

Try it online!

This is my first Wolfram golf, and as a golf I think it's pretty terrible, but I'm posting because it calculates n=3 almost instantly, which seems to support my conjecture from the other answer that there is a more efficient (possibly probabilistic) algorithm for this. These docs suggest this as well, though don't say which of the algorithms discussed powers `FindHamiltonianPath`.

`n=4` times out on TIO, and I haven't tested it longer than a minute, so I'm not sure how long its execution time would be.

# Answer
> 1 votes
# Jelly, 21 bytes

```
R;€`Œ!€ẎQŒ!ṙ1nƊ§ỊẠƲƇḢ

```

Try It Online!

-1 byte thanks to Nick Kennedy, then fixed for +1 thanks to Nick Kennedy

Full explanation to come if I remember.

# Answer
> 1 votes
# , 76 bytes

```
0{[:(#~([:*/2(1=1#.*@|@-/)\],{.)"2)@(i.@!@#A."2])@~.[:,/i.@!@>:A."1,"0 1~@i.

```

Try it online!

Brute force, not a great golf. Should work in theory but too slow to test on anything above 2.

General Hamiltonian circuit is NP, but I'm wondering if there's something special about the structure of this problem that allows a clever, much faster algorithm? I had another approach that's 2^n instead of n! but that's still not close to good enough.

Perhaps this? https://stackoverflow.com/questions/1987183/randomized-algorithm-for-finding-hamiltonian-path-in-a-directed-graph

Maybe I'll give it a shot tomorrow...

---
Tags: code-golf, graph-theory, permutations, edit-distance
---


# Question
Title: Tuples by sequentially stepping through entries in list of lists
## Challenge:

Given a list of nonempty lists of integers, return a list of tuples of the following form: First list tuples starting with each element of the first list followed by the first element of every subsequent list, so the ith tuple should be `[ith element of first list, first element of second list, ... , first element of last list]`. For example:

```
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [[1, 4, 7], [2, 4, 7], [3, 4, 7], ...

```

Then do tuples of the form `[last element of first list, ith element of second list, first element of third list, ..., first element of last list]`, so in our example this would be:

```
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] =>  ..., [3, 4, 7], [3, 5, 7], [3, 6, 7], ...

```

Continue on with each remaining list, until you get to `[last element of first list, ..., last element of second to last list, ith element of last list]`:

```
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] => ..., [3, 6, 7], [3, 6, 8], [3, 6, 9]]

```

The full output is as follows:

```
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] =>
        [[1, 4, 7], [2, 4, 7], [3, 4, 7], [3, 5, 7], [3, 6, 7], [3, 6, 8], [3, 6, 9]]

```

Some boilerplate for good measure:

* If you want the input to be lists of strings, or lists of positive integers, it's fine. The question is about manipulating lists, not about what is in the lists.
* Input and output can be in any acceptable format.
* Either a full program or function is permitted.
* Standard loopholes are disallowed by default.
* This question is code golf, so lowest byte-count wins.

## Examples:

```
[] => [[]] (or an error, thanks to ngn for correcting the output in this case)

[[1]] => [[1]]

[[1, 2], [3, 4], [5]] => [[1, 3, 5], [2, 3, 5], [2, 4, 5]]

[[1], [2], [5, 6], [3], [4]] => [[1, 2, 5, 3, 4], [1, 2, 6, 3, 4]]

[[1, 2, 3], [4, 5]] => [[1, 4], [2, 4], [3, 4], [3, 5]]

[[1, 2, 3], []] => unspecified behavior (can be an error)

[[3, 13, 6], [9, 2, 4], [5, 10, 8], [12, 1, 11], [7, 14]] =>
     [[3, 9, 5, 12, 7], [13, 9, 5, 12, 7], [6, 9, 5, 12, 7], [6, 2, 5, 12, 7],
      [6, 4, 5, 12, 7], [6, 4, 10, 12, 7], [6, 4, 8, 12, 7], [6, 4, 8, 1, 7],
      [6, 4, 8, 11, 7], [6, 4, 8, 11, 14]]

[[16, 8, 4, 14, 6, 7, 10, 15], [11, 1, 12, 2, 19, 18, 9, 3], [13, 5, 17]] =>
    [[16, 11, 13], [8, 11, 13], [4, 11, 13], [14, 11, 13], [6, 11, 13],
     [7, 11, 13], [10, 11, 13], [15, 11, 13], [15, 1, 13], [15, 12, 13], [15, 2, 13],
     [15, 19, 13], [15, 18, 13], [15, 9, 13], [15, 3, 13], [15, 3, 5], [15, 3, 17]]

```

If anyone has a better title, let me know.

# Answer
# JavaScript (ES6), 59 bytes

Expects a list of lists of *positive* integers.

```
f=a=>[a.map(a=>a[0]),...a.some(a=>a[1]&&a.shift())?f(a):[]]

```

Try it online!

### How?

At each iteration:

* We output a new list consisting of the first element of each list.
* We remove the first element of the first list containing at least 2 elements, and repeat the process. Or we stop the recursion if no such list exists.
> 5 votes

# Answer
# K (ngn/k), ~~40 21 19 18~~ 17 bytes

```
{x@'/:?|\+|!|#'x}

```

Try it online!

uses ideas from @H.PWiz's answer

`{` `}` function with argument `x`

`#'` length of each

`|` reverse

`!` all index tuples for an array with those dimensions as columns in a matrix (list of lists)

`|` reverse

`+` transpose

`|\` running maxima

`?` unique

`x@'/:` use each tuple on the right as indices in the corresponding lists from `x`
> 2 votes

# Answer
# Jelly, 15 bytes

```
ẈṚṪ×€PƊƤFQṚCịŒp

```

**Try it online!** (the footer displays the actual returned list rather than a Jelly representation)

### How?

Indexes into the Cartesian product of the lists at the required points...

```
ẈṚṪ×€PƊƤFQṚCịŒp - Link: list of lists  e.g. [[6,8,4,9],[7,1,5],[3,2]]
Ẉ               - length of each            [4,3,2]
 Ṛ              - reverse                   [2,3,4]
       Ƥ        - for each prefix:             [2]      [2,3]      [2,3,4]
      Ɗ         -   last 3 links as a monad:
  Ṫ             -     tail (pop rightmost)     2        3          4
     P          -     product (of remaining)   1        2          6
    €           -     for €ach (range tail)    [1,2]    [1,2,3]    [1,2,3,4]
   ×            -       multiply               [1,2]    [2,4,6]    [6,12,18,24]
        F       - flatten                   [1,2,2,4,6,6,12,18,24]
         Q      - de-duplicate              [1,2,4,6,12,18,24]
          Ṛ     - reverse                   [24,18,12,6,4,2,1]
           C    - complement (1-x)          [-23,-17,-11,-5,-3,-1,0]
             Œp - Cartesian product (of the input)
                -         -> [[6,7,3],[6,7,2],[6,1,3],[6,1,2],[6,5,3],[6,5,2],[8,7,3],[8,7,2],[8,1,3],[8,1,2],[8,5,3],[8,5,2],[4,7,3],[4,7,2],[4,1,3],[4,1,2],[4,5,3],[4,5,2],[9,7,3],[9,7,2],[9,1,3],[9,1,2],[9,5,3],[9,5,2]]
            ị   - index into (1-based & modular)
                -   indexes:      -23,                                            -17,                                            -11,                                             -5,             -3,             -1,     0
                -    values: [[6,7,3],                                        [8,7,3],                                        [4,7,3],                                        [9,7,3],        [9,1,3],        [9,5,3],[9,5,2]]
                -         -> [[6,7,3],[8,7,3],[4,7,3],[9,7,3],[9,1,3],[9,5,3],[9,5,2]]

```

---

`ẈṚ’ṣ1T$¦ƬUṚị"€` (14 bytes) fails for inputs with (non-trailing) length one lists; but maybe `ṣ1T$` can be replaced with something else?
> 2 votes

# Answer
# Python 2, 72 bytes

```
f=lambda a:zip(*a)[:1]+(any(len(u)>1and u.pop(0)for u in a)and f(a)or[])

```

Try it online!

This is a Python port of Arnauld's excellent Javascript algorithm.
> 2 votes

# Answer
# Python 2, 62 bytes

```
lambda M:[zip(*M)[l.pop(0)*0]for l in M+[[1,1]]for _ in l[1:]]

```

Try it online!

Using Chas Brown's pop idea inspired by Arnauld's JS submission.

---

**Python 2, 68 bytes**

```
M=input()
for l in[[0,0]]+M:
 for x in l[1:]:l[0]=x;print zip(*M)[0]

```

Try it online!

Mutates the first elements of the lists to hold the desired values. The `[[0,0]]+` is an ugly hack to print the initial first values.
> 2 votes

# Answer
# APL (Dyalog), 15 bytes (SBCS)

Thanks ngn for pointing out an unnecessary byte

```
{∪⌈\,⍉⍳≢¨⍵}⊃¨¨⊂

```

Try it online!

`{∪⌈\,⍉⍳≢¨⍵}` generates lists to index into the input. e.g `(1 2 3) (4 5 6) (7 8 9) -> (0 0 0) (1 0 0) (2 0 0) (2 1 0) (2 2 0) (2 2 1) (2 2 2)`

`≢¨⍵`: the length of each list in the input

`,⍉⍳` creates all combinations of numbers up to it's input. e.g. `2 3 -> (0 0) (1 0) (0 1) (1 1) (0 2) (1 2)`

`⌈\`: scan with maximum. e.g. the above example would now be `(0 0) (1 0) (1 1) (1 1) (1 2) (1 2)`

: remove duplicates

`⊃¨¨⊂` does the indexing, being mindful of the depth of either argument
> 2 votes

# Answer
# Haskell, 87 bytes

```
x?[]=[]
x?([c]:d)=(x++[c])?d
x?((c:d):e)=(x++c:map head e):x?(d:e)
f x=[]?x++[last<$>x]

```

Try it online
> 2 votes

# Answer
# Charcoal, 33 bytes

```
ＩＥ⊕ΣＥθ⊖ＬιＥθ§λ⌈⟦⁰⌊⟦⊖Ｌλ⁻ι∧μΣＥ…θμ⊖Ｌν

```

Try it online! Link is to verbose version of code. Explanation:

Cast the integers to strings before implicitly printing using the default output format for lists, which is each item on its own line, and nested lists double-spaced.

```
Ｅ⊕ΣＥθ⊖Ｌι

```

Take the sum of the lengths of the lists and subtract the length of the list of lists. Then loop from 0 to this value inclusive.

```
Ｅθ§λ

```

Map over the list of lists and index into each list.

```
⌈⟦⁰⌊⟦⊖Ｌλ

```

Clamp the index to 0 and the last index in the list. (The closing brackets are implied.)

```
⁻ι∧μΣＥ…θμ⊖Ｌν

```

After the first list, subtract the decremented lengths of all the previous lists from the outermost index. (This doesn't work for the first list because the length of lists is empty and the sum isn't a number.)
> 1 votes

# Answer
# APL (Dyalog Classic), ~~32~~ ~~30~~ 27 bytes

```
1↓¨∪⊃{(⍵,¨⊃⍺),⍺,¨⍨⊢/⍵}/⌽0,⎕

```

Try it online!

complete program, input is from the keyboard ()

for input `[]` outputs `[[]]` (their APL equivalents are `0⍴⊂⍬` and `,⊂⍬`)

assumes uniqueness of numbers in the input
> 1 votes

# Answer
# Python 2, 91 bytes

```
f=lambda a,p=():a and[p+(q,)+zip(*a)[0][1:]for q in a[0][p>():]]+f(a[1:],p+(a[0][-1],))or[]

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), 58 54 bytes

```
h=(x,s)=>[x.map(y=>s|y?y[0]:s=y.shift()),...s?h(x):[]]

```

After 14+ attempts at golfing my code down (removing all instances of while loops, `push`, and `concat`), I arrived at an iteration algorithmically similar to @Arnauld's answer, unsurprising given how succinct it is!

Accepts a list of lists of positive integers. Try it online!

### 58 bytes

For 1 more byte, replacing `s = y.shift()` with `y.shift(s = 1)` should handle all integers (presumably, as I have not personally tested it).

```
h=(x,s)=>[x.map(y=>!s/y[1]?s=y.shift():y[0]),...s?h(x):[]]

```

### 58 bytes

Bonus version, with slight rearranging:

```
h=x=>[x.map(y=>s&&y[1]?y.shift(s=0):y[0],s=[]),...s||h(x)]

```

# Explanation

Early versions of the code tried to modify a clone of (an array of) the first elements of each array, but the extra step of initializing that array was expensive... until I realized that mapping over the first elements of each array was roughly the "only" operation necessary if I mutate the original arrays.

Uses a boolean flag to check if any array has been shifted (i.e. shortened) yet. Golfed the conditional check down further by observing that JS coerces arrays with a number value as its only element into that number, while coercing arrays with multiple values as NaN.

```
var
h = (x, s) =>
    [
        x.map(y =>                 // map to first element of each array
            s|y                    // if s == 1 (i.e. an array has been shortened)
                                   // or the current array y has length == 1
                ? y[0]
                : s = y.shift()    // remove first element of y and set s to truthy
        ),
        ...s ? h(x) : []           // only concatenate a recurrence of the function if an array has had a value removed
    ]

```
> 1 votes

---
Tags: code-golf, array
---