title: Be there, for the square

text:
# Question
Title: Be there, for the square
Sometimes when you're lying in bed and reading a message, your phone screen will pop into landscape mode right in the middle of a sentence. Only being able to read left to right, you find yourself incapacitated, unable to process the text in front of you.

To ensure that this won't happen again, you decide to make every message readable from any angle, whether your phone screen is rotated or mirrored. To make this happen, each message is printed as a square, with each side of the square containing the message, either in the original order or in reverse.

* For backwards compatibility, the top side of the square should be the original message.
* To make each message square as compact as possible, the first and last character of the message should be a part of two sides of the square. This means that the top side reads normally, the bottom side is in reverse, the left side reads top-bottom, and the right side reads bottom-top.

## Input

A single string, with 2 or more characters. You should not assume that the string only contains alphanumerical characters or similar.

## Output

The Squarification™ of the string. It is permissible to leave some whitespace at the end of each line, and a single newline at the end of the output.

## Examples

```
Input: 'ab'
ab
ba

Input: 'abc'

abc
b b
cba

Input: 'Hello, world!'
Hello, world!
e           d
l           l
l           r
o           o
,           w

w           ,
o           o
r           l
l           l
d           e
!dlrow ,olleH

```

This challenge looks like A cube of text, but I'm hoping that it's different enough that there will be some clever answers.

As this is code-golf, get ready to trim some bytes!

# Answer
# Charcoal, 4 bytes

```
Ｓ‖Ｏ^

```

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

```
Ｓ       Input the string and implicitly print it
 ‖      Reflect...
  Ｏ     ... overlapping the first and last character...
   ^    ... in the ↙↘ directions (^ is shorthand for ↙↘).

```
> 18 votes

# Answer
# 05AB1E, ~~12~~ 11 bytes

Saved 1 byte thanks to *Kevin Cruijssen*

```
g4иsûûŽ9¦SΛ

```

Try it online!

**Explanation**

```
g            # length of input
 4и          # quadruplicate in a list
             # these are the string lengths we'll print
   s         # push input
    ûû       # palendromize twice
             # this is the string we'll print
      Ž9¦S   # push [2,4,6,0]
             # these are the directions we'll print
          Λ  # paint on the canvas

```
> 10 votes

# Answer
# Python 2, ~~80~~ ~~76~~ ~~71~~ ~~70~~ 69 bytes

```
lambda s:[s]+map((' '*len(s[2:])).join,zip(s,s[:0:-1]))[1:]+[s[::-1]]

```

Try it online!

# Python 3, 70 bytes

```
lambda s:[s,*map((' '*len(s[2:])).join,zip(s[1:],s[-2:0:-1])),s[::-1]]

```

Try it online!
> 7 votes

# Answer
# Canvas, 6 bytes

```
⤢ｎ：±⇵ｎ

```

Try it here!

Explanation:

```
⤢       transpose the input
 n      and overlap that over the input
  :     duplicate that
   ±⇵   reverse it vertically & horizontally
     n  and overlap over the old version

```
> 7 votes

# Answer
# Python 3, ~~78~~ 76 Bytes

-2 bytes thanks to maxb!

```
lambda x:[x]+[x[i]+" "*(len(x)-2)+x[~i]for i in range(1,len(x)-1)]+[x[::-1]]

```

Try it Online!
> 6 votes

# Answer
# 05AB1E, 14 bytes

```
¦¨s¨š.BsRøJIRª

```

Try it online!

Outputs as a list of lines, but the TIO link uses the old version which printed instead – Try an alternative online!. Thought I'd be nice to show how awesome the canvas is by comparing that approach to others that don't use it. See Emigna's answer for a canvas version, then compare it to mine :)

### How?

```
¦¨s¨š.BsRøJ»,R=    Full program. Accepts a string from STDIN. | Example: "abcd"
¦¨                 Tail and pop.                              | STACK: ["bc"]
  s¨               Swap and pop.                              | STACK: ["bc", "abc"]
    š              Prepend a to b as a list.                  | STACK: [["abc", "b", "c"]]
     .B            Squarify.                                  | STACK: [["abc", "b  ", "c  "]]
       sRøJ        Interleave with the reversed input.        | STACK: [["abcd", "b  c", "c  d"]].
           »,      Join by newlines, pop and print.           | STACK: [] (the above is removed after being printed)
             R=    Print the reversed input (taken implicitly due to the empty stack).

```

The only thing which is different in the 14-byter is that the reversed input is appended to the list rather than printed.
> 6 votes

# Answer
# MATL, 8 bytes

```
YTO6Lt&(

```

Try it online!

### Explanation

Consider input `'abcd'` as an example. Stack is shown bottom to top.

```
YT     % Implicit input: string. Create Toeplitz matrix of chars
       % STACK: ['abcd';
                 'babc';
                 'cbab';
                 'dcba']
O      % Push 0
       % STACK: ['abcd';
                 'babc';
                 'cbab';
                 'dcba']
                 0
6L     % Push [2, -1+1j]. Used as an index, this means 2:end
       % STACK: ['abcd';
                 'babc';
                 'cbab';
                 'dcba']
                 0,
                [2, -1+1j]
t      % Duplicate
       % STACK: ['abcd';
                 'babc';
                 'cbab';
                 'dcba']
                 0,
                [2, -1+1j],
                [2, -1+1j]
&(     % Write 0 into the internal entries of the char matrix.
       % STACK: ['abcd';
                 'b  c';
                 'c  b';
                 'dcba']
       % Implicitly display. Char 0 is shown as a space

```
> 6 votes

# Answer
# Japt `-R`, ~~22~~ 15 bytes

```
U+ÕÅ+UÔÅ Õ·hJUw

```

Try it online!
> 6 votes

# Answer
# Perl 6, ~~55~~ 51 bytes

```
{$_,|.comb[1..*-2].&{(@_ X~' 'x@_)Z~[R,] @_},.flip}

```

Try it online!

Returns a list of lines.

### Explanation:

```
{                                                 }  # Anonymous code block
 $_,    # The given string as the first line
     .comb[1..*-2]   # The string as a list of chars without the first or last char
                  .&{                      }  # Passed to a function
                     (@_ X~' 'x@_)  # Each character padded with space
                                  Z~[R,] @_   # And zipped with the reverse
    |   # Flattened
                                            ,.flip  # And the reverse of the string

```
> 5 votes

# Answer
# Pyth, ~~16~~ 15 bytes

```
LXXb0Qt0_Qy.tym

```

Try it online here, or verify all the test cases at once here (test suite joins output on newlines for easier verification, as per OP request).

```
LXXb0Qt0_Qy.tymdQ   Implicit: Q=eval(input())
                    Trailing d,Q inferred
L                   Define a function, y(b), as:
  Xb                  Replace in b...
    0                 ... at position 0...
     Q                ... the input string
 X                    Replace in the above...
      t0              ... at position -1 (decrement 0)
        _Q            ... the reversed input string
              mdQ   Split the input string into array of characters
                      (The exact contents of the array don't matter, as long as the array
                       has the same length as the input string and the elements are
                       of length < 2)
             y      Apply the function y (defined above) to the array
                      (For Q="abc", yields ["abc", "b", "cba"]
           .t       Transpose, padding with spaces
                      (For Q="abc", yields ["abc", "b b", "c a"]
          y         Apply y to the above

```

*Edit: OP clarified that a list of lines is acceptable as output, so removed `j` to join on newlines - previous version `LXXb0Qt0_Qjy.tym`*
> 5 votes

# Answer
# JavaScript (Node.js), ~~93~~ ~~91~~ ~~87~~ ~~80~~ ~~78~~ ~~77~~ ~~76~~ 74 bytes

```
x=>[...x].map(c=>(w+=z=x[--j])[1]?j?c.padEnd(l-1)+z:w:x,w="",l=j=x.length)

```

Try it online!

Returns list of lines.

## Explanation

```
x =>                     // Main function
 [...x].map(c =>         // For each character in the input:
  (w += z = x[--j])[1]   //  Check whether this is not the first row (by producing w, the
                         //  reverse of x, character by character, and check if len(w) > 1)
  ?                      //  If so:
   j                     //   Check if this is not the last row
   ? c.padEnd(l - 1) + z //   If so: return the needed row
   : w                   //   If not (i.e. last row): return w, the reverse of x
  : x,                   //  If not (i.e. first row): return x
  w = "",                // Stores the reverse of w
  l = j = x.length       // A variable that stores the length of the string, and a counter
 )                       // Golfing from 78 onwards is tough work.

```
> 4 votes

# Answer
# Haskell, ~~80~~ ~~76~~ ~~72~~ 71 bytes

* Saved ~~four~~ ~~eight~~ nine bytes thanks to Laikoni.

```
f s=s:m[c:m(' '<$s)++[d]|(c,d)<-zip s$r s]++[r s];m=init.tail;r=reverse

```

Try it online!
> 4 votes

# Answer
# Red, 145 127 bytes

```
func[s][print a: s b: tail s repeat n l:(length? s)- 2[print rejoin[pad first a:
next a l + 1 first b: back b]]print reverse s]

```

Try it online!
> 3 votes

# Answer
# MathGolf, ~~20 19~~ 15 bytes

```
p╡╞▒x_xh *+m+nx

```

Try it online!

Edited to an improved version of maxb's original 22 byte solution. Zip operator is sadly lacking though the `m`ap operator has a partial implementation.

### Explanation:

```
p                 Print the original string ["abcd"]
 ╡╞               Remove from the start and end of the string  ["bc"]
   ▒              Convert to a list of chars  [["b","c"]]
    x_x           Reverse, dupe and reverse back again [["c","b"],["b","c"]]
       h          Get length of array without popping  [["c","b"],["b","c"],2]
         *        Create a string with that many spaces [["c","b"],["b","c"],"  "]
          +       Map adding it to every character [["c","b"],["b  ","c  "]]
           m+     Zip add each character of the reversed string [["b  c","c  b"]]
             n    Join with newlines and print
              x   Reverse the original string and implicitly output

```
> 3 votes

# Answer
# Java 11, ~~143~~ ~~142~~ ~~141~~ 140 bytes

```
s->{for(int l=s.length(),i=l;i>0;)System.out.println(i--<l?i<1?new StringBuffer(s).reverse():s.charAt(l+~i)+" ".repeat(l-2)+s.charAt(i):s);}

```

-1 byte thanks to *@OlivierGrégoire*.

Try it online.

**Explanation:**

```
s->{                                // Method with String parameter and no return-type
  for(int l=s.length(),             //  Length of the input-String
      i=l;i>0;)                     //  Loop `i` in the range (length,0]
    System.out.println(             //   Print with trailing newline:
     i--<l?                         //    If it's NOT the first iteration:
                                    //    (and decrease `i` by 1 at the same time)
      i<1?                           //    If it's the last iteration:
       new StringBuffer(s).reverse() //     Print the input reversed
      :                              //    Else:
       s.charAt(l+~i)                //     Print the `l-i-1`'th character,
       +" ".repeat(l-2)              //     appended with length-2 amount of spaces,
       +s.charAt(i):                 //     appended with the `i`'th character
     :                               //   Else (it is the first iteration):
      s);}                           //    Print the input as is

```
> 3 votes

# Answer
# Ruby, 78 bytes

```
->s{[s.b,*s.chars.zip(s.reverse!.chars).map{|a|"%s%#{s.size-1}s"%a}[1..-2],s]}

```

Try it online!
> 3 votes

# Answer
# Z80Golf, 48 bytes

```
00000000: 1525 13cd 0380 3806 ff4d 2377 18f5 3e0a  .%....8..M#w..>.
00000010: ff7b b928 1113 1aff 4105 2805 3e20 ff18  .{.(....A.(.> ..
00000020: f82b 7eff 18e8 131a b720 0176 ff1b 18f7  .+~...... .v....

```

Try it online!

```
  dec d
  dec h
  inc de
get:
  call $8003
  jr c, got
  rst 38h
  ld c, l
  inc hl
  ld (hl), a
  jr get

got:
  ld a, '\n'
  rst 38h
  ld a, e
  cp c
  jr z, final
  inc de
  ld a, (de)
  rst 38h
  ld b, c
spaces:
  dec b
  jr z, doneb
  ld a, ' '
  rst 38h
  jr spaces
doneb:
  dec hl
  ld a, (hl)
  rst 38h
  jr got

final:
  inc de
reverse:
  ld a, (de)
  or a
  jr nz, cont
  halt
cont:
  rst 38h
  dec de
  jr reverse

```
> 3 votes

# Answer
# Powershell, 93 bytes

```
param($s)$s
if(($m=$s.Length-2)-gt0){1..$m|%{$s[$_]+' '*$m+$s[$m-$_+1]}}
-join($s[($m+2)..0])

```

Test script:

```
$f = {

param($s)$s
if(($m=$s.Length-2)-gt0){1..$m|%{$s[$_]+' '*$m+$s[$m-$_+1]}}
-join($s[($m+2)..0])

}

&$f ab
&$f abc
&$f Hello...
&$f 'Hello, world!'

```

Output:

```
ab
ba
abc
b b
cba
Hello...
e      .
l      .
l      o
o      l
.      l
.      e
...olleH
Hello, world!
e           d
l           l
l           r
o           o
,           w

w           ,
o           o
r           l
l           l
d           e
!dlrow ,olleH

```
> 3 votes

# Answer
# APL(NARS), 59 chars, 118 bytes

```
{y←⊖⍵⋄0=z←¯2+⍴⍵:⊃,¨⍵ y⋄⊃(⊂⍵),({(∊1(z⍴0)1)\⍵}¨¯1↓1↓⍵,¨y),⊂y}

```

test

```
  f←{y←⊖⍵⋄0=z←¯2+⍴⍵:⊃,¨⍵ y⋄⊃(⊂⍵),({(∊1(z⍴0)1)\⍵}¨¯1↓1↓⍵,¨y),⊂y}
  f '12'
12
21
  f '123'
123
2 2
321
  f '1234'
1234
2  3
3  2
4321
  f 'Hello World!'
Hello World!
e          d
l          l
l          r
o          o
           W
W
o          o
r          l
l          l
d          e
!dlroW olleH
  f 'Hello, World!'
Hello, World!
e           d
l           l
l           r
o           o
,           W

W           ,
o           o
r           l
l           l
d           e
!dlroW ,olleH

```
> 3 votes

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

```
s=>[...s].map((e,i,a,n=s.length)=>i<1?s:i>n-2?a.reverse().join``:e.padEnd(n-1)+a[n+~i])

```

Question Title is **Be there, for the Square** but all answers print a **Rectangle**
So here's the one printing square:

```
s=>[...s].map((e,i,a,n=s.length)=>i<1?a.join` `:i>n-2?a.reverse().join` `:e.padEnd(2*n-2)+a[n+~i])
```

Try it online!
> 2 votes

# Answer
# JavaScript, ~~92~~ 85 bytes

Early morning golf on the bus. Not happy with it; there's definitely a shorter way :\

```
s=>s+`
`+(g=r=>--x?s[l-x].padEnd(l)+s[--y]+`
`+g(r+s[y]):r+s[0])(s[l=x=y=s.length-1])

```

Try it online
> 2 votes

# Answer
# Japt, 28 bytes

*Takes the input as an array of characters*

```
íUz2)£Y©Y<UÊÉ?XqSpUÊ-2:UqÃow

```

---

```
íUz2)£Y©Y<UÊÉ?XqSpUÊ-2:UqÃow    Full program. Implicity input U
                                ["a", "b", "c"]
 Uz2)                           Duplicate and rotate 180°
                                ["a", "b", "c"], ["c", "b", "a"]
í                               Pair each item at the same index
                                [["a","c"],["b","b"], ["c","a"]]
     £                          Map
      Y©Y<                      If index is positive and less than
          UÊÉ?                  Length - 1
              Xq                Join with...
                SpUÊ-2          Space repeated (U length - 2) times
                                [["a","c"],"b b", ["c","a"]]
                      :Uq       Else return joined input
                                ["abc","b b", "abc"]
                         Ãow    Map last item and reverse
                                ["abc","b b", "cba"]
                                Implicity output array joined with new lines
                                "abc
                                 b b
                                 cba"

```

Try it online!
> 2 votes

# Answer
# Jelly, 20 bytes

```
W;ḊW€$O‘z0ṚUoƊo33’ỌY

```

Try it online!

Assuming that unprintables can also be in the input.
> 2 votes

# Answer
# Stax, 10 bytes

```
▄▀τƒ○≡ë'▲.

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
{       start a block to repeat
  Mr    rotate matrix counter-clockwise
  0     actually just a literal 0
  x     retrieve "string" from x register, initially the input string
  rX    reverse, and write it back to register
  &     assign reversed "string" to 0 index of matrix (first row)
}4*     exectue block 4 times
m       output matrix as line-separated rows

```

Run this one
> 2 votes

# Answer
# C (gcc), ~~100~~ ~~103~~ 102 bytes

* Saved a byte thanks to ceilingcat; golfing an alternative solution.

```
o,O;v(char*_){for(O=puts(_,o=0)-2;O-++o;)printf("%c%*c\n",_[o],O,_[O-o]);for(o=O;~o;putchar(_[o--]));}

```

Try it online!
> 2 votes

# Answer
# Jelly,  ~~19~~  18 bytes

-1 thanks to Erik the Outgolfer (managing to use another repeat, , to inline my helper Link)

```
WẋL¬o1¦³ṚUƊ⁺ZƊ⁺o⁶Y

```

A full program.

**Try it online!**

### How?

```
WẋL¬o1¦³ṚUƊ⁺ZƊ⁺o⁶Y - Main Link: list of characters s
W                  - wrap s in a list
  L                - length of s
 ẋ                 - repeat (yielding a length(s) list of copies of s)
   ¬               - logical NOT (makes every element a zero - giving us a square of zeros)
             Ɗ     - last three links as a monad (say F(x)):
          Ɗ        -   last three links as a monad (say G(x)):
      ¦            -     sparse application...
     1             -       ...to indices: [1]
    o  ³           -       ...do: logical OR with the input (s)
                   -              (replaces the first list with the input)
        Ṛ          -     reverse               }
         U         -     upend (reverse each)  } (turn whole thing 180 degrees)
           ⁺       -   repeat previous link (i.e. G(that result))
            Z      -   transpose
              ⁺    - repeat previous link (i.e. F(that result))
               o⁶  - logical OR with a space character (replace all remaining zeros with spaces)
                 Y - join with newlines
                   - implicitly print

```

---

My 19 byters...

```
;⁶ɓJ»þ`n\«\aƊUṚ»ƊịY

```

Try this one, which works by building a table of indices filled with zeros and then indexing into the input with an extra space (in order to relace the 0s with spaces)

...and the one Erik improved to 18 for me:

```
o1¦³ṚU
WẋL¬ÇÇZƊ⁺o⁶Y

```

Try this one.
> 2 votes

# Answer
# , ~~113~~ 102 bytes

```
function(s,N=nchar(s),m=matrix(" ",N,N)){m[1,]=m[,1]=el(strsplit(s,""))
write(pmax(m,rev(m)),1,N,,"")}

```

Try it online!

*Thanks to JayCe for saving 6 bytes!*

Writes the string to the first row and column of the array. So long as the string contains only characters with ASCII codepoints greater or equal than 32 (space), which seems allowable by "alphanumeric characters", then the parallel maximum of the matrix and its reverse yields the appropriate matrix, which is then printed out by `write`.
> 2 votes

# Answer
# Java (JDK), 109 bytes

```
s->{int l=s.length,i=0;var r=new char[l][l--];for(char c:s)r[i][0]=r[0][i]=r[l-i][l]=r[l][l-i++]=c;return r;}

```

Try it online!

Returning a 2D array containing the characters to print. The inner of the array is filled with `\0` instead of spaces because no rules said spaces have to be used.
> 1 votes

# Answer
**C++, 232 231 bytes**

Edit: included the include statements in byte count, removed all white spaces, and removed include string.h, Thanks Dennis

Try it online!

```
#include <iostream>
#include <algorithm>
using namespace std;main(int c,char **a){string s=a[1];int x=s.length()-1,i(1);cout<<s<<endl;for(;i<x;++i)cout<<s[i]<<string(x-1,' ')<<s[x-i]<<endl;reverse(s.begin(),s.end());cout<<s<<endl;}

```
> 1 votes

# Answer
# PHP, 207 Bytes

```
$k=str_pad('',($L=mb_strlen($s=$argv[1]))-2,' ');$p=[];for($i=1;$i<=$L;$i++){$p[]=($j=mb_substr($s,$L-$i,1));if($i==1)$b=$s;elseif($i==$L)$b=implode('',$p);else$b=mb_substr($s,$i-1,1).$k.$j;echo$b.PHP_EOL;}

```

Not quite a creative entry, but it supports UTF-8 at least...
> 1 votes

# Answer
# , 34, 31 30 bytes

```
,(1|:@|.(2+#){.|.,:])@}.@}:,|.

```

Try it online!

## Explanation:

```
 ,(1|:@|.(2+#){.|.,:])@}.@}:,|.
                            ,   - append
                             |. - the reversed input to
  (                  )@}.@}:    - the input with the first and the last chars dropped and
                |.              - its reverse
                  ,.            - laminated to
                    ]           - the trimmed input (results in a matrix 2 x length )
              {.                - take as many rows (pad with empty lines)
         (2+#)                  - as is length of the input (2+length of the trimmed input)
       |.                       - rotate
   1                            - one position to the top
    |:@                         - and transpose
 '                              - prepend with the input

```
> 1 votes

# Answer
# Retina 0.8.2, 78 bytes

```
(.+).
$1¶$&
O$^r`.\G

+`^(.*)(.)(¶(.*).)
$1¶$2$4$3
^¶

T`p` `(?<=.¶.).*(?=.¶.)

```

Try it online! Handliy beating my previous attempt. Explanation:

```
(.+).
$1¶$&

```

Duplicate all but one character.

```
O$^r`.\G

```

Reverse the original.

```
+`^(.*)(.)(¶(.*).)
$1¶$2$4$3

```

Move characters from the duplicate to the original one at a time, creating a filled square.

Delete the blank line now that the duplicate has been processed.

```
T`p` `(?<=.¶.).*(?=.¶.)

```

Change all inner characters to spaces.
> 1 votes

# Answer
# APL (Dyalog Classic), 29 bytes

```
⊢⍪⌽⍪⍨1⌽⊢∘≢↑⍤1(↑⌽⍪¨⊢)∘(1↓¯1↓⊢)

```

Try it online!

Uses the same algorithm as my J solution.
> 1 votes

# Answer
# T-SQL, 179 bytes

```
DECLARE @ varchar(99),@n INT=2SELECT @=v FROM i PRINT @
a:PRINT SUBSTRING(@,@n,1)+SPACE(LEN(@)-2)+SUBSTRING(REVERSE(@),@n,1)SET @n+=1IF @n<len(@)GOTO a
IF LEN(@)>2PRINT REVERSE(@)

```

Input is taken via pre-existing table **i** with varchar field **v**, per our IO standards.
> 1 votes

# Answer
# Japt, ~~19~~ 18 bytes

Returns an array of lines.

```
¬íU¬w)mq¢ç)hJUw)hU

```

Try it

Saved a byte thanks to Oliver.
> 1 votes

# Answer
# VBA (Excel), 86 bytes

Using Immediate Window and Cell `[a1]` as input.

```
a=[a1]:b=StrReverse(a):c=Len(a):?a:For i=2To c-1:?Mid(a,i,1)Spc(c-2)Mid(b,i,1):Next:?b

```
> 1 votes

# Answer
# , 51 bytes

```
Ù:se ri
y$2o"mm2kÓ./&ò
dk2GddG:&&
dd'mdk$ëp'mdG

```

Try it online!

```
00000000: d93a 7365 2072 690a 7924 326f 1222 1b6d  .:se ri.y$2o.".m
00000010: 6d32 6bd3 2e2f 26f2 0a64 6b32 4764 6447  m2k../&..dk2GddG
00000020: 3a26 260a 6464 1627 6d64 6b24 16eb 7027  :&&.dd.'mdk$..p'
00000030: 6d64 47                                  mdG

```

```
Ù                                Duplicate line
 :se ri                          Enable reverse input.
y$                               Copy one line without line-break
  2o*<C-r>*"*<Esc>*                  With reverse input enabled, insert copied string in a new line twice
               mm                Set a mark in the last line
                 2kÓ./&ò         Go to second line, add a line break between each character
                                 This created the left edge of the square
dk2Gdd                           Delete first and last character of left edge
      G:&&                       Go to last line, repeat last substitution; this creates the right edge
dd                               Delete the final empty line that was just created
  *<C-v>*'md                       The right edge is currently below the square; delete it there
          k$*<C-v>*ëp              And put it in the right place
                   'mdG          Finally, remove excess new lines

```
> 1 votes

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


title: Hash collision: "NO" means "YES"

text:
# Question
Title: Hash collision: "NO" means "YES"
This Code Golf was inspired by the recent Daily WTF article You Can't Handle the True!, which features a string comparison written as:

```
String yes = "YES";
if ((delay.hashCode()) == yes.hashCode())

```

Imagine the trouble it would have caused for Steve's team if Java's `String.hashCode` method just happened to be implemented in a way that `"YES".hashCode() == "NO".hashCode()`. So, the challenge I propose here is:

> Write, in as few characters as possible, a hash function (I'll call it `h`) with a string parameter and integer return value, such that `h("YES")` is equal to `h("NO")`.

Of course, this would be trivial to do with a function like `def h(s): return 0`, which makes a hash collision for *every* string. To make this challenge more interesting, you must abide by the following additional rule:

> Of the *other* 18 277 possible strings consisting of three or fewer uppercase ASCII letters (`^[A-Z]{0,3}$`), there must be **no** hash collisions.

**Clarification** (pointed out by Heiko Oberdiek): The input string may contain characters other than `A-Z`, and your code **must** be able to hash arbitrary strings. (You may, however, assume that the input *is* a character string rather than a null pointer or an object of some other data type.) However, it does not matter what the return value is for strings that do not match `^[A-Z]{0,3}$`, as long as it's an integer.

Furthermore, to obfuscate the intent of this function:

> Your code must not include any of the letters 'Y', 'E', 'S', 'N', or 'O' (in either upper- or lowercase) within character or string literals.

Of course, this restriction doesn't apply to language keywords, so `else`, `return`, etc. are fine.

# Answer
# GolfScript: 19 chars (24 chars for named function)

```
26base.2107=59934*+

```

This is the body of the function. Assigning it to a named function `h` takes five more chars:

```
{26base.2107=59934*+}:h;

```

(The final semicolon can be omitted, if you don't mind leaving a copy of the code lying on the stack.)

The core of the hash function is `26base`, which calculates sum(26*n**k* · *a**k*; *k* = 1 .. *n*), where *n* is the number of characters in the input and *a**k* denotes the ASCII code of the *k*-th input character. For inputs consisting of uppercase ASCII letters, this is a collision-free hash function. The rest of the code compares the result to 2107 (the hash code of `NO`) and, if they're equal, adds 59934 to yield 2701 + 59934 = 62041, the hash code of `YES`.

For example output, see this online demo with test cases.
> 7 votes

# Answer
# 32-bit Python 2.x (19)

```
hash(w*9)%537105043

```

*RSA uses a semiprime modulus, and that makes it secure, so using one with my hash algorithm should surely make it even better!*1

This is a pure math function, works for all strings (hell, works for any hashable Python object), and doesn't contain any conditionals or special-casing! 32-bit Python can typically be called as `python-32` on most systems that have both installed2.

I've tested this, and it returns 18,278 different values for the 18,279 3-letter-or-less uppercase strings. Assigning this to a function takes 11 more bytes:

```
h=lambda w:hash(w*9)%537105043

```

and `h('YES') == h('NO') == 188338253`.

# 64-bit Python 2.x (19)

```
hash(w*2)%105706823

```

Same deal as above.

---

To come up with these numbers, a little bit of modular math was used. I was looking for a function `f` and a modulus `n` such that `hash(f('YES')) % n == hash(f('NO')) % n`. This is equivalent to testing that `n` divides `d = hash(f('YES')) - hash(f('NO'))`, i.e. we only have to check the factors of `d` for suitable values of `n`.

The ideal `n` is in the neighbourhood of 20000\**2 to reduce the chance of a birthday paradox collision. Finding a suitable `n` turns out to be a bit of trial and error, playing with all the factors of `d` (there usually aren't many) and different choices for the function `f`. Notice though that the trial and error is only needed because I wanted to make `n` as small as possible (for golfing). If that wasn't a requirement, I could just choose `d` as my modulus, which is usually sufficiently large.

Note too that you can't pull this trick off using just `f(s) = s` (the identity function) because the rightmost character of the string has essentially a linear relationship (actually an `XOR` relationship) with the final hash (the other characters contribute in a much more nonlinear way). The repetition of the string therefore ensures that the differences between the strings are amplified to eliminate the effect of changing only the rightmost character.

---

1 This is patent nonsense.
2 Python string hashing depends on major version (2 vs 3) and bitness (32-bit vs 64-bit). It does not depend on platform AFAIK.
> 55 votes

# Answer
# Perl, 53 49 40 bytes

```
sub h{hex(unpack H6,pop)-20047||5830404}

```

**Test:**

```
h('YES') = 5830404
h('NO')  = 5830404
Keys:   18279
Values: 18278

```

The hash values for `YES` and `NO` are the same and there are 18279 strings `^[A-Z]{0,3}$`, which are collision free except for the only collision for `YES` and `NO`.

**Ungolfed:**

```
sub h {
    hex(unpack("H6", pop())) - 20047 || 5830404;
    # The argument is the first and only element in the argument array @_.
    # "pop" gets the argument from array @_ (from the end).
    # The first three bytes of the argument or less, if the argument
    # is shorter, are converted to a hex string, examples:
    #   "YES" -> "594553"
    #   "NO"  -> "4e4f"
    # Then the hex string is converted to a number by function "hex":
    #   0x594553 = 5850451
    #   0x4e4f   =   20047
    # The value for "NO" is subtracted, examples:
    #   case "YES": 5850451 - 20047 = 5830404
    #   case "NO":    20047 - 20047 =       0
    # If the argument is "NO", the subtraction is zero, therefore
    # 5830404 is returned, the result of "YES".
}

# Test
my %cache;
sub addcache ($) {$cache{$_[0]} = h($_[0])}

# Check entries 'YES' and 'NO'
addcache 'YES';
addcache 'NO';
print "h('YES') = $cache{'YES'}\n";
print "h('NO')  = $cache{'NO'}\n";

# Fill cache with all strings /^[A-Z]{0-3}$/
addcache '';
for my $one (A..Z) {
    addcache $one;
    for (A..Z) {
        my $two = "$one$_";
        addcache $two;
        for (A..Z) {
            my $three = "$two$_";
            addcache $three;
        }
    }
}
# Compare number of keys with number of unique values
my $keys = keys %cache;
my %hash;
@hash{values %cache} = 1 x $keys;
$values = keys %hash;
print "Keys:   $keys\n";
print "Values: $values\n";

```

# Older version, 49 bytes

Since the new algorithm is slightly different, I keep the old version.

```
sub h{($_=unpack V,pop."\0"x4)==20302?5457241:$_}

```

**Test:**

```
h('YES') = 5457241
h('NO')  = 5457241
Keys:   18279
Values: 18278

```

**Ungolfed:**

```
sub h {
    $_ = unpack('V', pop() . ($" x 4);
        # pop():  gets the argument (we have only one).
        # $" x 4: generates the string "    " (four spaces);
        #   adding the four spaces ensures that the string is long
        #   enough for unpack's template "V".
        # unpack('V', ...): takes the first four bytes as
        #   unsigned long 32-bit integer in little-endian ("VAX") order.
    $_ == 20302 ? 5457241 : $_;
        # If the hash code would be "NO", return the value for "YES".
}

```

**Edits:**

* Using `"\0"` as fill byte saves 4 bytes in comparison to `$"`.
> 38 votes

# Answer
# Python: 63

An incredibly lame solution:

```
def h(s):
 try:r=int(s,36)
 except:r=0
 return(r,44596)[r==852]

```

It works by interpreting alphanumeric strings as base-36 numbers, and returning 0 for everything else. There's an explicit special case to check for a return value of 852 (NO), and return 44596 (YES) instead.
> 7 votes

# Answer
# Pure Bash, 29 bytes (function body)

```
h()(echo $[n=36#$1,n-852?n:44596])

```

This simply treats the input string as a base 36 number and converts to decimal, then deals with the special `NO` case.

Output:

```
$ h A
10
$ h B
11
$ h CAT
15941
$ h NO
44596
$ h YES
44596
$ h ZZZ
46655
$

```
> 6 votes

# Answer
# Ruby, 51 bytes

```
h=->s{d=s.unpack('C*').join;d=~/896983|^7879$/?0:d}

```

testing code :

```
h=->s{d=s.unpack('C*').join;d=~/896983|^7879$/?0:d}

puts 'YES : '+h.call('YES').to_s # 0
puts 'NO : '+h.call('NO').to_s # 0
puts 'NOX : '+h.call('NOX').to_s # 787988
puts 'FNO : '+h.call('FNO').to_s # 707879
puts ''

values = Hash[]
n = 0
('A'..'Z').each{|c|
    values[c] = h.call(c)
    ('A'..'Z').each{|c2|
        values[c+c2] = h.call(c+c2)
        ('A'..'Z').each{|c3|
            values[c+c2+c3] = h.call(c+c2+c3)
            n += 1
        }
    }
}
puts 'tested '+n.to_s
duplicate = Hash.new()

values.each{|k, e|
    if duplicate.has_key?(e)
        puts 'duplicate : "'+k+'" = "'+duplicate[e].to_s+'" ('+e.to_s+')'
    else
        duplicate[e] = k
    end
}

```

output :

```
YES : 0
NO : 0
NOX : 787988
FNO : 707879

tested 17576
duplicate : "YES" = "NO" (0)

```
> 5 votes

# Answer
# Java - 94 77

```
int h=new BigInteger(s.getBytes()).intValue();return Math.abs(h-(h^5835548));

```

Unrolled:

```
int hashCode(String s) {
    int h = new BigInteger(s.getBytes()).intValue();
    return Math.abs(h - (h ^ 5835548));
}

```

Narrative - for `f(s) = BigInteger(s.getBytes())`:

* `f("YES") xor f("NO") = 5835548`
* So `f("YES") xor 5835548 = f("NO")`
* So `f("YES") - (f("YES") xor 5835548) = f("NO") - (f("NO") xor 5835548)` am I right?
> 5 votes

# Answer
# Javascript (*ES6*) 54 bytes

```
f=s=>[x.charCodeAt()for(x of s)].join('')^7879||897296

```

```
f('YES'); // 897296
f('NO'); // 897296
f('MAYBE'); // -824036582

```
> 5 votes

# Answer
# CJam, 15 bytes

```
q42b_*81991617%

```

Works as the GolfScript solution below. Try it online.

---

# GolfScript, 17 bytes

```
42base.*81991617%

```

This approach builds on the answers of nneonneo and Ilmari Karonen.

### How it works

```
42base    # Interpret the input string as a base 42 number.
          # "YES" is [ 89 69 83 ] in ASCII, so it becomes 42 * (42 * 89 + 69) + 83 = 159977.
          # "NO" is [ 78 79 ] in ASCII, so it becomes 42 * 78 + 79 = 3355.
          #
.*        # Square. "YES" becomes 25592640529, "NO" becomes 11256025.
          #
81991617% # "YES" becomes 11256025.

```

### Choosing an algorithm

We start with `{b base}:h`, i.e., the input string is considered a base-b number. As long as `b > 25`, `h` is inyective.

We get a collision for strings "YES" and "NO" if we modify `h` in the following way: `{x base n}:h`, where `n` is a divisor of `"YES" h "NO" h -`.

Unfortunately, this means we'll also get a collision for, e.g., `YET` and `NP`. To prevent this, we have to modify the base-b number in a non-linear fashion before taken the modulus.

The shortest way to accomplish this in GolfScript is to multiply the base-b number with itself (i.e., squaring it). `h` is now `{base b .* n %}:h`.

All that remains to do is finding suitable values for `b` and `n`. We can accomplish this by brute force:

```
for((b=26;b<100;b++)){
    P=($(golfscript <<< "['YES' 'NO']{$b base.*}/-" | factor | cut -d\  -f 2-))

    for n in $(for((i=0;i<2**${#P[@]};i++)){
        for((n=1,j=0;j<${#P[@]};n*=${P[j]}**((i>>j)&1),j++)){ :;};echo $n;} | sort -nu);{
            [[ $n -ge 18277 && $(echo -n '' {A..Z}{,{A..Z}{,{A..Z}}} |
                golfscript <(echo "' '/[{$b base.*$n%}/].&,")) = 18278 ]] &&
            echo $b $n && break
    }
}

```

The shortest possible values for `b n` are:

```
37 92176978
42 81991617

```

### Testing

```
$ echo -n '' {A..Z}{,{A..Z}{,{A..Z}}} |
     golfscript <(echo '{42base.*81991617%}:h;" "/{.`"\t"+\h+puts}/') |
     sort -k 2n |
     uniq -Df 1
"NO"    11256025
"YES"   11256025

```
> 5 votes

# Answer
# JavaScript (ES6) - 38 characters (33 char function body)

```
h=s=>(a=btoa(s))=="WUVT"|a=="Tk8="||+s

```

### Test Cases:

```
var l = console.log;
l(  h("YES")  );                // 1
l(  h("NO")  );                 // 1
l(  h("ABC")  );                // NaN
l(  h("WIN")  );                // NaN
l(  h("YES") === h("NO")  );    // true
l(  h("ABC") === h("WIN")  );   // false
l(  h("WIN") === h("YES")  );   // false

l(  NaN === NaN  );             // false

```

### Explanation:

First of all, let me introduce you to `NaN` \- "Not A Number" - in JavaScript. It is a number:

```
typeof NaN  // number

```

Just like:

```
typeof 42   // number

```

Its special property is that it *never equals itself*. My function returns `1` if the string is `YES` or `NO`, and `NaN` for any other string.

So, this doesn't break the rules, because there would be no hash collision for any other string ;) ( `NaN !== NaN` shown above in test cases).

And my dream comes true: beating Bash, Perl and Ruby in code length!

### Ungolfed Code:

```
h =  // h is a function
s => // s = string argument

( ( a = btoa(s) )  ==  "WUVT" | a == "Tk8=" )
        ^-- returns some value stored in `a`

```

If that value is `"WUVT"` or `"Tk8="`, return `1`. Else, return

```
+s // parseInt(s, 10)

```

which would be `NaN`.
> 3 votes

# Answer
# Python 92

```
n=int("".join(map(str,map(ord,raw_input()))))    # hashing function
print n if 1+(n**2-904862*n)/7067329057 else-1   # input validation

```

The hashing function concatenates the ordinal values of the ASCII characters, the print statement ensures that the two desired inputs collide.
> 2 votes

# Answer
# ECMAScript 6 (30 bytes)

I've tried to avoid variable assignment, return, and function keyword, and this looks like a great way to avoid all that nonsense (it also looks like functional programming, in a way). Unlike other solutions, it doesn't depend on `btoa` or `atob`, which isn't ECMAScript 6, but HTML5. `0+` is needed, so it could parse arbitrary strings.

```
a=>parseInt(0+a,36)-852||43744

```
> 2 votes

# Answer
# Java - 45 (or 62?)

I have no idea how to fairly score given what one needs to run a program in Java, do I need to include the function definition? Feel free to edit and adjust my score appropriately. Currently I'm scoring the same way as the @OldCurmudgeon answer. Add 17 for `int h(String t){}` if it's required:

```
int h=t.hashCode();return h*h*3%1607172496;

```

Ungolfed with test harness:

```
import static org.junit.Assert.*;

import java.util.*;

import org.junit.Test;

public class YesNo {
  @Test
  public void testHashValue() {
    YesNo yesNo = new YesNo();
    Set<Integer> set = new HashSet<>();

    assertEquals(yesNo.hash("YES"), yesNo.hash("NO"));

    set.add(yesNo.hash(""));
    for(char i = 'A'; i <= 'Z'; i++) {
      set.add(yesNo.hash("" + i));
      for(char j = 'A'; j <= 'Z'; j++) {
        set.add(yesNo.hash("" + i + j));
        for(char k = 'A'; k <= 'Z'; k++) {
          set.add(yesNo.hash("" + i + j + k));
        }
      }
    }
    assertEquals(18278, set.size());
  }

  int hash(String toHash) {
    int hashValue=toHash.hashCode();
    return hashValue*hashValue*3%1607172496;
  }
}

```
> 2 votes

# Answer
And the looser is...

# Conveyor, 145 chars

```
 I
>#<
 26*)2**\88
 >========*
 ^    \ \+-
 ^=====#==<
5**222P:
5======<
5***26*)*(\P\:@e25*:*)4*,F
>==============#=========
             P,F

```

Basically this program does some kind of base 26 thing on the chars. After that it checks if the hash is equal to 12999 (The hash code of YES) and if so print 404 (the hashcode of NO), else it will just print the hashcode.

Conveyor is a language made by me that is currently in beta-stages but an interpreter along with some examples and source code can be found here: https://github.com/loovjo/Conveyor
> 1 votes

# Answer
# C# 4.5 (112 bytes)

```
int h(string s){int code=s.Select((v,i)=>((int)v)<<(2*(i-1))).Sum();return(code|1073742225)|(code|-2147483569);}

```

Working (?) version of undergroundmonorail's attempt, in C#. Concats the bytes in the string into a 32-bit integer (only works up to 4 characters), then ORs the result against the result for "YES" and "NO" respectively, then ORs those together.

While it may collide at some point, it shouldn't happen for any ^\[A-Z\]{2,3}$ other than "YES" and "NO".
> 0 votes

# Answer
# No Comment - 31 (function content: 26)

```
'=|*==|,,|+|"#|[|,  |+|-%3|]*|:

```

Pretty simple solution. ;) Works for any and all UTF-8 strings.

**EXPLANATION:** `'` is, obviously, the function. First, it checks whether `*` (it's input) is equal to `|,,|+|"#|` (`|NO|`). If it is, it returns `|, |+|-%3|` (`|YES|`) - otherwise, it just returns `*`.
> 0 votes

# Answer
**C 54**

```
h(char *c){int d=*(int*)c-20302;return d*(d-5436939);}

```

Convert string to integer -"NO" and multiply that by by same value + "NO"-"YES" to get 0 for "NO" and "YES" and non-zero for any other string in the range specified.

All values on Windows 7 machine if there are any endian concerns.
> 0 votes

# Answer
# Stax, ~~12~~ 11 bytes

```
ì≤ïøZ‼kESa←

```

Run and debug it

Translates input as base-36, subtracts 852, then replaces 0 with 43744. It's a port of Konrad's excellent solution.
> 0 votes

# Answer
Here's a super lame one. **SO LAME IT DOESN'T EVEN WORK**

# Python 2.7 - 79 bytes

```
def h(s):n=sum(100**i*ord(c)for i,c in enumerate(s));return (n-7978)*(n-836989)

```

First we get the sum of (each character's ascii value) * 100^(that character's position in the string). Then we multiply (that result - 7978) and (that result - 836989) to get our final answer. 7978 and 836989 are the results for "YES" and "NO" of the first bit, so for YES and NO we're multiplying by 0.

This shouldn't have any collisions? I don't feel like testing against 18000 possible counterexamples, but if there was an unintended collision I can throw another 0 on that `100` and then there *really* shouldn't be any collisions.

Disappointed that I couldn't use a `lambda` for this, but I didn't want to do the whole calculation twice so I had to save it to a variable.

Please don't let this win. It's super lame and I don't deserve it.
> -1 votes

# Answer
# CoffeeScript - 36

Should return `1` for `YES` and `NO`, and whatever garbled nonsense `atob` produces for everything else that's not a base64 string.

```
h=(s)->_=atob s;_ in["`D","4"]&&1||_

```

The JavaScript equivalent (*not* the JS code from the CS compiler):

```
function h( s ) {
    var _ = atob( s );

    if( _ === "`D" || _ === "4" )
        return 1;
    else
        return _;
}

```
> -1 votes

---
Tags: code-golf, restricted-source, hashing
---


# Question
Title: Converting a number from Zeckendorf Representation to Decimal
### About Zeckendorf Representations/Base Fibonacci Numbers

This is a number system which uses Fibonacci numbers as its base. The numbers consist of 0 and 1's and each 1 means that the number contains the corresponding Fibonacci number, and 0 means it does not.

For example, let's convert all natural numbers \<=10 to base Fibonacci.

* 1 will become 1, because it is the sum of 1, which is a Fibonacci number,
* 2 will become 10, because it is the sum of 2, which is a Fibonacci number, and it does not need 1, because we already achieved the desired sum.
* 3 will become 100, because it is the sum of 3, which is a Fibonacci number and it does not need 2 or 1 because we already achieved the desired sum.
* 4 will become 101, because it is the sum of \[3,1\], both of which are Fibonacci numbers.
* 5 will become 1000, because it is the sum of 5, which is a Fibonacci number, and we do not need any of the other numbers.
* 6 will become 1001, because it is the sum of the Fibonacci numbers 5 and 1.
* 7 will become 1010, because it is the sum of the Fibonacci numbers 5 and 2.
* 8 will become 10000, because it is a Fibonacci number.
* 9 will become 10001, because it is the sum of the Fibonacci numbers 8 and 1.
* 10 will become 10010, because it is the sum of the Fibonacci numbers 8 and 2.

Let's convert a random Base Fibonacci number, 10101001010 to decimal: First we write the corresponding Fibonacci numbers. Then we compute the sum of the numbers under 1's.

```
 1   0   1   0   1   0   0   1   0   1   0
 144 89  55  34  21  13  8   5   3   2   1  -> 144+55+21+5+2 = 227.

```

Read more about Base Fibonacci numbers: link, it also has a tool which converts regular integers to base Fibonacci. You can experiment with it.

### Now the Question:

Your task is to take a number in the Zeckendorf Representation, and output its decimal value.

Input is a string which contains only 0 and 1's (although you can take the input in any way you want).

Output one number in decimal.

Test cases: (in the format input-\>output)

```
 1001 -> 6
 100101000 -> 73
 1000000000 -> 89
 1001000000100100010 -> 8432
 1010000010001000100001010000 -> 723452

```

This is code-golf, so the shortest answer in bytes wins.

Note: The input will not contain any leading 0's or consecutive 1's.

# Answer
# Taxi, ~~1987~~ 1927 bytes

*-60 bytes due to the realization that linebreaks are optional.*

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 1 r 1 l 4 r 1 l.[B]Switch to plan C if no one is waiting.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 3 l.Pickup a passenger going to Narrow Path Park.Pickup a passenger going to Sunny Skies Park.Go to Zoom Zoom:n.Go to Sunny Skies Park:w 2 l.Go to Narrow Path Park:n 1 r 1 r 1 l 1 r.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan B.[C]1 is waiting at Starchild Numerology.1 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 3 l 3 l 2 r.Pickup a passenger going to Addition Alley.Pickup a passenger going to Cyclone.Go to Cyclone:w 1 r 4 l.[D]Pickup a passenger going to Addition Alley.Pickup a passenger going to Cyclone.Go to Addition Alley:n 2 r 1 r.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Multiplication Station.Go to Zoom Zoom:n.Go to Narrow Path Park:w 1 l 1 l 1 r.Switch to plan E if no one is waiting.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 1 r.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:n 1 r 2 l.Pickup a passenger going to Joyless Park.Go to Joyless Park:n 2 l 1 r 1 r.Go to Addition Alley:w 1 r 2 l 1 l.Pickup a passenger going to Cyclone.Go to Cyclone:n 1 l 1 l.Pickup a passenger going to Addition Alley.Switch to plan D.[E]Go to Addition Alley:w 1 l 1 r 1 l.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:n 1 r.Go to Joyless Park:e 1 r 2 l.Pickup a passenger going to Addition Alley.[F]Switch to plan G if no one is waiting.Pickup a passenger going to Addition Alley.Go to Fueler Up:w 1 l.Go to Addition Alley:n 3 l 1 l.Pickup a passenger going to Addition Alley.Go to Joyless Park:n 1 r 1 r 2 l.Switch to plan F.[G]Go to Addition Alley:w 1 r 2 l 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:n 1 r 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.

```

Try it online!

Because I don't return to the Taxi Garage at the end, my boss fires me, so it exits with an error.
> 19 votes

# Answer
# Perl 6, ~~28~~ 23 bytes

```
{[+] (1,2,*+*...*)Z*$_}

```

Try it online!

Anonymous codeblock that takes a list of `1`s and `0`s in LSB ordering and returns a number.

### Explanation:

```
{                     }   # Anonymous codeblock
 [+]                      # The sum of
     (1,2,*+*...*)        # The infinite Fibonacci sequence starting from 1,2
                  Z*      # Zip multiplied by
                    $_    # The input list in LSB form

```
> 11 votes

# Answer
# Jelly, 5 bytes

```
T‘ÆḞS

```

A monadic link accepting a list in Little-endian form (i.e. from the LSB at the left to MSB at the right).

**Try it online!**
> 7 votes

# Answer
# Wolfram Language (Mathematica), 35 32 29 28 bytes

```
Fibonacci[Range@Tr[#!]+1].#&

```

Try it online!
> 7 votes

# Answer
# Python 2, 43 bytes

```
a=b=0
for x in input():b+=a+x;a=b-a
print b

```

Try it online!

Takes input as a list. The update is a shorter version of `a,b=b+x,a+b+x`, which is like the Fibonacci update `a,b=b,a+b` if you ignore `x`.

---

# Python 2, 45 bytes

```
f=lambda n,a=1,b=1:n and n%10*b+f(n/10,b,a+b)

```

Try it online!

Takes input as decimal numbers.
> 5 votes

# Answer
# Haskell, 38 bytes

```
f=1:scanl(+)2f
sum.zipWith(*)f.reverse

```

Try it online!

Takes input as a list of 1s and 0s.

## Explanation

---

```
f=1:scanl(+)2f

```

Makes a list of the Fibonacci numbers sans the first one, in variable `f`.

```
sum.zipWith(*)f.reverse

```

Takes the input list `reverse`s it the multiplies each entry by the corresponding entry in `f`, then `sum`s the results.

# Haskell, 30 bytes

```
f=1:scanl(+)2f
sum.zipWith(*)f

```

Try it online!

If we take input in with the least significant bit first we don't need `reverse` so we can save 8 bytes.
> 4 votes

# Answer
# Brain-Flak, ~~110~~, ~~102~~, ~~96~~, ~~94~~, ~~78~~, 74 bytes

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

```

Try it online!
> 3 votes

# Answer
# Pyth, 13 bytes

Most of this (8 bytes) is just generating the Fibonacci numbers.

```
s*V_m=+Z|~YZ1

```

Try it out with this test suite!

Explanation:

```
s*V_m=+Z|~YZ1QQ     Autofill variables
    m=+Z|~YZ1Q      Generate the first length(input) Fibonacci numbers as follows:
       Z             Start with Z=0
         ~YZ         And Y=[] (update it to Y=Z, return old Y)
        |   1        if Y is [], then replace with 1
      +              Sum Z and Y
     =               Replace Z with sum
    m                Repeat process
             Q       once for each element of the input
   _                Reverse the order of the Fibonacci numbers
 *V                 Vectorize multiplication
s                   Sum

```
> 3 votes

# Answer
# , <sub>~~24~~</sub> 14 bytes

```
#.~2+&%&1~#-#\

```

Try it online!

Golfed down the 24-byte version that uses the mixed base for Fibonacci.

### How it works

```
#.~2+&%&1~#-#\  Example input: y=1 0 0 1 0
          #-#\  Length minus 1-based indices; 4 3 2 1 0
   2     ~      Starting from 2, run the following (4,3,2,1,0) times:
    +&%&1         Given y, compute 1 + 1 / y
                The result is 13/8 8/5 5/3 3/2 2
#.~             Mixed base conversion of y into base above; 2+8=10

```

---

# , 21 bytes

```
1#.|.*[:+/@(!~#-])\#\

```

Try it online!

Refined version of Galen Ivanov's 25-byte solution.

Uses the diagonal sum of Pascal's triangle, which is equivalent to the sum of binomial coefficients:

\\$ F\_n = \sum\limits\_{i=0}^{n} {}\_{n-i}C\_{i} \\$

### How it works

```
1#.|.*[:+/@(!~#-])\#\
                       Example input: 1 0 0 1 0
                   #\  Generate 1-based index; 1 2 3 4 5
      [:          \    For each prefix of above... (ex. 1 2 3)
              #-]        Subtract each element from the length (ex. 2 1 0)
           (!~   )       Compute binomial coefficient (ex. 3C0 + 2C1 + 1C2)
        +/@              Sum
                       The result is Fibonacci numbers; 1 2 3 5 8
   |.*                 Multiply with mirrored self; 0 2 0 0 8
1#.                    Sum; 10

```

---

# , 24 bytes

```
3 :'y#.~|.(1+%)^:(<#y)2'

```

Try it online!

Monadic explicit verb. Generates the mixed base that represents the Fibonacci base, and then feeds into base conversion `#.`.

### How it works

```
y#.~|.(1+%)^:(<#y)2  Explicit verb, input: y = Fibonacci digit array, n = length of y
      (1+%)          x -> 1 + 1/x
           ^:(<#y)2  Apply the above 0..n-1 times to 2
                     The result looks like 2/1, 3/2, 5/3, 8/5, 13/8, ...
    |.               Reverse
                     Now, if it is fed into #. on the left, the digit values become
                     ...(8/5 * 5/3 * 3/2 * 2/1), (5/3 * 3/2 * 2/1), (3/2 * 2/1), 2/1, 1
                     which is ... 8 5 3 2 1 (Yes, it's Fibonacci.)
y#.~                 Convert y to a number using Fibonacci base

```

---

## Alternatives

### , 27 bytes

```
}.@(+#{.3#{.)^:(<:@#)@(,&0)

```

Try it online!

The idea:

```
 1  0  0  1  0  1
-1 +1 +1
------------------
    1  1  1  0  1
   -1 +1 +1
------------------
       2  2  0  1
      -2 +2 +2
------------------
          4  2  1
         -4 +4 +4
------------------
             6  5
            -6 +6 +6 <- Add an imaginary digit that has value 1
---------------------
               11  6
              -11+11
---------------------
                  17 <- the answer

```

### , 30 bytes

```
0.5<.@+(%:5)%~(-:>:%:5)#.,&0 0

```

Try it online!

This one took the most effort to build. Uses the closed-form expression with rounding trick. In the expression, 0th and 1st values are 0 and 1 respectively, so the actual digit power must start with 2.

```
0.5<.@+(%:5)%~(-:>:%:5)#.,&0 0  Tacit verb.
                         ,&0 0  Add two zeroes at the end
              (-:>:%:5)#.       Convert to a number using base phi (golden ratio)
       (%:5)%~                  Divide by sqrt(5)
0.5<.@+                         Round to nearest integer

```

While the error (`((1-sqrt(5))/2)^n` terms) may build up, it never exceeds 0.5, so the rounding trick works up to infinity. Mathematically:

\\$ \max(|error|) = \frac{1}{\sqrt{5}} \sum\limits\_{1}^{\infty} (\frac{1-\sqrt{5}}{2})^{2n} = \frac{1}{\sqrt{5}} \sum\limits\_{0}^{\infty} (\frac{1-\sqrt{5}}{2})^{n} = \frac{\sqrt{5}-1}{2\sqrt{5}} \< \frac{1}{2} \\$
> 3 votes

# Answer
# 05AB1E, ~~11~~ ~~9~~ 8 bytes

```
vyiNÌÅfO

```

Try it online!

Explanation:

```
v             : For each character in input string (implicit) in LSB order
  yi          : If the current character is truthy (1)
    NÌ        : Add 2 to the current index
       ÅfO    : Add the fibonacci of this number to the stack

```
* *-2 bytes*: Thanks to @KevinCruijssen for pointing out small ways to shorten this code!
* *-1 byte*: Thanks to @JonathanAllan for pointing out LSB order for input!
> 2 votes

# Answer
# MathGolf, ~~8~~ 6 bytes

```
{î)f*+

```

Try it online!

## Explanation

```
{        Start block (foreach in this case)
 î)      Push loop index (1-based) and increment by 1
   f     Get fibonacci number of that index
    *    Multiply with the array value (0 or 1)
     +   Add top two elements of stack. This implicitly pops the loop index the first iteration, which makes the addition become 0+a, where a is the top of the stack.

```

Saved 1 byte thanks to JoKing, and another byte thanks to LSB ordering.
> 2 votes

# Answer
# Red, 142, 126 106 bytes

```
func[a][b: copy[1 1]reverse a s: 0 n: 1
until[s: b/1 * a/:n + s insert b b/1 + b/2(n: n + 1)> length? a]s]

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 23 bytes

```
0?
;
+`1;(1*);
;1$1;1
1

```

Try it online! Link includes the faster test cases. Explanation:

```
0?
;

```

Insert separators everywhere and delete any zeros. For example, `1001` becomes `;1;;;1;`.

```
+`1;(1*);
;1$1;1

```

Repeatedly replace each `1` with a `1` in each of the next two places, as the sum of their values equals the value of the original `1`. `1`s therefore migrate and accumulate until they reach the last two places, which (due to the newly added separator) now both have value `1`.

```
1

```

Count the `1`s.
> 1 votes

# Answer
# Python 3, 63 bytes

```
a=b=n=1
for i in input()[::-1]:n+=b*int(i);a,b=b,a+b
print(n-1)

```

Try it online!

Takes input through STDIN as a string.
> 1 votes

# Answer
# Ruby, 39 bytes

```
->n{a,b=0,1;n.digits.sum{|x|x*b=a+a=b}}

```

Try it online!
> 1 votes

# Answer
# Stax, 6 bytes

```
çéC◘0â

```

Run and debug it

```
:1F^|5+           #Full program, unpacked, implicit input as array
:1                #Get indicies of truthy
  F               #Use rest of program to loop through elements
   ^              #Increment current element
    |5+           #Get n-th fib and Add

```

Pretty straight forward. LSB Ordering.
> 1 votes

# Answer
# Brain-Flak, 40 bytes

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

```

Try it online!
> 1 votes

# Answer
# C (gcc), 63 bytes

Takes input as an array of `1`'s and `0`'s, along with the length of the array. This solution is a rather straight-forward backwards loop.

```
f(_,l,a,b,t)int*_;{a=b=1;for(t=0;l--;b=(a+=b)-b)t+=a*_[l];_=t;}

```

Try it online!
> 1 votes

# Answer
# Prolog (SWI), 74 bytes

```
\D-->[X,Y],{D is 2*X+Y};[D];a,\D.
a,[A],[B]-->[X,Y,Z],{A is X+Y,B is X+Z}.

```

Try it online!

Takes input as a list of integers 1 and 0 with the most significant bit first.
> 1 votes

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

A port of xnor's answer. Takes input as a BigInt literal.

```
f=(n,a=1n,b=a)=>n&&n%10n*b+f(n/10n,b,a+b)

```

Try it online!

---

# JavaScript (ES6), 44 bytes

Takes input as an array of characters, in LSB-first order.

```
s=>s.map(k=>t+=k*(z=x,x=y,y+=z),x=t=0,y=1)|t

```

Try it online!
> 0 votes

# Answer
# Japt `-x`, 9 bytes

```
Ë*MgUÊa´E

```

Try it
> 0 votes

# Answer
# Actually, 8 bytes

```
;r⌐@░♂FΣ

```

Try it online!

Input is taken as a list of bits in LSB-first order.

Explanation:

```
;r⌐@░♂FΣ
;r        range(0, len(input))
  ⌐       add 2 to every element in range (range(2, len(input)+2))
   @░     filter: take values in range that correspond to 1s in input
     ♂F   Fibonacci number at index of each element in list (Actually uses the F(0)=F(1)=1 definition, which is why we needed to add 2 earlier)
       Σ  sum

```
> 0 votes

# Answer
# Powershell, 68 bytes

```
param($s)$b=1
$s[$s.Length..0]|%{$a,$b=$b,($a+$b)
$x+=($_-48)*$b}
$x

```

Test script:

```
$f = {
param($s)$b=1
$s[$s.Length..0]|%{$a,$b=$b,($a+$b)
$x+=($_-48)*$b}
$x
}

@(
    ,("1001", 6)
    ,("100101000", 73)
    ,("1000000000", 89)
    ,("1001000000100100010", 8432)
    ,("1010000010001000100001010000", 723452)
) | % {
    $s,$e = $_
    $r = &$f $s
    "$($r-eq$e): $r"
}

```

Output:

```
True: 6
True: 73
True: 89
True: 8432
True: 723452

```
> 0 votes

# Answer
# Java (OpenJDK 8), 65 bytes

Pretty small for a Java answer to I'm happy with that. Takes input as a LSB-first ordered array of ints.

```
d->{int s=0,f=1,h=1;for(int i:d){s+=i>0?f:0;f=h+(h=f);}return s;}

```

Try it online!

**Ungolfed**

```
d->{                        // Lambda function that takes array of ints
    int s=0,f=1,h=1;        // Initialise sum and fibonacci vars
    for(int i:d){           // Loop through each input integer
        s+=i>0?f:0;         // If it's 1 add current fibonacci number to sum
        f=h+(h=f);          // Increase fibonacci number
    }return s;              // return sum
}

```
> 0 votes

# Answer
# Z80Golf, 34 bytes

```
00000000: dde1 f1b7 2819 fe30 2812 4504 aff5 3cf5  ....(..0(.E...<.
00000010: d1f1 82d5 f510 f9c1 f17c 8067 2c18 e3dd  .........|.g,...
00000020: e5c9                                     ..

```

Example with input 1001-Try it online!

Example with input 100101000-Try it online!

Assembly:

```
zeck:		; input=push on stack in MSB order (eg top is LSB) output=reg h
pop ix		; save return addr in ix
f:
pop af		; get next digit
or a
jr z, return	; if current digit==0, return
cp 0x30
jr z, skip	; if current digit=='0' (e.g. not '1'), skip loop
ld b, l		; find fib of counter
fib:
	inc b	; 1-indexing for func to work
	xor a	; set a to 0 (1st fibo num)
	push af
	inc a	; set a to 1 (2nd fibo num)
	push af
	fib_loop:
		pop de
		pop af
		add d
		push de
		push af
		djnz fib_loop
pop bc		; get the fibo num just calculated
pop af		; pop just to reset stack frame
ld a, h
add b		; add current fibo number to sum
ld h, a
skip:
inc l		; increment counter reg
jr f		; repeat loop
return:
push ix		; push the return addr to ret to it
ret

```
> 0 votes

---
Tags: code-golf, fibonacci
---


title: Amidakuji (阿弥陀籤) simplification

text:
# Question
Title: Amidakuji (阿弥陀籤) simplification
If you have ever had any exposure to Japanese or East Asian culture you will have surely encountered the Amidakuji game:

As Wikipedia explains, it is a type of lottery drawn on paper and used to randomly select a permutation of N items.

For example, it may be used to randomly assign a starting sequence to N people, or N prizes to N people, and so on.

The trick to understanding why the game represents a permutation is to realize that every horizontal stroke (called a "leg") **swaps** its two items in place.

The same Wikipedia page also explains that each permutation P of N items corresponds to an infinite number of Amidakuji diagrams. The one(s) with the least number of horizontal strokes (legs) are called the "primes" of that particular permutation P.

Your task is to receive an Amidakuji diagram with 2 or more vertical lines (in this example they are 6) in this format (minus the letters):

```
A B C D E F
| | | | | |
|-| |-| |-|
| |-| |-| |
| | | | |-|
| |-| |-| |
| | |-| |-|
| | |-| | |
|-| | |-| |
|-| |-| | |
| |-| | |-|
| | | | | |
B C A D F E

```

And produce one of its primes (again, minus the letters):

```
A B C D E F
| | | | | |
|-| | | |-|
| |-| | | |
| | | | | |
B C A D F E

```

The first and last lines with the letters are **not** part of the format. I have added them here to show the permutation. It is also **not** required that the first or last lines contain no legs `|-|`, **nor** that the output be as compact as possible.

This particular input example is one of the (infinite) ASCII representations of the Amidakuji diagram at the top of the Wikipedia page.

There is one non-obvious rule about these ASCII diagrams: adjacent legs are forbidden.

```
|-|-|  <-  NO, this does not represent a single swap!

```

Wikipedia explains a standard procedure to obtain a prime from a diagram, called "bubblization", which consists of applying the following simplifications over and over:

1) Right fork to left fork:

```
| |-|      |-| |
|-| |  ->  | |-|
| |-|      |-| |

```

2) Eliminating doubles:

```
|-|        | |
|-|   ->   | |

```

I am not sure whether that explanation is unambiguous. Your code may use that technique or any other algorithm that produces the required primes.

**Shortest code wins.**

Standard rules and standard allowances apply. (If the input is not valid, your program may catch fire. Input/output formats may be stdin/stdout, string argument, list of lines, matrix of chars, whatever works best for you, etc.)

# Answer
> 5 votes
# Python 2, ~~322~~ 240 bytes

```
def f(X):
 X=[[c>' 'for c in s.split('|')]for s in X.split('\n')];h=L=len(X[0])-1;p=range(L)
 for x in X:p=[a-x[a]+x[a+1]for a in p]
 while h:h=i=0;exec"if p[i]>p[i+1]:print'|'+i*' |'+'-|'+(L-i-2)*' |';h=p[i],p[i+1]=p[i+1],p[i]\ni+=1\n"*~-L

```

Try it online!

A function which takes the string in the specified form, and prints out the reduced Amidakuji in that form as well.

The basic idea here is to first convert the input into a permutation (in the `for x in X` loop); and then in the `while` loop, perform a bubble sort of that permutation, since as the wikipedia article notes, this results in a 'prime' Amidakuji.

# Answer
> 4 votes
# Haskell, 288 bytes

```
p x(_:[])=x
p(x:y:z)(_:b:c)|b=='-'=y:p(x:z)c|0<1=x:p(y:z)c
c 0='-'
c _=' '
_#1="|"
m#n='|':c m:(m-1)#(n-1)
p?q=(p:fst q,snd q)
f%b|b==f b=b|0<1=f%f b
f l=reverse$snd$(g 0)%(foldl p[1..n]l,[])where n=1+div(length$l!!0)2;g b((x:y:z),a)|x>y=y?g(b+1)(x:z,a++[b#n])|0<1=x?g(b+1)(y:z,a);g _ x=x

```

Try it online!

### Explanation

```
-- the function p performs the permutation of a list
-- according to a single line from amidakuji board
p x (_:[]) = x
p (x:y:z) (_:b:c)
    | b == '-' = y : p (x : z) c
    | otherwise = x : p (y : z) c

-- helper to select either leg '-' or empty cell
c 0 = '-'
c _ = ' '

-- the # operator generates an amidakuji line containing one leg
-- which corresponds to one swap during bubble sort

-- terminal case, just one edge left
_ # 1 = "|"
-- each cell contains an edge '|' and either space or a '-' for the "active" cell
m # n = '|' : c m : (m - 1) # (n - 1)

-- helper to find the limit value of a function iteration
f % b
    | b == f b = b  -- return the value if it is unchanged by the function application
    | otherwise = f % f b -- otherwise repeat

-- helper to appropriately combine q which is the result of invocation of
-- the function g (see below), and a character p
p ? q = (p : fst q, snd q)

-- the function that does the work
f l = reverse $ snd $ (g 0) % (foldl p [1..n] l, []) where
    -- number of lines on the board
    n = 1 + div (length $ l !! 0) 2
    -- apply one iteration of bubble sort yielding (X, Y)
    -- where X is partially sorted list and Y is the output amidakuji
    g b ((x:y:z), a)
        -- if we need to swap two elements, do it and add a line to our board
        | x > y = y ? g (b + 1) (x:z, a ++ [b # n])
        -- if we don't need to, just proceed further
        | otherwise = x ? g (b + 1) (y:z, a)
    -- terminal case when there is only one element in the list
    g _ x = x

```

# Answer
> 2 votes
# Retina 0.8.2, 105 bytes

```
$
¶$%`
r`.?.\G
 1$.'$*
+r-1=`\|(-?.?[- 1]*¶.*)(1+)
$2$1
-

1G`
;{`\b(1+) \1
$1-$1
*`1+
|
(1+)-(1+)
$2 $1

```

Try it online! Explanation:

```
$
¶$%`

```

Duplicate the last line.

```
r`.?.\G
 1$.'$*

```

Number the columns in the last line.

```
+r-1=`\|(-?.?[- 1]*¶.*)(1+)
$2$1

```

Move the numbers up until they get to the first line. At each iteration, only the rightmost number `-1=` is moved. It is moved to the rightmost `|` unless it is preceded by a `-` in which case it is moved to the previous `|`. (The `r` indicates that the regex is processed as if it was a lookbehind, which makes it marginally easier to match this case.) This calculates the permutation that the Amidakuji transforms into sorted order.

```
-

1G`

```

Keep just the list of numbers, deleting the `-`s and anything after the first line.

```
;{`

```

The rest of the program then is then repeated sort the list back into order, but the final list is not printed, however as it takes an iteration for Retina 0.8.2 to notice that the list is in order, a line with no legs is generated at the end, which I believe is acceptable.

```
\b(1+) \1
$1-$1

```

Mark all available pairs of adjacent unsorted numbers with `-`s for the legs.

```
*`1+
|

```

Print the legs but with the numbers replaced with `|`s.

```
(1+)-(1+)
$2 $1

```

Actually perform the swaps.

# Answer
> 1 votes
# Python 3, ~~524~~ ~~488~~ 486 bytes

*-38 bytes thanks to ovs!*

```
from numpy import*
A=array;E=array_equal
K=[0]
def r(a,m,n):
	X=len(m);Y=len(m[0]);W,H=a.shape
	for x in range(W-X+1):
		for y in range(H-Y+1):
			if E(a[x:x+X,y:y+Y],A(m)):a[x:x+X,y:y+Y]=A(n)
	return a
def p(a):
	b=A([[j>" "for j in i]for i in[i.split("|")for i in a.split("\n")]])
	while E(a,b)<1:a=b;Z=K*3;O=[0,1,0];T=[K+O,O+K]*2;D=[O,O],[Z,Z];P=[Z,O],[O,Z];*R,_=T;_,*L=T;b=r(r(r(r(r(r(a[any(a,1)],R,L),*D),*P),L,R),*D),*P)
	for i in a:print("",*[" -"[j]for j in i[1:-1]],"",sep="|")

```

Try it online!

This converts the Amidakuji to a 2D binary array, and directly reduces it using the rules.

# Answer
> 0 votes
# Stax, 45 bytes

```
⌐φ²MC½↕uö∩┴║%≤Oo╧i╕ïô§ê{δ¿k>┴ê◘►╢lµ∙→Z↔8╨─(·£

```

Run and debug it

---
Tags: code-golf, game, permutations
---


# Question
Title: Accordion Solitaire: Which First Moves Can I Make?
## Introduction:

Unfortunately an Accordion Solitaire Solver challenge already exists (*Solve a game of Accordion*), so instead this easier related challenge.

Let's start by explaining how Accordion Solitaire works:

1. You start with all 52 cards (or 53 if you add a Joker) in one big row.
2. You pile up cards from right to left that are either adjacent, or have two cards in between them.
    1. This can either be when they are the same suit
    2. Or when they have the same value

For example, let's say we start with this: `HK S8 SK DK`, then you'd have these possible game scenarios:

1. `S8←SK`, resulting in `HK SK DK`; `SK←DK`, resulting in `HK DK`; `HK←DK`, resulting in `DK`.
2. `SK←DK`, resulting in `HK S8 DK`.
3. `HK←DK`, resulting in `DK S8 SK`; `S8←SK`, resulting in `DK SK`; `DK←SK`, resulting in `SK`.

You win when every card is in a single pile in the end, so the game scenarios 1 and 3 would be a won Accordion Solitaire, but in scenario 2 you would have lost.

*NOTE: Symbols used are as follows: `H=Hearts; S=Spades; D=Diamonds; C=Clubs. T=10; J=Jack; Q=Queen; K=King; A=Ace. J=Joker`.*

PS: Irrelevant for this challenge, but added for informational purposes for those interested: if you play Accordion Solitaire with Jokers, you can only use each Joker once. The Joker will be put at the bottom of the pile when paired up. I.e. `H4 C4 S4 J` could have for example the following game scenario: `S4←J`, resulting in `H4 C4 S4` (so NOT `H4 C4 J`); `C4←S4` resulting in `H4 S4`; `H4←S4` resulting in `S4`.

## Challenge:

Given a row of cards, output all first steps we can make. So with the example `HK S8 SK DK` above, the result would be `["S8←SK","SK←DK","HK←DK"]`.

## Challenge rules:

* Not all inputs can have a move. So a test case like `H3 C7 S5 CQ` will result in an empty output, because no moves can be made.
* Jokers will be added, which can be used as any wild card, so it can always pair up with up to four other cards (depending on its position).
* Input and output formats are flexible, but you'll have to use the formats specific (with optionally `10` instead of `T`). Input can be a single space-delimited string; list of strings, characters; map with suit + value; etc. Output can be a single delimited string, pairs output to STDOUT, list of pairs, etc. (the character to indicate moves - for which I've used  in the example above - can also be anything you'd like, and the order of the pairs could also be reversed (i.e. `["SK→S8","DK→SK","DK→HK"]`)). Please state what you've used in your answer!
* Order of the list in the output doesn't matter (i.e. `["SK←DK","S8←SK","HK←DK"]` is valid as well).
* There won't be any test cases with duplicated cards (including Jokers). So we can assume the test cases use a single Deck of 53 cards (52 + 1 Joker). (So you could use a set instead of list for the output if it would save bytes, since all pairs will be unique.)
* You are allowed to use `10` instead of `T` if that's what you prefer. You are not allowed to use `JJ` (or anything else of 2 characters) for the Jokers; Jokers will always be a single `J`.

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input                       Output

"HK S8 SK DK"               ["S8←SK","SK←DK","HK←DK"]
"HA H3 ST"                  ["HA←H3"]
"H3 C7 S5 CQ"               []
"HK S8 J C8 CK"             ["S8←J","J←C8","C8←CA"]
"H5 CA SQ C9 H9 C2 CQ HJ CT SK D3 H8 HA HQ S4 DA H7 SA DK"
                            ["C9←H9","C9←CQ","H9←HJ","C2←CQ","C2←CT","H8←HA","HA←HQ","HA←DA","HQ←H7","S4←SA","DA←DK"]
"CA C2 C3 J H2 H3 D4 H4"    ["CA←C2","CA←J","C2←C3","C2←H2","C3←J","C3←H3","J←H2","J←D4","H2←H3","H2←H4","D4←H4"]
"H4 C4 S4 J"                ["H4←C4","H4←J","C4←S4","S4←J"]
"H3 S3"                     ["H3←S3"]

```

# Answer
# Retina, 60 bytes

```
L$w`((\bJ)|(\w)(\w)) (\w+ \w+ )?((?(2)..|(J|\3.|.\4)))
$1<$6

```

Try it online! Link includes test cases. Explanation:

```
L$
$1<$6

```

Output the appropriate captures from each match.

```
w`

```

Find all overlapping matches (not just simple overlaps).

```
\b((\bJ)|(\w)(\w)) (\w+ \w+ )?((?(2)..|(J|\3.|.\4)))

```

Match either the Joker or a two-letter card, then two optional cards, then if the Joker was matched then any other card otherwise either the Joker or a card that matches either in suit or value. (I don't have to check for letters here as there can only be one Joker and the suit and rank can only match another card.)
> 2 votes

# Answer
# Python 3, ~~124~~ 119 bytes

```
lambda c:[[v,c[j]]for i,v in enumerate(c)for j in[i+1,i+3]if j<len(c)and any(d[0]==d[1]or"J"in d for d in zip(v,c[j]))]

```

Try it online!

Credits

* From 124 to 119 bytes by ovs.
> 1 votes

---
Tags: code-golf, string, game, card-games
---


title: ASCII Calendar Planner

text:
# Question
Title: ASCII Calendar Planner
Given a list of activities and their start time/date, output an ASCII-art calendar showing the activities on the appropriate days. All activities are guaranteed to be in the same month, no two activities will be on the same day, and all activities are guaranteed to fit within the calendar box.

The calendar has the date in the upper-left corner of each box, the boxes are 9 spaces wide by 5 spaces tall, surrounded by `-` and `|`. The two-letter abbreviation for the day of the week is centered above the first row, and the weeks start with Sunday.

For example, given the following activities:

```
10/5/2018 - 9:00am - Sandbox calendar challenge
10/9/2018 - 9:00am - Post challenge to main
10/10/2018 - 10:00am - Profit
10/31/2018 - 7:30pm - Halloween party

```

Output this corresponding calendar:

```
    Su        Mo        Tu        We        Th        Fr        Sa
-----------------------------------------------------------------------
|         |1        |2        |3        |4        |5        |6        |
|         |         |         |         |         |9:00am   |         |
|         |         |         |         |         |Sandbox  |         |
|         |         |         |         |         |calendar |         |
|         |         |         |         |         |challenge|         |
-----------------------------------------------------------------------
|7        |8        |9        |10       |11       |12       |13       |
|         |         |9:00am   |10:00am  |         |         |         |
|         |         |Post     |Profit   |         |         |         |
|         |         |challenge|         |         |         |         |
|         |         |to main  |         |         |         |         |
-----------------------------------------------------------------------
|14       |15       |16       |17       |18       |19       |20       |
|         |         |         |         |         |         |         |
|         |         |         |         |         |         |         |
|         |         |         |         |         |         |         |
|         |         |         |         |         |         |         |
-----------------------------------------------------------------------
|21       |22       |23       |24       |25       |26       |27       |
|         |         |         |         |         |         |         |
|         |         |         |         |         |         |         |
|         |         |         |         |         |         |         |
|         |         |         |         |         |         |         |
-----------------------------------------------------------------------
|28       |29       |30       |31       |         |         |         |
|         |         |         |7:30pm   |         |         |         |
|         |         |         |Halloween|         |         |         |
|         |         |         |party    |         |         |         |
|         |         |         |         |         |         |         |
-----------------------------------------------------------------------

```

## Clarifications

* The schedule words (matching \[A-Za-z\]+) will delimited by a single space between them (as in the example).
* Splitting the text on word boundaries is sufficient. No need for hyphenating words.
* If February starts on a Sunday in a non-leap-year, you only will have four calendar rows.
* If a 31-day month (e.g., August) starts late in the week, you may have to output six calendar rows.

## I/O and Rules

* Your code must handle dates at least between `0001-01-01` and `9999-12-31` in the Gregorian calendar, including leap years as appropriate. For example, if given input `2016-02-13 9:00am Test`, the output calendar should have February 29.
* Input date format can be in any desired format. ISO 8601, a `datetime` object, a particularly-formatted string, etc. Input parsing is not the interesting part of this challenge.
* Input and output can be by any convenient method.
* Leading/trailing newlines or other whitespace are optional, provided that the characters line up appropriately.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, returned as a list of strings, returned as a single string, etc.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# JavaScript (ES8), ~~380~~~~321~~ 320 bytes

Takes input as `(y,m,e)` where:

* `y` is the year
* `m` is the month, 0-indexed
* `e` is an object whose keys are the days and whose values are the events in `[hour, task]` format

```
(y,m,e)=>`SuMoTuWeThFrSa
`.split(/(..)/).join`    `+(p='-'.repeat(d=71)+`
`)+(g=i=>++d<1|(x=G`getMonth`==m)|i%7?`|${[h,t]=e[d]||E,o=[x*d,h],q=E,t&&t.split` `.map(s=>q=(u=q?q+' '+s:s)[9]?o.push(q)&&s:u),[...o,q][r%5]||E}`.padEnd(10)+(++i%7?E:`|
`+(++r%5?(d-=7,E):p))+g(i):E)(E=r='',d=-(G=s=>new Date(y,m,d)[s]())`getDay`)

```

Try it online!

## How?

Below are some important parts in the code.

### Header

The header line is generated with:

```
'SuMoTuWeThFrSa\n'.split(/(..)/).join`    `

```

When `split()` is used with a regular expression containing a capturing group, this group is included in the output array. In this case, it gives:

```
[ '', 'Su', '', 'Mo', '', 'Tu', '', 'We', '', 'Th', '', 'Fr', '', 'Sa', '\n' ]

```

We join this array with 4 spaces, leading to:

```
'    Su        Mo        Tu        We        Th        Fr        Sa    \n'

```

which is exactly what we want.

### Month structure

The helper function \\$G\\$ builds a date from the input year \\$y\\$ and input month \\$m\\$ (which are constant) and the day \\$d\\$ (which is dynamic). Its parameter is a method name, which allows to extract either the day of the week or the month.

```
G = s => new Date(y, m, d)[s]()

```

It is first used to identify the day of the week of the first day of the month, so that we can move back to the last Sunday from there. It is then used to detect when we enter back the correct month and when we leave it (this information is stored in the Boolean \\$x\\$).

### Event formatting

The following code is used to format an event.

```
[h, t] = e[d] || E,           // split the content of the event into h and t
o = [x * d, h],               // set the first 2 entries of o[]: day and hour
q = E,                        // we start with q = empty string
t &&                          // skip this .map() loop entirely if t is not defined
t.split` `                    // split the string on spaces
.map(s =>                     // for each word s:
  q =                         //   update q:
    (u = q ? q + ' ' + s : s) //     u is the concatenation of the previous string with
                              //     the new word, separated by a space if needed
    [9] ?                     //     if u is more than 9 character long:
      o.push(q)               //       push the previous string in o[]
      && s                    //       and reset q to s
    :                         //     else:
      u                       //       update q to u
),                            // end of map()
[...o, q][r % 5]              // append the last pending part to o[] and extract the
|| E                          // relevant row; or use an empty string by default

```
> 10 votes

# Answer
# Python 2, ~~326~~ ~~324~~ ~~315~~ ~~312~~ 307 bytes

```
import calendar as c,textwrap as t
c.setfirstweekday(6)
y,m,e=input()
print' Su Mo Tu We Th Fr Sa\n'.replace(' ',' '*8)[4:]+'-'*71
for w in c.monthcalendar(y,m):
 for l in zip(*[[d or'',a]+(t.wrap(b,9)+['']*3)[:3]for d in w for a,b in[e.get(d,'  ')]]):print'|'+'|'.join('%-9s'%v for v in l)+'|'
 print'-'*71

```

Try it online!

Same input as Arnauld's JS answer:

Takes input as `(y,m,e)` where:

* `y` is the year
* `m` is the month, 1-indexed
* `e` is an object whose keys are the days and whose values are the events in `(hour, task)` format
> 3 votes

# Answer
# Charcoal, ~~215~~ 206 bytes

```
Ｓθ≔Ｉ⪪§⪪θ ⁰/η≔⁻⁺×¹²⊟η⊟η²η≔ＥＥ²⁻ηι﹪Σ⟦÷ι⁴⁸⁰⁰±÷ι¹²⁰⁰÷ι⁴⁸÷ι¹²÷×¹³⁺⁴﹪ι¹²¦⁵⟧⁷η≔±⊟ηζ≔⁺²⁸﹪⁺⊟ηζ⁷ε⭆⪪SuMoTuWeThFrSa²◨◧ι⁶χ↓←⁷¹Ｗ‹ζε«↘Ｆ⁷«Ｐ↓⁵→≦⊕ζＦ⁼Ｉζ§⪪θ/⁰«≔⪪θ - θ≔⟦ω◨§θ¹¦⁹⟧δＦ⪪⊟θ ⊞δ⎇‹⁺Ｌ§δ±¹Ｌμ⁹⁺⁺⊟δ μμＰ⪫δ¶Ｓθ»◨×››ζ⁰›ζεＩζ⁹»↓⁵←⁷¹

```

Try it online! Link is to verbose version of code. Takes dates in d/m/yyyy format. Explanation:

```
Ｓθ

```

Input the first event.

```
≔Ｉ⪪§⪪θ ⁰/η

```

Extract the date and split on `/`s.

```
≔⁻⁺×¹²⊟η⊟η²η

```

Convert to months since March, 1 BC. I want to calculate the day of week of the first of both next month and the current month, and working in months is easier than keeping the months and years separate and carrying at the end of the year, plus it also allows me to start counting months beginning at March instead of January, which is required by Zeller's congruence.

```
≔ＥＥ²⁻ηι﹪Σ⟦÷ι⁴⁸⁰⁰±÷ι¹²⁰⁰÷ι⁴⁸÷ι¹²÷×¹³⁺⁴﹪ι¹²¦⁵⟧⁷η

```

Use a modified Zeller's congruence to extract the day of the week of the first day of next month and this month. The basic part relies on the fact that the number of days from October 30th of the previous year to the 1st of a given month where `m = 4` for March and `m = 14` for January of the following year is given by the formula `m * 153 / 5`, however we can subtract 140 because we only care about the day of the week. It then remains to make adjustments due to the year; each year adds a day, each 4th year adds an extra day, each 100th year subtracts a day, and each 400th year adds a day again. (As I'm working in months these values are all multiplied by 12.) Rather conveniently this directly gives me the answer in terms of a Sunday-indexed week (normally you would add the day of month and start counting on Saturday).

```
≔±⊟ηζ

```

Negate the day of the week and save it as the current day of the month.

```
≔⁺²⁸﹪⁺⊟ηζ⁷ε

```

Calculate the number of days in the month from the day of the week of the two months.

```
⭆⪪SuMoTuWeThFrSa²◨◧ι⁶χ

```

Output the day headers.

```
↓←⁷¹

```

Print the top row of `-`s.

```
Ｗ‹ζε«

```

Loop until the last day of the month has been output.

Move the cursor to the start of the next row.

```
Ｆ⁷«

```

Process 7 days at a time.

```
Ｐ↓⁵→

```

Print the column of `|`s to the left.

```
≦⊕ζ

```

Increment the current day of the month.

```
Ｆ⁼Ｉζ§⪪θ/⁰«

```

If the current day of the month is the day of the current event, ...

```
≔⪪θ - θ

```

... extract the other parts of the event, ...

```
≔⟦ω◨§θ¹¦⁹⟧δ

```

... pad the time to 9 spaces and save it and an empty string as a list, ...

```
Ｆ⪪⊟θ

```

... split the description on spaces and loop over them, ...

```
⊞δ⎇‹⁺Ｌ§δ±¹Ｌμ⁹⁺⁺⊟δ μμ

```

... adding each word to the previous word if it will fit; ...

```
Ｐ⪫δ¶

```

... output the time and description (`Ｐδ` doesn't work, might be a Charcoal bug?), ...

```
Ｓθ»

```

... and input the next event.

```
◨×››ζ⁰›ζεＩζ⁹»

```

If the current day of the month is between 1 and the last day of the month then output it, otherwise just output enough spaces to move to the next day.

```
↓⁵←⁷¹

```

At the end of the week, print the right column of `|`s and the bottom row of `-`s.
> 3 votes

# Answer
# Java (JDK), 538 439 428 425 bytes

Quite possibly the longest Code Golf solution I've ever posted. Still trying to golf it down from here but it's a struggle.

Managed to knock off 99 bytes by changing the input format and using some regex parsing, and another 11 from miscellaneous bits.

*3 extra bytes off thanks to Kevin!*

Taking inspiration from other answers, it takes input as the year, month and a Map of days to a String representing the time and event in the format `<time>-<event>`.

```
(y,m,M)->{var C=java.util.Calendar.getInstance();C.set(y,m-1,1);String r=",Su,,Mo,,Tu,,We,,Th,,Fr,,Sa\n".replace(",","    "),e;for(int x=C.getActualMaximum(5),l=0,b=0,j,c,i=0;i<7;r+="\n",l+=b<=x&++i>6?7*(i=1):0)for(j=0;j<71;b=l+j/10+2-C.get(7),e=(e=M.get(b))!=null?e.replaceAll("([^-]{1,9})(-| |$)","$1-")+" - ":null,r+=e=i%6<1?"-":c<1?"|":c*i<2&b>0&b<=x?b+"":c<2&e!=null?e.split("-")[i-2]:" ",j+=e.length())c=j%10;return r;}

```

Try it online!

---

**Ungolfed**

```
(y,m,M)->{                                              // Lambda taking input as a year, month and map
  var C=java.util.Calendar.getInstance();               // Creates a new Calendar instance
  C.set(y,m-1,1);                                       // Sets the calendar to the first of the month in the given year
  String r=",Su,,Mo,,Tu,,We,,Th,,Fr,,Sa\n"              // Creates the header row by replacing
    .replace(",","    "),e;                             // commas with 4 sets of spaces

  for(                                                  // Creates 7 rows for a calendar row
      int x=C.getActualMaximum(5)                       // Stores last day of the month
      ,l=0,b=0,j,c,i=0;i<7;                             // Initialises other integers
      r+="\n",                                          // Add new line each row
      l+=b<=x&++i>6                                     // If end of a calendar row is reached, and current day is less than max
        ?7*(i=1)                                        // Set i to 1 and add 7 to line count to create another calendar row
        :0)                                             // Otherwise do nothing

    for(j=0;j<71;                                       // Loop 71 times, appending characters to create a row
        b=l+j/10+2-C.get(7),                            // Determine the day of the box we're in
        e=(e=M.get(b))!=null?                           // Get the event for this day from the map and if not null
            e.replaceAll("([^-]{1,9})(-| |$)","$1-")      // Do some regex to separate the line entries by hyphens
            +" - "                                      // Append extra hyphen to prevent array out of bounds
            :null,                                      // Otherwise do nothing
        r+=e=i%6<1?"-":                                 // If it's the first line of a calendar row, append -
           c<1?"|":                                     // If it's the first column of a box, append |
           c*i<2&b>0&b<=x?b+"":                         // If it's the second column of a box, the second row,
                                                        // and less than the max day, append the day
           c<2&e!=null?e.split("-")[i-2]:               // If it's any other row and there is an event then split and append correct line
           " ",                                         // Else just append a space
        j+=e.length())                                  // Increase the row character count by the length to append
          c=j%10;                                       // Set the column of box (this is the only thing in the loop so happens first)

  return r;                                             // return the calendar string!
}

```
> 2 votes

# Answer
# Red, 674 651 bytes

```
func[a][z: func[a b c][to-tuple reduce[a b c]]c: a/1 c/4: 1 d: c + 31
d/4: 1 d: d - 1 e: 1 + c/weekday % 7 if e = 0[e: 7]foreach
t[:Su:Mo:Tu:We:Th:Fr:Sa][prin pad pad/left t 6 10]h:
pad/with"-"71 #"-"print["^/"h]m: copy[]foreach[i b]a[put m z r:(t: e - 1)+
i/4 / 7 + 1 n: i/4 % 7 + t 2 b/1 t: split b/2" "l: 0
until[if t/2[if 10 >((length? t/1)+ length? t/2)[t/1:
rejoin reduce[t/1" "take next t]]]put m z r n 2 + l: l + 1 take t
tail? t]i: 0]n: k: 0 repeat v(g: e - 1 + d/4)/ 7 + sign? g % 7[repeat
r 5[repeat i 7[t: copy"|"if i = e[k: 1]if all[k = 1 r = 1 n < d/4][append t
n: n + 1]if s: select m z v i r[append t s]prin pad t 10]print"|"]print h]]

```

Try it online!

## More readable:

```
func [ a ] [
    c: d: a/1
    c/4: d/4: 1
    d: d + 31
    d/4: 1
    d: d - 1
    e: 1 + c/weekday % 7
    if e = 0[e: 7]
    g: e - 1 + d/4
    w: g / 7 + sign? g % 7
    foreach t [ :Su :Mo :Tu :We :Th :Fr :Sa ] [
        prin pad pad/left t 6 10
    ]
    h: pad/with "-" 71 #"-"
    print[ "^/" h ]
    m: copy #()
    foreach[ i b ] a [
        n: i/4 % 7 + t: e - 1
        r: t + i/4 / 7 + 1
        put m to-tuple reduce[ r n 2 ] b/1
        t: split b/2" "
        i: 0
        until [
            if t/2 [ if 9 >= ((length? t/1) + (length? t/2)) [
                t/1: rejoin reduce[t/1" "take next t]
                ]
            ]
            put m to-tuple reduce [ r n 2 + i: i + 1 ] take t
            tail? t
        ]

    ]
    n: 0
    g: off
    repeat v w [
        repeat r 5 [
           repeat i 7 [
                t: copy "|"
                if i = e[ g: on ]
                if all [ g r = 1 n < d/4 ] [ append t n: n + 1 ]
                if s: select m to-tuple reduce [ v i r ]
                    [ append t s ]
                prin pad t 10
            ]
            print "|"
        ]
        print h
    ]
]

```
> 1 votes

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


# Question
Title: Modified Boggle-able Code and Output: CnR Edition (Cops)
> This is the Cops' thread. Robbers' thread is here.

## Background

Boggle is a board game where the players have to find English words on a 4-by-4 board of random alphabets. Words can be constructed by selecting sequentially adjacent cells on the board. ("adjacent" means horizontally, vertically or diagonally adjacent.) Also, same cell can't be used more than once in a word.

The following is an example board:

```
I L A W
B N G E
I U A O
A S R L

```

On this board, `BINGO`, `ORANGE` and `WEARS` are valid words, but `SURGE` and `RUSSIA` are not:

* `SURGE` : There's no adjacent pair on the board having `RG`.
* `RUSSIA` : `S` cannot be used twice.

**Modified Boggle** is a modified version of Boggle, with the following rules:

* The board size is `m`-by-`n`, where `m` and `n` can be any positive integer.
* Each cell can contain any one byte between 0 and 255 inclusive.
* **A cell can be used more than once, but not twice in a row.**

Using the example board above, in addition to `BINGO`, `ORANGE` and `WEARS`, `LANGUAGE` becomes a valid string (since `G` is used twice, but not twice in a row) but `RUSSIA` is still not (due to `SS` pair).

Here is another example using a code fragment. The string `from itertools import*\n` can be found on the following board, but not `from itertoosl import*` or `from itertools import *`:

```
f   i   ' ' s
r   t   m   l
e   o   o   p
\n  *   t   r

```

Note that you need two `o`'s in order to match the `oo` sequence.

---

## Cop's challenge

Write a **full program** in your language of choice that satisfies the following rules:

* The program should print something which is consistent over multiple runs.
* The program should finish in roughly 5 seconds.
* The program may not take any input.
* Both the program and the output should be at least 2 bytes.
* **Anything related to hash functions, PRNGs, or cryptography is not allowed.**

Then, **lay out your program *and* output into two separate modified-boggle boards**. Each board can be a non-square. Note that 1-by-N and 2-by-N boards can pose special challenges to both the cop and the robber. If you want some cells on a board unusable (to add more restriction), you can pick some useless bytes and fill the holes with them.

For example, if you want a 2x2 grid with horizontal/vertical movements only, you can do this instead:

```
a b
c d
-----------
X a X
c X b
X d X

```

In your submission, specify the language you used, the lengths of the source code and the output, and the two boggle boards. Note that **shorter code and/or longer output is allowed for robbers**, so you can choose to give some room for the byte counts (i.e. specify longer code and/or shorter output than your actual solution).

If your board contains some unprintable characters, you can specify the board as byte values instead.

After a week a cop is posted, it can be marked safe by the poster if it isn't cracked until then. The cop is still open for robbers until it's actually marked safe. A safe cop can't be cracked, and the poster should reveal the intended solution.

You'll want to obfuscate the boards as much as possible, as the robber's challenge is to crack your submission by finding the code and its output on the boards. If you want to cram a long code into a small board, answers to the original Modified Boggle challenge may give some insights.

## Scoring for cops

Since it's hard to say whether a larger or smaller board is harder to crack, each safe cop submission counts as a score of 1. The user with the greatest score wins. It's encouraged to participate with different languages and creative approaches.

## Cop example & formatting

```
# Japt, code 9 bytes, output 20 bytes

Code board: 2 rows, 2 columns

    `l
    íÏ

As byte values:

    96  108
    237 207

Output board: 3 rows, 3 columns

    175
    120
    643

```

---

## Modified Boggle verification script

All of the scripts below have an example input with it.

Script for character string(code/output) & boggle. This does not support multi-line string. The input format is

* a single line of string (either code or output), followed by
* the raw boggle board.

Script for character string with byte-value boggle. Use this if the target string is printable but has one or more newlines in it. The input format is

* the number of lines for the string,
* raw string (possibly multi-line), then
* the boggle board as byte values.

Script for byte-value string & boggle. Use this if the target string contains one or more unprintable characters. The input format is

* a single line of string (either code or output) as byte values, followed by
* the boggle board as byte values.

# Answer
# JavaScript (Node.js), code 53 bytes, output 41 bytes, cracked by Arnauld

### Code Board: 3 rows by 6 columns:

```
cog(n)
lsn1()
e.+<<;

```

### Output Board: 4 rows by 6 columns:

```
481534
270906
602148
53829n

```

**Hint: the code only works on V8 JS engines, version 6.7 or later**

Mine was `console.log(1n+1n+1n<<(1n+1n+1n+1n<<1n+1n+1n+1n+1n));` with the semicolon (don't ask why) and the output is yes, `3 * 2**128` with an trailing `n` marking the number as a BigInt literal.
> 3 votes

# Answer
# JavaScript, 1443 bytes code, 3 bytes output, cracked in moments by @ShieruAsakoto

### Code board, 3 rows by 4 columns

```
!![+
+[]]
+]()

```

### Output board, 1 row by 2 columns

```
aN

```

Kinda obvious what the output is. ~~It'll be the code that's fun to crack.~~ Forgot to mention that it was intended to be a full program (and kinda implied that it wasn't; see paragraph below). For the real challenge, see my other answer.

I don't think this is Node.js, but my knowledge in this area is zero. What I can say is that it runs in my console in both Edge and Chrome.
> 3 votes

# Answer
# JavaScript (Node.js), code 88 bytes, output 2 bytes, cracked by Arnauld with a 27-byte

### Code Board: 7 rows by 9 columns:

```
e.i--)=%5
lc;,2s*17
fosn8407%
gnr785138
s(;527067
=);s%1419
4n,i=1832

```

### Output Board: 1 rows by 2 columns:

```
0n

```

The output is obvious, but the code is not. ;)

My original answer was an LL-test of M127, which was

```
for(s=4n,i=125;i;s%=170141183460469231731687303715884105727n,i--)s=s*s-2n;console.log(s)

```

Arnauld's answer utilized the semicolons to bridge a shorter crack, and I didn't expect (or realize) the `s%=s` part at all:

```
s=4n;s%=s;7n;console.log(s)

```

Oh by the way my 3 posts have absolutely nothing to do with hash functions, PRNGs or cryptography. I swear these three are only about number manipulations.

**there are unused bytes in code board**
> 2 votes

# Answer
# Python 3, code 56 bytes, output 69 bytes, SAFE

### Code Board: 4 rows by 10 columns:

```
  print(1,
b; f,)*l(1
 =lamb+a,)
ese d:(-1)

```

### Output Board: 7 rows by 7 columns:

```
1466900
3427430
1304212
9653895
0511633
5680228
4437679

```

Much difficult one than my first challenge ;)

# Expected Code and Output:

> Code:
>
> ```
> l=lambda a,b:(a+b)*l(a-1,a*b)if a else b;print(l(11,11))
>
> ```
>
> Output:
>
> ```
> 421827435070654423113161304555505960246647934329322186026783332352000
>
> ```
> 1 votes

# Answer
# JavaScript, 1443 bytes code, 3 bytes output, cracked by @Bubbler

A full program.

### Code board, 3 rows by 4 columns

```
!![+
+[]]
+]()

```

### Output board, 1 row by 2 columns

```
aN

```

Kinda obvious what the output is. It'll be the code that's fun to crack.

I don't think this is Node.js, but my knowledge in this area is zero. What I can say is that it runs in both Edge and Chrome. By "full program" I mean that it runs when placed between `<script>` and `</script>` in an HTML file.
> 1 votes

# Answer
# MathGolf, code 42 bytes, output 22 bytes

### Code Board: 3 rows by 7 columns

```
 r5 qÄ
~←▲↔▼→~
 Äq 5r

```

### Output Board: 3 rows by 6 columns:

```
421
402
135

```

This is quite a bit longer, but I'll give a small hint: The code board is supposed to resemble a bowtie, and you might need to "tie" it multiple times.
> 1 votes

# Answer
# MathGolf, code 7 bytes, output 12 bytes

Just a first easy challenge, if you want to get into MathGolf!

### Code Board: 2 rows by 4 columns

```
╒Æ■r
îm4~

```

### Output Board: 2 rows by 3 columns

```
140
412

```
> 0 votes

# Answer
# Jelly, 17 byte code, 19 byte output

The general method shouldn't be too hard to pick out.

## Code board

```
»V
”;
“;

```

## Output board

```
Krgwn
Ubots
RAbbt

```
> 0 votes

# Answer
# (REPL), code 9 bytes, output 10000 bytes

Code board: 3 rows, 3 columns

```
epi
j.r
oI5

```

Output board: 3 rows, 2 columns, as byte values

```
10  10
48  49
32  255

```

In essence, `\n\n` / `01` / `<space><don't use>`.

Intended solution gives 20008-byte output.
> 0 votes

---
Tags: cops-and-robbers, boggle
---