# Question
Title: Draw a sudoku board using line drawing characters
This is code golf. For this challenge, I will accept a method (you don't need a full program), but the method signature does count towards the byte count and I want to see the full signature (not a lamdba). The input for the method is an integer array with 81 elements. The output/return value from the method is a string that represents the array as an ascii sudoku board.

If you're using an esoteric language or something that absolutely doesn't have methods, you can adapt, but if the language supports this at all I want to see something might actually be plugged into a "real" ungolfed program, even if the method body itself is a pain to work with. The requirement is not meant to block languages like Jelly or 05AB1E, but to make it easier for languages like Java to build something that makes sense for that platform.

For the input, integer values 1-9 should have obvious meanings. A 0 should always be interpreted as a blank cell. You may also interpret anything else outside the 1-9 range as a blank cell, but this is not required. Positioning from the array to the puzzle starts at the top left and fills each row from left to right before moving to the next row.

For the boxes, I want double lines around the outside and between each 3x3 region, and single lines between other cells. These should be drawn with line drawing characters (if your I/O format represents strings as a sequence of bytes rather than a sequence of characters, you should represent them in a well-known encoding such as UTF-8 or codepage 347).

For this challenge, I am **NOT** asking you to generate the sudoku puzzle. That is the input for the function. I am **NOT** asking you to solve the puzzle. I'm just asking you to produce a string to "draw" what you're given (in as few bytes as possible).

### Example Input:

Values for the array:

```
{ 8, 5, 0, 0, 0, 2, 4, 0, 0, 7, 2, 0, 0, 0, 0, 0, 0, 9, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 7, 0, 0, 2, 3, 0, 5, 0, 0, 0, 9, 0, 0 ,0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 7, 0, 0, 1, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 6, 0, 4, 0}

```

The values can use whatever mechanism is natural for your language: int\[\], ArrayList, sequence, tuple, string of digits, whatever, as long as you have a value in the input for every cell (no maps for only populated cells to positions). Remember that the input is supplied... it is not part of your byte count. But the input might represent *any* sudoku puzzle, and the puzzle *might not even have a valid solution*. You do get to assume that puzzle *is* printable. You won't get something with 82 elements, for example.

You also get to assume a reasonable fixed-width font.

### Corresponding Output:

```
╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗
║ 8 │ 5 │   ║   │   │ 2 ║ 4 │   │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ 7 │ 2 │   ║   │   │   ║   │   │ 9 ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │   │ 4 ║   │   │   ║   │   │   ║
╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣
║   │   │   ║ 1 │   │ 7 ║   │   │ 2 ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ 3 │   │ 5 ║   │   │   ║ 9 │   │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │ 4 │   ║   │   │   ║   │   │   ║
╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣
║   │   │   ║   │ 8 │   ║   │ 7 │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │ 1 │ 7 ║   │   │   ║   │   │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │   │   ║   │ 3 │ 6 ║   │ 4 │   ║
╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝

```

# Answer
> 10 votes
# Python 3, 232 bytes

Thanks to those who helped to golf this down.

Encryption within encryption...

```
q=lambda x,y:x+y+x+y+x
r=lambda a,b,c,d,e:a+q(q(b*3,c),d)+e+"\n"
print(((r(*"╔═╤╦╗")+q(q("║ %d │ %d │ %d "*3+"║\n",r(*"╟─┼╫╢")),r(*"╠═╪╬╣"))+r(*"╚═╧╩╝"))%eval(input())).replace(*"0 "))

```

Try it online!

To be golfed.

# Answer
> 8 votes
# C (gcc), ~~398~~ ~~395~~ 291 bytes

Saved 3 bytes by working through the string reversed, and 104 (!) bytes thanks to Leaky Nun.

```
#include<locale.h>
#define q(x,y) x y x y x
#define D L"╝"q(q("═══","╧"),"╩")"╚"q(q("\n║"q(q(" & ","│"),"║")"║","\n╢"q(q("───","┼"),"╫")"╟"),"\n╣"q(q("═══","╪"),"╬")"╠")"\n╗"q(q("═══","╤"),"╦")"╔"
i;f(int*t){setlocale(LC_ALL,"");for(i=721;i--;)wprintf(L"%lc",D[i]%19?D[i]:*t++?48+t[-1]:32);}

```

Try it online!

## C (gcc), 395 bytes

I'll keep this here so its more evident as to how the program works.

```
#include<locale.h>
#define A L"\n╢───┼───┼───╫───┼───┼───╫───┼───┼───╟"
#define B L"\n║ & │ & │ & ║ & │ & │ & ║ & │ & │ & ║"
#define C L"\n╣═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╠"
#define E B A B A B
#define D L"╝═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╚"E C E C E L"\n╗═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╔"
i;f(int*t){setlocale(LC_ALL,"");for(i=721;i--;)wprintf(L"%lc",D[i]%19?D[i]:*t++?48+t[-1]:32);}

```

Try it online!

Working with unicode in C is... costly. Takes input as an `int*` as shown in the link and in the specification.

I'm going to see if I can save bytes using some number magic instead of hardcoding the string.

# Answer
> 7 votes
# PHP, 297 bytes

```
<?for(;$l<19;$l++)echo$l&1?strtr(vsprintf(str_pad("",67,"║ %d │ %d │ %d "),array_slice($_GET,9*($l/2^0)-9,9)),0," "):str_pad([╔,╟,╠,╚][$b=$l?$l<18?$l%6<1?2:1:3:0],108,strtr("11101110111".[╦,╫,╬,╩][$b],[[╤,═],[┼,─],[╪,═],[╧,═]][$b])).[╗,╢,╣,╝][$b],"
";

```

Try it online!

Expanded

```
for(;$l<19;$l++)  # loop thrpugh lines
  echo$l&1 # Output
    ?strtr(
        vsprintf(str_pad("",67,"║ %d │ %d │ %d ") # formated string for lines with numbers
        ,array_slice($_GET,9*($l/2^0)-9,9)) # nine items of the input array
      ,0," ") #replace zeros with space
    :str_pad([╔,╟,╠,╚][$b=$l?$l<18?$l%6<1?2:1:3:0] # start character non number lines and switch number four cases
      ,108 # fill too 108 bytes
      ,strtr("11101110111".[╦,╫,╬,╩][$b] # with string
        ,[[╤,═],[┼,─],[╪,═],[╧,═]][$b]))  #replace ones and zero with the two character in array chosed
    .[╗,╢,╣,╝][$b] # end row with chosen character
  ,"
    "; # end line with new line

```

used functions for both versions

vsprintf , strtr , str\_pad , array\_slice , array\_chunk

# PHP, 313 bytes

```
<?$r=($s=str_pad)(╔,108,($t=strtr)(($p=11101110111).╦,[╤,═])).╗;foreach(array_chunk($_GET,9)as$v)$r.=$t(vsprintf($s("
",68,"║ %d │ %d │ %d "),$v),0," ").(++$k%9?$k%3?$s("
╟",109,$t($p.╫,[┼,─])).╢:$s("
╠",109,$t($p.╬,[╪,═])).╣:"");echo$r.$s("
╚",109,$t($p.╩,[╧,═])).╝;

```

Try it online!

# Answer
> 5 votes
# T-SQL, ~~445~~ 437 bytes (in 381 characters)

```
DECLARE @r INT=0,@ NVARCHAR(999)=N'╔=╤=╤=╦=╤=╤=╦=╤=╤=╗P'p:SELECT @+=FORMAT(CAST(SUBSTRING(a,@r*9+1,9)AS INT),N'║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║P')FROM t
SET @r+=1IF @r=9SET @+=N'╚=╧=╧=╩=╧=╧=╩=╧=╧=╝P'ELSE IF @r%3=0SET @+=N'╠=╪=╪=╬=╪=╪=╬=╪=╪=╣P'ELSE SET @+=N'╟-┼-┼-╫-┼-┼-╫-┼-┼-╢P'IF @r<9GOTO p
PRINT REPLACE(REPLACE(REPLACE(REPLACE(@,'=',N'═══'),'-',N'───'),'0',' '),'P',CHAR(13))

```

Input is via a string of digits stored in column *a* of pre-existing table *t*, per approved methods.

**Format and Explanation**:

```
DECLARE @r INT=0, @ NVARCHAR(999)= N'╔=╤=╤=╦=╤=╤=╦=╤=╤=╗P'
p:
    SELECT @+= FORMAT(CAST(SUBSTRING(a, @r*9+1, 9) AS INT),
        N'║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║P') FROM t
    SET @r+=1
    IF @r=9 SET @+= N'╚=╧=╧=╩=╧=╧=╩=╧=╧=╝P'
    ELSE IF @r%3=0 SET @+= N'╠=╪=╪=╬=╪=╪=╬=╪=╪=╣P'
    ELSE SET @+= N'╟-┼-┼-╫-┼-┼-╫-┼-┼-╢P'
IF @r<9 GOTO p
PRINT REPLACE(REPLACE(REPLACE(REPLACE(@, '=',N'═══'), '-',N'───'), '0',' '), 'P',CHAR(13))

```

In the top line of the loop I'm getting the next 9 digits of the input string from column *a* of pre-existing table *t*.

I convert that string of digits to an integer, and use the .Net `FORMAT` function to display them using a custom text template `'║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║ 0 │ 0 │ 0 ║P'`.

After that I just append the appropriate divider line, and make some byte-saving replacements before output.

Output is displayed in the results pane:

```
╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗
║ 8 │ 5 │   ║   │   │ 2 ║ 4 │   │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ 7 │ 2 │   ║   │   │   ║   │   │ 9 ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │   │ 4 ║   │   │   ║   │   │   ║
╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣
║   │   │   ║ 1 │   │ 7 ║   │   │ 2 ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║ 3 │   │ 5 ║   │   │   ║ 9 │   │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │ 4 │   ║   │   │   ║   │   │   ║
╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣
║   │   │   ║   │ 8 │   ║   │ 7 │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │ 1 │ 7 ║   │   │   ║   │   │   ║
╟───┼───┼───╫───┼───┼───╫───┼───┼───╢
║   │   │   ║   │ 3 │ 6 ║   │ 4 │   ║
╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝

```

I previously had some additional replacements for some of the other drawing characters, but they ultimately didn't save me bytes.

**EDIT 1**: Saved 8 bytes by starting `@r` at zero instead of 1, and removing some unneeded spaces.

# Answer
> 4 votes
# Retina, ~~196~~ 167 bytes

```
.{27}
¶N#=XZ#Q¶|$&
\d{9}\B
$&¶M#─┼Y#P¶|
\d{3}
 $& |
\B\d
 │ $&
^¶.*
B#=RT#E
$
¶H#=UW#K
+`#([^#¶]+)([^#¶])#
#$1#$2#$1#$2#$1#
#(.)#
$1$1$1
T`0=|#L` ═-╬

```

Try it online! Takes input as a string of length 81. Explanation: Because the box drawing characters cost three bytes, the unicode code points `═-╬` are represented in the code using `=|#A-Z` (not all the characters are used but sticking to ranges saves bytes). Additionally the rows are compressed using `#` signs: `a#bcd#e` expands to `abbbcbbbcbbbdbbbcbbbcbbbdbbbcbbbcbbbe`.

```
.{27}
¶N#=XZ#Q¶|$&

```

Inserts `╠═══╪═══╪═══╬═══╪═══╪═══╬═══╪═══╪═══╣` for every third row, plus a  at the start of every group of 27.

```
\d{9}\B
$&¶M#─┼Y#P¶|

```

Inserts `╟───┼───┼───╫───┼───┼───╫───┼───┼───╢` between the other rows, plus s at the start of those rows.

```
\d{3}
 $& |

```

Inserts s after every three digits. All the s have now been inserted.

```
\B\d
 │ $&

```

Inserts `|`s between all the remaining pairs of digits. (This one is the actual box drawing character rather than a pipe. Unfortunately the characters `─│┼` have codes too far apart from each other and the double box characters to make it worth while using placeholders.)

```
^¶.*
B#=RT#E

```

Changes the first row to `╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗` (this saves 1 byte over not adding the first row in the first place).

```
$
¶H#=UW#K

```

Adds `╚═══╧═══╧═══╩═══╧═══╧═══╩═══╧═══╧═══╝` after the last row.

```
+`#([^#¶]+)([^#¶])#
#$1#$2#$1#$2#$1#

```

Expands `a#bcd#e`, first to `a#bc#d#bc#d#bc#e`, then to `a#b#c#b#c#b#d#b#c#b#c#b#d#b#c#b#c#b#e`.

```
#(.)#
$1$1$1

```

Changes `#b#` to `bbb`. This completes the decompression.

```
T`0=|#L` ═-╬

```

Deletes all the zero entries, and replaces the placeholders with the box drawing characters.

# Answer
> 4 votes
# JavaScript (ES6), 246 bytes / 198 chars

```
(n,r=(x,y)=>x+y+x+y+x,q=s=>([u,w,x,y,z]=[...s[0]],u+r(r(w+w+w,x),y)+z+`
`))=>q`╔═╤╦╗`+n.reduce((o,v,i)=>o+"║││"[i++%3]+` ${v||" "} `+(i%9?e:`║
`+(i-27&&i-54?i<81?q`╟─┼╫╢`:e:q`╠═╪╬╣`)),e="")+q`╚═╧╩╝`

```

Input is an array of integers. Ended up using the same two helper functions as Leaky Nun's Python answer, so credit goes there.

### If `function` is required, 263 bytes / 215 chars

```
function g(n,r=(x,y)=>x+y+x+y+x,q=s=>([u,w,x,y,z]=[...s[0]],u+r(r(w+w+w,x),y)+z+`
`)){return q`╔═╤╦╗`+n.reduce((o,v,i)=>o+"║││"[i++%3]+` ${v||" "} `+(i%9?e:`║
`+(i-27&&i-54?i<81?q`╟─┼╫╢`:e:q`╠═╪╬╣`)),e="")+q`╚═╧╩╝`}

```

## Test Snippet

Any input of 81 numbers is supported (`1234`, `1, 2, 3, 4`. `[1 2 3 4]`, etc). Best viewed as full page.

```
f=
(n,r=(x,y)=>x+y+x+y+x,q=s=>([u,w,x,y,z]=[...s[0]],u+r(r(w+w+w,x),y)+z+`
`))=>q`╔═╤╦╗`+n.reduce((o,v,i)=>o+"║││"[i++%3]+` ${v||" "} `+(i%9?e:`║
`+(i-27&&i-54?i<81?q`╟─┼╫╢`:e:q`╠═╪╬╣`)),e="")+q`╚═╧╩╝`

onload=I.oninput=_=>O.innerHTML=(m=I.value.match(/\d/g))&&m.length==81?f(m.map(x=>+x)):''
```

```
<textarea id=I rows=3 style="width:95%">8, 5, 0, 0, 0, 2, 4, 0, 0, 7, 2, 0, 0, 0, 0, 0, 0, 9, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 7, 0, 0, 2, 3, 0, 5, 0, 0, 0, 9, 0, 0 ,0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 7, 0, 0, 1, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 6, 0, 4, 0</textarea>
<pre id=O>
```

# Answer
> 3 votes
# SOGL V0.12, ~~174~~ ~~172~~ ~~164~~ ~~160~~ 158 bytes

```
«ž#>]Wž²6√±_ΕΨ╥╬]v←ē⅓ZΗ⌡z∫◄‽q   §↑╗∑Ολ[Μ↕z↓/∆Yn⁄:Ο║χ≥¾▓g*≈]═+π℮─6⁽SE/⁷,0+►Ƨ⌡u\^⁄-▼0cΦ“╤─┼╬│║═╔╗╚╝”Φ⅜nΡ¡ΞΨīŗ(`½│uģ“ ╬ζ─{ζ} 6Δ¹∑A'⁄─{IaW}¹∑#¶ŗ3 ¶ŗ ”+Ƨøp+!!┌d0@ŗčŗ

```

Overly long explanation:

```
...“                          push a big base-43 encoded number; will be used later. It's pushed here to save a byte on a quote
    ...”                      push "╤─┼╬│║═╔╗╚╝" - the chars in SOGLs encoding
        ...“                  push 679301851737965572513837476350078477
             ╬                push "╬"
              ζ               convert it to its codepoint (9580)
               ─              convert that number to an array of base-9580 numbers
                {ζ}           convert each number to a character (pushing each on the stack)
                    6Δ        push all ascii chars up to 6 (" !"#$%&'()*+,-./0123456")
                      ¹∑      join all the strings on the stack together ("╤─┼╬│║═╔╗╚╝╦╟╫╢╠╪╣╧╩ !"#$%&'()*+,-./0123456")
                        A     save on variable `A`. Now ontop of the stack is the 1st big number
                         '⁄─  onvert from base 43

{   }                           for each number do
 I                                increase
  aW                              get its position in the variable A
     ¹∑                         join all the strings ontop of the stack (the loop above pushed each char separately)
       #¶ŗ                      replace quote (") characters with newlines
          3 ¶ŗ                  replace 3s with "¶"
               ”+               append "”"
                 Ƨøp+           append "øp"
                     !!         execute the created code as SOGL
                       ┌        push "-"
                        d       push variable d - defaults to string input. In a full program could be set as an input
                         0@ŗ    replace zeroes with spaces
                            č   chop into an array
                             ŗ  replace ["-" with input chopped - so each iteratively]

```

The program that's executed:

```
───!#
 - $
¶%&¶'(
)╪)╪)+
)╤)╤),
)╧)╧).
┼#
+╬+/
0!╫0!1
,╦,2
.╩.4
5│$║&
#0
═══)
$│$5
║&&%
╠/╬+╣6'*
╟1╫0!╢(
(6
╔2╦,╗6'**╚4╩.╝”øp

```

where all but last line are just `in the entire program replace occurrences of the last char of this line with the rest of this line`. This is the reason it was possible to make half of the chars just random ascii (but getting so that spaces, dashes, and quotes are usefully used took a while to figure out)

```
...”    push the whole sudoku grid
    øp  print nothing (prevents bug that this code would already print and pop the result)

```

Try it Here!
The online interpreter code is more correct because tabs don't work with SE

-8 bytes: brute force replacement compressing the entire board, then replacing foreign chars (to the codepage) with their codepoints. Doing this took an hour less than the old program...
-4 bytes: compressing the compressed string...
-2 bytes: using a variable+string instead of array

# Answer
> 2 votes
# With ideas harvested from other answers:

## C# (.NET Core), 401 bytes, 349 Chars

```
string s(string x){Func<string,string,string>q=(m,n)=>m+n+m+n+m;var a="╔"+q(q("=","╤"),"╦")+"╗";for(var i=0;i<9;) {a+=int.Parse(x.Substring(i*9,9)).ToString("\n║"+q(q(" 0 ","│"),"║")+"║\n")+(i++<8?(i%3>0?"╟"+q(q("-","┼"),"╫")+"╢":"╠"+q(q("=","╪"),"╬")+"╣"):"╚"+q(q("=","╧"),"╩")+"╝");}return a.Replace("=","═══").Replace("-","───").Replace("0"," ");}

```

### Ungolfed:

```
static public string s(string x)
{
    Func<string,string,string>q=(m,n)=>m+n+m+n+m;
    var a="╔"+q(q("=","╤"),"╦")+"╗";
    for (var i=0;i<9;) //once per row
    {
        //parse that row to an int, then spit out a formatted string
        a += int.Parse(x.Substring(i*9,9)).ToString("\n║"+q(q(" 0 ","│"),"║")+"║\n")
          // as well as a trailing row for the box
          + (i++<8?(i%3>0?"╟"+q(q("-","┼"),"╫")+"╢":"╠"+q(q("=","╪"),"╬")+"╣"):"╚"+q(q("=","╧"),"╩")+"╝");
    }
    //expand placeholder characters before returning
    return a.Replace("=","═══").Replace("-","───").Replace("0"," ");
}

```

Try it online!

# My Answer:

## C# (.NET Core), 509 430 418 bytes, 328 chars

```
string b(string x){var a="╔=╤=╤=╦=╤=╤=╦=╤=╤=╗\n║";for(int i=0,j=0,k,l,m;j<3;j++)for(k=0;k<3;k++){for(l=0;l<3;l++)for(m=0;m<3;)a+=" "+x[i++]+(m++<2?" │":" ║");a+=i<80?(k<2?"\n╟-┼-┼-╫-┼-┼-╫-┼-┼-╢\n║":"\n╠=╪=╪=╬=╪=╪=╬=╪=╪=╣\n║"):"\n╚=╧=╧=╩=╧=╧=╩=╧=╧=╝";}return a.Replace("=","═══").Replace("-","───").Replace("0"," ");}

```

### Ungolfed:

```
public string s(string x)
{
    var a = "╔=╤=╤=╦=╤=╤=╦=╤=╤=╗\n║";
    for (int i=0,j=0,k,l,m;j<3;j++)
    {
        for (k = 0; k < 3;k++)
        {
            for (l = 0; l < 3; l++)
            {
                for (m = 0; m < 3;)
                    a += " " + x[i++] + (m++ < 2 ? " │" : " ║");
            }
            a += i < 80 ? (k < 2 ? "\n╟-┼-┼-╫-┼-┼-╫-┼-┼-╢\n║": "\n╠=╪=╪=╬=╪=╪=╬=╪=╪=╣\n║")
                        : "\n╚=╧=╧=╩=╧=╧=╩=╧=╧=╝";
        }
    }
    return a.Replace("=", "═══").Replace("-","───").Replace("0"," ");
}

I also looked at using a lambda for the `for` loops here, but it actually cost me one byte (saved 10 bytes per loop, with 41 bytes of overhead).

```

Try it online!

# Answer
> 2 votes
## Batch, 332 bytes

```
@echo off
set/ps=
set s=%s:0= %
call:l É Í Ñ Ë »
set t="Ç Ä Å × ¶"
for %%i in (%t% %t% "Ì Í Ø Î ¹" %t% %t% "Ì Í Ø Î ¹" %t% %t% "È Í Ï Ê ¼")do call:c %%~i
exit/b
:c
set t=º
for %%j in (³ ³ º ³ ³ º ³ ³ º)do call set t=%%t%% %%s:~,1%% %%j&call set s=%%s:~1%%
echo %t%
:l
set t=%2%2%2%3%2%2%2%3%2%2%2
echo %1%t%%4%t%%4%t%%5

```

Needs the console to be in CP437. If that's not your default, then you can change it using the `CHCP 437` command if your console is set to TrueType fonts. (It will only work with raster fonts if CP437 is already your default code page.) This is what the code looks like in CP437:

```
@echo off
set/ps=
set s=%s:0= %
call:l ╔ ═ ╤ ╦ ╗
set t="╟ ─ ┼ ╫ ╢"
for %%i in (%t% %t% "╠ ═ ╪ ╬ ╣" %t% %t% "╠ ═ ╪ ╬ ╣" %t% %t% "╚ ═ ╧ ╩ ╝")do call:c %%~i
exit/b
:c
set t=║
for %%j in (│ │ ║ │ │ ║ │ │ ║)do call set t=%%t%% %%s:~,1%% %%j&call set s=%%s:~1%%
echo %t%
:l
set t=%2%2%2%3%2%2%2%3%2%2%2
echo %1%t%%4%t%%4%t%%5

```

# Answer
> 1 votes
# Tcl, 373 bytes (273 chars)

Very naïve approach, but I just had to do it even it not being a winner by any measure:

```
puts ╔[set D ═══]╤$D╤$D╦$D╤$D╤$D╦$D╤$D╤$D╗
set r ║
lmap x $L {set r $r\ [expr $x?$x:{ }]\ [expr [incr i]%3?"│":"║"]
if ![expr $i%9] {puts $r\n[expr $i%27?"╟[set S ───]┼$S┼$S╫$S┼$S┼$S╫$S┼$S┼$S╢":$i<72?"╠$D╪$D╪$D╬$D╪$D╪$D╬$D╪$D╪$D╣":"╚$D╧$D╧$D╩$D╧$D╧$D╩$D╧$D╧$D╝"]
set r ║}}

```

Try it online!

---

Same chars expense but more bytes:

# Tcl, 421 bytes (273 chars)

```
puts ╔[set D ═══]╤$D╤$D╦$D╤$D╤$D╦$D╤$D╤$D╗
set r ║
lmap x $L {set r $r\ [expr $x?$x:{ }]\ [expr [incr i]%3?"│":"║"]
if ![expr $i%9] {puts $r\n[expr $i%27?"╟───┼───┼───╫───┼───┼───╫───┼───┼───╢":$i<72?"╠$D╪$D╪$D╬$D╪$D╪$D╬$D╪$D╪$D╣":"╚$D╧$D╧$D╩$D╧$D╧$D╩$D╧$D╧$D╝"]
set r ║}}

```

Try it online!

# Answer
> 1 votes
# Chip, 3645 bytes

<sup>...that's not a typo...</sup>

```
ooooooZZ-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-).
|`xxxx-x--(x---x---x---x---x-v-x---x---x---x---x---x-.`K-)-K-)-K-)-K-).
|b|`xx-x--(x-v-x---x-v-x---x-x-x---x-v-x---x-v-x---x-x-x---x-v-x---x-.`K-).
|>xd`x-x(v-x-x-x-v-x-x-x-v-x-x-x-v-x-x-x-v-x-x-x-v-x-x-x-v-x-x-x-v-x-x-x-.|
||`--x-x-x(x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x/.
|`--z',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\',/\','
`-. |,< >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.| >.|
*-x-/xZ/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ^/xZ'
Z~' |`'|`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`' |`','`'
    `)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)-K-)'
=
oooooo).h
`)))--^M^Zh
=
oooooo
|    `(--------------------------------------------------------------------------------------------------------va
KZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ^cg
)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx-xKZvvZ
xxxxxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxxx-Kxxxx}e
)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)x))xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)x))xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)x)b`feac
  c
=
oooooo
,'   `(--------------------------------------------------------------------------------------------------------.cba
KZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ^x^^)v--.
xx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxxx-xK-'f e`.
)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx-x-K-+Z+Z}e
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxK^}b gac
xxxxxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxxx-K^d
=
oooooo
,-'
KZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZtabgfv------.
)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx-xK^^x-Zv-vZ}e
xxxxxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxxxK^---^}cade,]b
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)-K----^-^^~'
,v'
db
=
oooooo
,--' `(--------------------------------------------------------------------------------------------------------v-.,-v-ZZZZZZZZZZZZf
KZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'a{x.df
)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xx)xxKx-xxv+Zc
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx)x-KZx+bge
xx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxx)xxxxxxxxxxxx---K\--^c
 a^b
=
oooooo
,---'`(--------------------------------------------------.
KZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'gf
)xxxxx)xxxxx)xxxxx)xxxxx)xxxxx)xxxxx)xxxxx)xxxxx)xxxxx)xx-^KZc
)xxxxx)x)xxx)x)xxx)xxxxx)x)xxx)x)xxx)xxxxx)x)xxx)x)xxx)xxbahKZ\ZZZ
x))xxxxxxxxxxxxxxxx))xxxxxxxxxxxxxxxx))xxxxxxxxxxxxxxxx))-K-eh|fff
 ,--K-v-v-K--v-vK-v---K-----K-----K-----K-----K-----K `--Z-Z--'
A/ab/B/e/C/cd/D/-e/A
*}s

```

Try it online!, sort of. The TIO version contains a cutoff about a third of the way in (the `t` after the 4th `oooooo`), so that it should terminate in less than 60 seconds. The full version takes about 1m25s on my machine, and TIO seems about half as quick. This also means the TIO only shows the first 7 lines of output.

My first draft weighed in at a massive 19758 bytes, and took me about 8m30s to run. The final solution, pre-golfing, was a spry 5980 bytes, taking only 2m07s.

### So, how's it work, then?

This takes a string of 82 bytes, 81 digits, followed by a terminator. `\0` or `\n` or even another number will do. (This implementation actually only looks at the first 81, but requires at least one more, since Chip will terminate if it has exhausted its input. If this is unacceptable, the flag `-z` may be used, which effectively appends an infinite number of `\0` bytes to the end of the input.) The shortened TIO code doesn't actually get to all 81 bytes, so the point is moot there.

The way I've implemented this, it only looks at the low 4 bits of the input, so anything, really, can be a sudoku 'puzzle', from raw binary data, to the lesser-known works of Shakespeare. Any character whose low 4 bits are all zero will appear as a space (a special case), all other characters map into `123456789:;<=>?`. (So, the last few aren't digits, but neither is 10 a valid number in normal sudoku).

For the box-drawing characters, it produces UTF-8, equating to 3 bytes each.

### What about the actual implementation?

Chip is a 3D language that is inspired by integrated circuits. It has wires, logic gates, and memory cells. Most stuff is done on 2D planes, but these planes may be stacked atop one another. That is how this program is built.

The lines that start with `=` are the layer separators. Then, the layers are stacked, with the top and left sides aligned. The `o`'s serve as pins, allowing signals to pass from one layer to another.

Each layer here has a purpose, you could think of them as functions. The first layer controls everything; it 'calls' each of the other layers in turn. There is a repeating left-to-right pattern here. That pattern keeps track of which of the 19 lines of output we are currently printing.

The second layer is rather tiny, and it has a very tiny job. It sets the `0x80` bit for all the lines of output except the lines that contain numbers. `h` is the Chip element that corresponds to the `0x80` bit. (The low end of the alphabet `h` through `a` define all eight output bits.)

Layer three is where we really get into the meat of printing. This layer is in charge of line one. The ungolfed version has eight rows of `x`'s and `)`'s, mapping to 0's and 1's for each of the eight bits of each byte. However, we can take advantage of the patterns in the bits to accomplish the same task in fewer rows.

Layer four is much like the third. It handles the horizontal double lines.

Layer five handles the last line. Note that it is missing the wire along the top that the other layers have. This is because we don't need to return control to the sequencer. Instead, we can just terminate execution here with `t`.

Layer six handles the horizontal single lines.

Layer seven is where the numbers are printed. It is 'called' for each the nine numeric lines. It consumes 9 bytes of input as part of its execution.

# Answer
> 1 votes
# JavaScript (ES6), 222 bytes

Using short syntax for ES6 functions - 174 chars encoded in utf8, 222 bytes (https://mothereff.in/byte-counter). Using `function ...` requires 16 more bytes.

```
F=v=>[1,...v].map((x,i)=>'│║│'[i%3]+` ${x||' '} `+(i%9?'':`║
${[h,r,s,u,t]=i%27?'─╟╫┼╢':i>80?'═╚╩╧╝':i?'═╠╬╪╣':'═╔╦╤╗',r+(s=(u=(h+=h+h)+u+h+u+h)+s)+s+u+t}
`)).join``.slice(6)

```

*Less golfed*

```
F=v=>{
   // horizontal lines are appended after each 9th element
   // so I need to prepend a dummy first element to draw the top horizontal line
   v = [1, ...v];
   return v.map( (x,i) =>
     '│║│'[i % 3] + ` ${x||' '} ` // left bar and cell value
     + ( i % 9 ? '' // add horizontal line after each 9th element
       // the line drawing characters are chosen according to the value of i
       : `║\n${ [h, r, s, u, t] =
         i % 27 != 0
         ? '─╟╫┼╢'
         : i > 80
           ? '═╚╩╧╝' // i==81, bottom row
           : i != 0
             ? '═╠╬╪╣'
             : '═╔╦╤╗', // i==0, top row
         r + (s = (u = (h += h + h) + u + h + u + h) + s) + s + u + t
         }\n`
       )
   ).join``
   .slice(6) // cut the first cell (the dummy element)
}

```

```
F=v=>[1,...v].map((x,i)=>'│║│'[i%3]+` ${x||' '} `+(i%9?'':`║
${[h,r,s,u,t]=i%27?'─╟╫┼╢':i>80?'═╚╩╧╝':i?'═╠╬╪╣':'═╔╦╤╗',r+(s=(u=(h+=h+h)+u+h+u+h)+s)+s+u+t}
`)).join``.slice(6)

function go() {
  var i=I.value
  i = i.match(/\d+/g).map(x => +x); // convert strings to numbers
  O.textContent = F(i)
}
```

```
#I { width: 90% }
```

```
<input id=I value='8 5 0 0 0 2 4 0 0 7 2 0 0 0 0 0 0 9 0 0 4 0 0 0 0 0 0 0 0 0 1 0 7 0 0 2 3 0 5 0 0 0 9 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 8 0 0 7 0 0 1 7 0 0 0 0 0 0 0 0 0 0 3 6 0 4 0'>
<button onclick='go()'>go</button>
<pre id=O></pre>
```

# Answer
> 1 votes
# Java (OpenJDK 8), 279 bytes

```
String f(int[]a){String P="0121213121213121214",R[]={"╔═╤╦╗","║ │║║x","╟─┼╫╢","╠═╪╬╣","╚═╧╩╝"},r="";for(int X:P.getBytes()){for(int x:P.replace("1",R[X-=48].length()>5?"151":"111").getBytes())r+=R[X].charAt(x-48);r+="\n";}for(int i:a)r=r.replaceFirst("x",i>0?""+i:" ");return r;}

```

Try it online!

For the byte count, use CP-437, which is natively supported by Java as `IBM437` (recent APIs) or `Cp437` (older APIs); so use a system that has this charset has this charset as default charset.

This code is compatible from Java 5 onwards, but was tested on Java 8 only.

### Explanation

```
String f(int[]a){
  String P="0121213121213121214",                         // Both lines and rows are repeated according to this pattern.
         R[]={"╔═╤╦╗","║ │║║x","╟─┼╫╢","╠═╪╬╣","╚═╧╩╝"},  // Characters found on each line.
                                                          //   (note the 'x')
         r="";                                            // The string under construction
  for (int X: P.getBytes()) {                             // For each line,
    for (int x:                                           //  For each character in the pattern,
         P.replace("1",R[X-=48].length()>5?"151":"111")   //    *but* with a cell width of 3,
                                                          //    and with an optional character ('x')
         .getBytes())
      r+=R[X].charAt(x-48);                               //   append the real mapped character
    r+="\n";                                              //  then append a new line
  }
  for(int i:a)                                            // For each number in the input
    r = r.replaceFirst("x",i>0?""+i:" ");                 //  replace the first 'x' with that number.
                                                          //    (or space if zero)
  return r;                                               // Return the constructed string.
}

```

# Answer
> 0 votes
# SlimSharp, 284 characters (bytes not counted)

```
S b(S x){S a="╔=╤=╤=╦=╤=╤=╦=╤=╤=╗\n║";for(I i=0,j=0,k,l,m;j<3;j++)for(k=0;k<3;k++){for(l=0;l<3;l++)for(m=0;m<3;)a+=" "+x[i++]+(m++<2?" │":" ║");a+=i<80?(k<2?"\n╟-┼-┼-╫-┼-┼-╫-┼-┼-╢\n║":"\n╠=╪=╪=╬=╪=╪=╬=╪=╪=╣\n║"):"\n╚=╧=╧=╩=╧=╧=╩=╧=╧=╝";}return a.R("=","═══").R("-","───").R("0"," ");}

```

This is a simple adaption of my C# answer.

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


# Question
Title: Print your username by ONLY using the characters in your username
You have to print out your username, by only using the characters in your username.

Standard loopholes are forbidden

This is not , so shortest does not win

Don't modify your username please

And each language be used one time

# Answer
# Swap, 39 bytes

```
'n'e'i'r'B'''O' 'r'o'n'o'Cooooooooooooo

```

Try it online!

I thought it would make sense for me to participate in this challenge, considering I have both spaces and the `'` character at my disposal. Terminates, I think, by crashing. Doesn't use the Swapping nature of the language.
> 7 votes

# Answer
# V (vim), 7 bytes

```
iDingus

```

Try it online!

Yep, I sure am.
> 5 votes

# Answer
# Charcoal, 4 bytes

```
Wezl

```

I hope I remembered how Charcoal works?
> 1 votes

# Answer
# Text, 6 bytes

```
hakr14

```

---

Yucky bad trivial solution. Basically, every program in Text is a quine.
> 0 votes

# Answer
# ///, 22 bytes

```
caird coinheringaahing

```

Try it online!

I may have chosen the wrong username to win this :/
> 0 votes

---
Tags: string, kolmogorov-complexity, popularity-contest, restricted-source
---


title: Efficient Bytewise FizzBuzz

text:
# Question
Title: Efficient Bytewise FizzBuzz
Given the following Python "reference implementation" of non-terminating FizzBuzz:

```
i=1
while True:
    if i%15 == 0:
        print("FizzBuzz")
    elif i%3 == 0:
        print("Fizz")
    elif i%5 == 0:
        print("Buzz")
    else:
        print(i)
    i += 1

```

We can represent its output as an infinite array of chars/bytes (assuming \n line terminators) that looks like the following:

```
['1', '\n', '2', '\n', 'F', 'i', 'z', 'z', '\n', '4', '\n', 'B', 'u', 'z', 'z', '\n', 'F', 'i', 'z', 'z', ...]

```

**Your task is to write the shortest function or program that returns the character at the Nth index of this array.**

Sounds easy? Your code should also work for extremely large values of N, for example 1e100.

It is possible to calculate the Nth byte of this output array in O(log(n)) time (or possibly better) - *how* is left as an exercise for the reader.

**Your solution must run in O(poly(log(n))) time (or better).** There is no hard execution time limit, but as a rough guideline you should be able to solve the `N=1e100` case almost instantaneously.

This is : the shortest code in bytes wins.

# Test cases:

```
f(0)      == '1'
f(1)      == '\n'
f(2)      == '2'
f(10)     == '\n'
f(100)    == '\n'
f(1000)   == 'z'
f(100000) == 'F'
f(1e10)   == '5'
f(1e100)  == '0'

```

Some more, randomly generated testcases: https://gist.github.com/DavidBuchanan314/65eccad5032c427218eb9c269b55e869

Note: these test cases are correct to the best of my knowledge. If you have contradictory findings, I am open to discussion.

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

*Saved 2 bytes thanks to @user202729*

Expects a BigInt. Outputs `#` instead of `\n` for readability.

```
f=(n,k=0n,p=10n**k,x=55n+8n*k,q=p*3n/5n*x||30n)=>n<q?(g=p=>j--&&([["Fizz"][p%3n]]+[["Buzz"][p%5n]]||p)+'#'+g(++p))(p+n/x*(j=15n))[n%x]:f(n-q,-~k)

```

Try it online!

## How?

### Method

We use a recursive function that quickly computes the number of characters required to build all blocks of 15 terms using numbers of \\$1\\$, \\$2\\$, ..., \\$N\\$ digits. This takes \\$\approx \log(n)\\$ iterations, where \\$n\\$ is the input.

The only block that is explicitly generated is the last one, which contains the character we're looking for.

### Formulae

Below is the template of a block of 15 terms of the sequence, where `#` is the separator and `@` is a placeholder for a full number. (Note that the leading term modulo \\$15\\$ can be anything between \\$0\\$ and \\$14\\$. The length of the block doesn't depend on that.)

```
        <--------- 55 characters and 8 full numbers ---------->
        FizzBuzz#@#@#Fizz#@#Buzz#Fizz#@#@#Fizz#Buzz#@#Fizz#@#@#
        ^        ^ ^ ^    ^ ^    ^    ^ ^ ^    ^    ^ ^    ^ ^
mod 15: 0        1 2 3    4 5    6    7 8 9    10  11 12  13 14

```

All terms in such a block are meant to have the same number of digits \\$k+1\\$. For \\$k\>0\\$, the length of the block is \\$55+8k\\$ characters. For \\$k=0\\$, we can only build a partial block of 9 terms whose length is \\$30\\$ characters:

```
<------ 30 characters ------->
1#2#Fizz#4#Buzz#Fizz#7#8#Fizz#

```

The number of terms with \\$k+1\\$ digits is \\$9\times 10^k\\$.

The number of blocks with \\$k+1\\$ digits is:

$$\left\lceil10^k\times\dfrac{9}{15}\right\rceil=\left\lceil10^k\times\dfrac{3}{5}\right\rceil$$

(where the ceiling is only needed for \\$k=0\\$)

And the number of characters is:

$$\cases{ 30&k=0\\ 10^k\times\dfrac{3}{5}\times (55+8k)&k\>0 }$$

## Commented

```
f = (                      // f is a recursive function taking:
  n,                       //   n = input
  k = 0n,                  //   k = exponent
  p = 10n ** k,            //   p = 10 ** k
  x = 55n + 8n * k,        //   x = length of a block of 15 terms, using numbers of
                           //       k + 1 digits
  q = p * 3n / 5n * x      //   q = number of characters added when all numbers of
      || 30n               //       k + 1 digits are used (p = 1 is an edge case)
) =>                       //
n < q ?                    // if n is less than q:
  ( g = p =>               //   g is a recursive function that builds the block of 15
                           //   terms in which lies the character we're looking for
    j-- &&                 //     abort if j = 0 (decrement it afterwards)
    (                      //     otherwise:
      [["Fizz"][p % 3n]] + //       append 'Fizz' if p is a multiple of 3
      [["Buzz"][p % 5n]]   //       append 'Buzz' if p is a multiple of 5
      || p                 //       append p if it's neither a multiple of 3 or 5
    ) + '#' +              //       append the separator
    g(++p)                 //       append the result of a recursive call to g
  )(p + n / x * (j = 15n)) //   initial call to g: we set j to 15 and add to p the
                           //   number of terms that can be generated with n
                           //   characters, using only full blocks of 15 terms
  [n % x]                  //   extract the character at n modulo x
:                          // else:
  f(n - q, -~k)            //   recursive call to f with n - q and k + 1

```
> 20 votes

# Answer
# Python 2, ~~216~~ ~~212~~ ~~209~~ ~~189~~ ~~183~~ 182 bytes

```
f=lambda i,j=90:j*"."and f(i,j-1)+("Fizz"*(j%3<1)+"Buzz"*(j%5==1)or str(10*i+j-1))+"\n"
n,i,l=input()-30,1,len
while n/i/l(f(i)):n-=l(f(i))*i;i*=10
s=f(i+n/l(f(i))*9);print s[n%l(s)]

```

Try it online! Compares `n` against a number increasing by more than tenfold every iteration, so I assume this should take log time. Edit: Saved 4 bytes thanks to @Danis. Saved ~~3~~ 6 bytes thanks to @JonathanAllan. Saved 1 byte thanks to @ovs.
> 8 votes

# Answer
# Ruby, ~~170 ... 139~~ 138 bytes

```
f=->n,d=0,c=55,a=30,b=6,t=1{n<a ?((b%10-5..10).map{|x|:FizzBuzzz[x**4%-15,x==0?8:4]||d+(n/c)*15+x}*$/)[n%c]:f[n-a,d+t*15,c+=8,b*c,b*10,b]}

```

Try it online!

### How:

```
f=->n,d=0,c=55,a=30,b=6,t=1

```

Initialize some parameters: d is the last number of the previous block, c is the size in bytes of the 15-number sequence in the current block, a is the length of the current block, b is the number of sequences in the next block, and t is the number of sequences in the current block.

```
    {n<a ?

```

First check: is the byte in the current block?

```
    ((b%10-5..10)

```

Build a FizzBuzz sequence, starting from 1 for the first iteration, and from -5 after that. We could stop at 9, but going to 10 adds the final newline (the last "Buzz" is ignored) at the cost of 1 byte.

```
    :FizzBuzzz[x**4%-15,x==0?8:4]||d+(n/c)*15+x

```

Courtesy of Lynn: shortest Ruby FizzBuzz generator ever. The Fizzes and Buzzes are in fixed position, we have to find the beginning of the sequence, which is the (n/c)th sequence of the current block. The starting number is d plus 15 times the position of the sequence in the block.

```
    }*$/)[n%c]:

```

Join using newlines, get the nth character of the block, and since this is the (n/c)th slice, this is the (n%c)th byte of this slice.

```
f[n-a,d+t*15,c+=8,b*c,b*10,b]}

```

If the byte is not in the current block, move to the next:

* decrease n by the length of the current block
* increase d by 15 times the number of sequences in the current block
* increase the length in byte of a sequence by 8
* calculate the number of bytes in the next block
* multiply the number of sequences in a block by 10
* ~~still lose to Javascript by 1 byte~~???
* reduce by 1 byte every day (and thanks Dingus for -1 byte)
> 5 votes

---
Tags: code-golf, restricted-complexity, fizzbuzz
---


title: Array alignment addition

text:
# Question
Title: Array alignment addition
## Introduction

Consider two non-empty integer arrays, say **A = \[0 3 2 2 8 4\]** and **B = \[7 8 7 2\]**. To perform *alignment addition* on them, we do the following:

1. Repeat each array enough times to have total length \\$\text{lcm(length(A), length(B))}\\$. Here \\$\text{lcm}\\$ stands for lowest common multiple.

```
 A -> [0 3 2 2  8 4][0 3  2 2 8 4]
 B -> [7 8 7 2][7 8  7 2][7 8 7 2]

```
2. Perform element-wise addition on the repeated arrays, and cut the result at every position where there's a cut in either of them.

```
 A -> [0  3 2 2   8  4][0 3  2  2  8 4]
 B -> [7  8 7 2][ 7  8  7 2][7  8  7 2]
   -> [7 11 9 4][15 12][7 5][9 10 15 6]

```
3. This array of arrays is your result.

## The task

Your inputs are two non-empty arrays of integers, and your output shall be the result of their alignment addition, as defined above. The inputs and output can be in any reasonable format. You don't have to worry about integer overflow when performing the addition.

## Rules and scoring

You can write a full program or a function. The lowest byte count wins.

## Test cases

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

```

# Answer
## JavaScript (ES6), ~~101~~ 99 bytes

Takes input as 2 arrays. Returns a string.

```
f=(a,b,j=0,s='')=>a.map((v,i)=>(s+=i*j?' ':s&&'][',s+=b[j]+v,j=++j%b.length))|j?f(a,b,j,s):`[${s}]`

```

### How it works

We iterate on the first array `a` with a pointer `i` while updating another pointer `j` into the second array `b`. The sums `a[i] + b[j]` are appended to the output string `s`. A separator is inserted each time `i == 0` or `j == 0`. We repeat this process until `j` is back exactly at the beginning of `b` at the end of an iteration.

*Note:* When the `|` operator is applied, `a.map(...)` is coerced to either `NaN` (if `a` contains more than one element) or the current value of `j` (if `a` contains exactly one element). Therefore, `a.map(...)|j == j` in all cases and is safe to use here.

### Test cases

```
f=(a,b,j=0,s='')=>a.map((v,i)=>(s+=i*j?' ':s&&'][',s+=b[j]+v,j=++j%b.length))|j?f(a,b,j,s):`[${s}]`

console.log(f([1], [4]));
console.log(f([1,2,-3,-4], [15]));
console.log(f([0,-4], [2,1,0,-3]));
console.log(f([0,3,2,2,8,4], [7,8,7,2]));
console.log(f([18,17,16], [-1,-2,-3,-4]));
console.log(f([18,17,16,15], [-1,-2,-3,-4]));
console.log(f([1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
console.log(f([1,1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
console.log(f([1,1,1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
```
> 9 votes

# Answer
## Haskell, ~~84~~ 79 bytes

```
a#b=a%b where(c:d)%(e:f)|(x:y)<-d%f=(c+e:x):y;[]%[]=[[]];c%[]=[]:c%b;_%d=[]:a%d

```

My first version was the same in more readable layout:

```
a#b=a%b where
 (c:d)%(e:f)|(x:y)<-d%f=(c+e:x):y
 []%[]=[[]]
 c%[]=[]:c%b
 _%d=[]:a%d

```

Using a local definition to avoid having to give `(%)` extra arguments for `a` and `b`. Amazingly, this is almost the same solution given at almost the same time as @nimi's, from whom I took the idea of using only one line for the local definition.

Usage:

```
*Main> [0,3,2,2,8,4] # [7,8,7,2]
[[7,11,9,4],[15,12],[7,5],[9,10,15,6]]

```
> 6 votes

# Answer
# PHP, ~~126~~ 120 bytes

```
function($a,$b){do{$c[$j][]=$a[$i%$x=count($a)]+$b[$i%$y=count($b)];++$i%$x&&$i%$y?:$j++;}while($i%$x|$i%$y);return$c;};

```

Try it here!

Anonymous function that returns the resulting array of arrays.

Essentially, we loop through the contents of both of our arrays, modding our iterator by the length of the array to simulate 'copying' them. Taking each of the values from the arrays, we sum them and add them to an array in `$c`. If we reach the end of one of our input arrays (a split, in terms of the challenge), we start assigning into a new array in `$c`.

The reason for the `do while` loop is because our condition is based on `$i`, which starts at `0`. If we use a loop where the condition is checked at the beginning, the loop wouldn't run

We only end the summation once we reach the end of both of the arrays at the same time, which would imply the LCM.
> 4 votes

# Answer
## Haskell, ~~87~~ 84 bytes

```
a#b=a%b where[]%[]=[[]];(e:f)%(g:h)=f%h!(e+g);e%[]=[]:e%b;_%g=[]:a%g
(m:n)!l=(l:m):n

```

Usage example: `[0,3,2,2,8,4] # [7,8,7,2]` -\> `[[7,11,9,4],[15,12],[7,5],[9,10,15,6]]`.

Simple recursion. Base case: both lists are empty. If only one of them is empty, restart with a full version and start a new cluster in the output. If none is empty, prepend the sum to the from element.

Have also a look at @Christian Sievers' answer, which is almost identical and was posted a few seconds earlier.
> 4 votes

# Answer
# , ~~34~~ 32 bytes

```
[:(<;.1~*)/[:+/*.&#$&>,:&(;2>#\)

```

Try it online!

## Explanation

```
[:(<;.1~*)/[:+/*.&#$&>,:&(;2>#\)  Input: array A (LHS), array B (RHS)
                             #\   Length of each prefix of A and B
                           2>     Less than 2
                          ;       Link each with A and B
                      ,:&         Pair them
                  #               Length of A and B
               *.&                LCM of the lengths
                    &>            For each box
                   $              Reshape it to the LCM of the lengths
           [:+/                   Reduce by addition
[:        /                       Reduce by
        *                           Sign of RHS
   <;.1~                            Box each partition of LHS

```
> 2 votes

# Answer
# Python 3.5 - (~~146~~~~137~~~~134~~130+12) = 142 Bytes

```
import math
def s(a,b):
 l,k,*r=map(len,[a,b])
 for i in range(l*k//math.gcd(l,k)):
  r+=a[i%l]+b[i%k],
  if i%k==k-1or i%l==l-1:print(r);r=[]

```

I cannot figure out how to put the whole for loop in one line.

**Edits:**
> 2 votes

# Answer
# Python 2, 119 bytes

```
a=input()
i,v,l=0,list(a),len
while 1:q=l(v[0])>l(v[1]);print map(sum,zip(*v)[i:]);i=l(v[q]);v[q]+=a[q];1/(i-l(v[q^1]))

```

Takes input from stdin as two tuples separated by comma, outputs resulting lists to stdout. Terminates by raising the `ZeroDivisionError` exception, since that seems to be allowed.

For example, if the input is `(0, 3, 2, 2, 8, 4), (7, 8, 7, 2)`, the program will print

```
[7, 11, 9, 4]
[15, 12]
[7, 5]
[9, 10, 15, 6]

```

to stdout and the exception traceback to stderr.
> 2 votes

# Answer
# Octave , 113 bytes

```
@(a,b)mat2cell(sum([repmat(a,1,(L=lcm(A=numel(a),B=numel(b)))/A);repmat(b,1,L/B)]),1,diff(unique([0:A:L,0:B:L])))

```

this function is directly callable to call it place it in parenthesis and call as (@(a,b)...)(\[1 2 3 4\],\[6 4 5\])
> 2 votes

# Answer
## CJam, 30 bytes

```
{Sf*Laf+_s,f*:.+La/0=S2*a-Sa/}

```

Try it online!

Takes input as a pair of lists.

### Explanation

The idea is to insert some markers into the input arrays (in the form of short strings) which indicate where the aligned array ends, and where we need to insert the breaks in the arrays. This way we can avoid having to compute the LCM.

```
Sf*    e# Riffle each list with spaces. These are just place holders, so that having
       e# an array-end marker between two elements doesn't misalign subsequent elements.
Laf+   e# Append an empty string to each list. This is the array-end marker.
_s,    e# Convert the pair of lists to a string and get its length. This is always
       e# greater than the number of elements in either input.
f*     e# Repeat either array that many times. This is definitely more than necessary
       e# to reach the LCM (since multiplying by the length of the other list always
       e# gives a common multiple).
:.+    e# Pairwise addition of the list elements. There are four cases:
       e# - Both elements are numbers, add them. This is the actual addition
       e#   we need for the problem.
       e# - Both elements are spaces. This is just a regular position between
       e#   list elements.
       e# - One is a space, one is empty: the result is a single space, and
       e#   this marks a position where one of the arrays ended, which means
       e#   we need to split here.
       e# - Both elements are empty. This happens at the LCM of both list lengths
       e#   and indicates where we need to stop the output.
La/0=  e# Split the input around empty strings and discard everything except
       e# the first chunk.
S2*a-  e# Remove the double-space strings, we no longer need them.
Sa/    e# Split the list around single spaces.

```
> 2 votes

# Answer
# Jelly, ~~21~~ ~~20~~ 18 bytes

```
ṁ€L€æl/$S
J€ỊÇœṗÇḊ

```

Try it online!

### How it works

```
ṁ€L€æl/$S  Helper link. Argument [X, Y] (arrays of integers).

       $   Combine the two links to the left into a monadic chain.
  L€       Length each; yield the lengths of X and Y.
    æl/    Reduce by least common multiple.
ṁ€         Mold each; cyclically repeat the elements of X and Y to extend them
           to length lcm(length(X), length(Y)).
        S  Compute the sum of the extended X and Y arrays.

J€ỊÇœṗÇḊ   Main link. Argument [A, B] (arrays of integers).

J€         Indices each; replace A and B by the arrays of there 1-based indices.
  Ị        Insignificant; map 1 to itself, all other indices to 0.
   Ç       Apply the helper link to the result.
           This yield a Boolean array with a 1 (or 2) at all indices where a new
           repetition of A or B (or both) begins.
      Ç    Apply the helper link to [A, B].
    œṗ     Partition; break the result to the right at truthy elements (1 or 2) in
           the result to the right.
       Ḋ   Dequeue; remove the first element of the partition (empty array).

```
> 2 votes

# Answer
# Haskell, 166 bytes

This is probably not the most elegant approach: Basically the function `?` creates one list of the needed length with thesums, and `%` is cutting this sum up again. `!` is the final function that merges those two.

```
l=length
a?b=take(lcm(l a)$l b)$zipWith(+)(cycle a)$cycle b
l%(i:ind)|l==[]=[]|1>0=take i l:(drop i l)%(map(+(-i))ind)
a!b=(a?b)%[k|k<-[1..],k`mod`l a<1||k`mod`l b<1]

```
> 1 votes

# Answer
# \[PHP\], ~~183~~ ~~152~~ 135 bytes

```
function O($A,$B){while($f<2){$O[$k][]=$A[+$i]+$B[+$j];$f=0;isset($A[++$i])?:$i=!++$k|!++$f;isset($B[++$j])?:$j=!++$k|!++$f;}return$O;}

```

Nice version:

```
function O($A,$B)
{
    while($f<2) {
        $O[$k][]=$A[+$i]+$B[+$j];
        $f=0;
        isset($A[++$i])?:$i=!++$k|!++$f;
        isset($B[++$j])?:$j=!++$k|!++$f;
    }

    return$O;
}

```

Output:

```
array (size=4)
  0 =>
    array (size=4)
      0 => int 7
      1 => int 11
      2 => int 9
      3 => int 4
  1 =>
    array (size=2)
      0 => int 15
      1 => int 12
  2 =>
    array (size=2)
      0 => int 7
      1 => int 5
  3 =>
    array (size=4)
      0 => int 9
      1 => int 10
      2 => int 15
      3 => int 6

```
> 1 votes

# Answer
# PHP, ~~150~~ ~~121~~ 119 bytes

```
function($a,$b){while($i<2|$x|$y)$r[$k+=!($x=$i%count($a))|!$y=$i++%count($b)][]=$a[$x]+$b[$y];array_pop($r);return$r;}

```

anonymous function takes input as arrays.

**breakdown**

```
while($i<2|$x|$y)   // loop while either $a or $b has NO cut
    $r[
                // if either $a or $b has a cut, increment $k; post-increment $i
        $k+=!($x=$i%count($a))|!$y=$i++%count($b)
                // append current $a + current $b to $r[$k]
    ][]=$a[$x]+$b[$y];
array_pop($r);  // $r has one element too much; remove it
return$r;

```
> 1 votes

# Answer
## Python 3.5, 210 176 173 169 158 Bytes

```
def f(a,b):
 x=[];e=f=0
 while 1:
  if e==len(a):
   print(x);x=[];e=0;
   if f==len(b):break
  if f==len(b):print(x);x=[];f=0
 x+=a[e]+b[f],;e+=1;f+=1

```

**Takes two lists as input and prints all the lists.**

Its my first answer and I don't know how to golf yet. The basic idea I've used is to have two counters for each list which indicate a split and a current list where the added values are appended onto; as soon as a split is encountered, we print the current list and make a new empty one.

* **Saved 34 bytes**: Thanks to Dennis and TimmyD
* **Saved 3 bytes**: was using c and d for len(a) and len(b), but turns out they weren't useful
* **Saved 4 bytes**: Thanks to orlp, removed unwanted paranthesis
* **Saved 11 bytes**: rearranged some blocks and crunched them down
> 1 votes

# Answer
# PowerShell, ~~147~~ 145 bytes

```
param($a,$b)$o=@{};do{$o[+$j]+=,($a[+$i%($x=$a.count)]+$b[$i++%($y=$b.count)]);if(!($i%$x-and$i%$y)){$j++}}until(($x,$y|?{!($i%$_)}).count-eq2)$o

```

Try it online!

(*Golfing suggestions welcome. I feel there's probably another 10 to 15 bytes that can be squeezed out of this.*)

Takes input as two explicit arrays (with the `@(...)` syntax) as command-line arguments. Returns a hashtable of the resulting arrays, because multidimensional arrays in PowerShell can get weird, and this is more consistent. Sets some initial variables, then enters a `do`/`until` loop again, with the conditional being until `$i` is the lcm of the array counts.

Each loop iteration, we add the corresponding `$a` and `$b` values together, treat it as an array `,(...)` before adding it into the hashtable `$o` at the appropriate spot `$j`. The array encapsulation is necessary to prevent arithmetical addition -- this forces the `+=` to overload to array concatenation instead. Then, a conditional on `$x` and `$y` (the counts) to determine if we're at an array edge - if so, we increment `$j`.

Finally, we leave `$o` on the pipeline and output is implicit.
(NB: Due to how PowerShell enumerates hashtables with the default `Write-Output`, this tends to be output "backward"; as in, the "0th" resultant array is on the "bottom" of the output. The hash itself is fine, and would be used just fine if you e.g., encapsulated this code in a return variable ... it just looks odd when it's printed.)

Saved 2 bytes by moving $x and $y into the array indexing rather than separate (saved two semicolons).
> 1 votes

# Answer
# Python 2, 113 bytes

```
a,b=input()
i=m=n=0;r=[]
while(not i)+m+n:r+=[[]]*(not m*n);r[-1]+=[a[m]+b[n]];i+=1;m=i%len(a);n=i%len(b)
print r

```
> 1 votes

# Answer
## Racket 373 bytes

```
(let*((lg length)(fl flatten)(ml make-list)(t rest)(r reverse)(m modulo)(o cons)(ln(lg l))(jn(lg j))(c(lcm ln jn))(l2(fl(ml(/ c ln)l)))
(j2(fl(ml(/ c jn)j)))(ll(for/list((a l2)(b j2))(+ a b))))(let p((ll ll)(ol '())(tl '())(n 0))(cond[(empty? ll)(t(r(o(r tl)ol)))]
[(or(= 0(m n ln))(= 0(m n jn)))(p(t ll)(o(r tl)ol)(take ll 1)(+ 1 n))][(p(t ll)ol(o(first ll)tl)(+ 1 n))])))

```

Ungolfed:

```
(define(f l j)
  (let* ((ln (length l))
         (jn (length j))
         (c (lcm ln jn))
         (l2 (flatten (make-list (/ c ln) l)))
         (j2 (flatten (make-list (/ c jn) j)))
         (ll (for/list ((a l2)(b j2))
               (+ a b))))

    ; TO CUT LIST INTO PARTS:
    (let loop ((ll ll)
               (ol '())
               (templ '())
               (n 0))
      (cond
        [(empty? ll)
         (rest (reverse (cons (reverse templ) ol)))]
        [(or (= 0 (modulo n ln))
             (= 0 (modulo n jn)))
         (loop (rest ll)
               (cons (reverse templ) ol)
               (list (first ll))
               (add1 n))]
        [(loop (rest ll)
               ol
               (cons (first ll) templ)
               (add1 n))]))))

```

Testing:

```
(f '[1]  '[4])
(f '[1 2 -3 -4] '[15])
(f '[0 3 2 2 8 4]  '[7 8 7 2])

```

Output:

```
'((5))
'((16) (17) (12) (11))
'((7 11 9 4) (15 12) (7 5) (9 10 15 6))

```
> 1 votes

# Answer
**Clojure, ~~280~~ 206 bytes**

```
(fn[a b](let[A(count a)B(count b)Q quot](map #(map last %)(partition-by first(take-while #((% 0)2)(map-indexed(fn[i s][[(Q i A)(Q i B)(or(= i 0)(>(mod i A)0)(>(mod i B)0))]s])(map +(cycle a)(cycle b))))))))

```

Well this makes a lot more sense. Generating the element-wise sum, adding positional metadata, taking while we haven't repeated yet and putting the sum value to each partition.

```
(def f (fn[a b]
         (let[A(count a)B(count b)Q quot]
           (->> (map +(cycle a)(cycle b))
                (map-indexed (fn [i s][[(Q i A)(Q i B)(or(= i 0)(>(mod i A)0)(>(mod i B)0))]s]))
                (take-while #((% 0)2))
                (partition-by first)
                (map #(map last %))))))

```

*Original:* I'm hoping to improve this but this is the sortest one I have for now.

```
(fn[a b](let [C cycle o count c(take-while #(or(=(% 0)0)(>(% 1)0)(>(% 2)0))(map-indexed(fn[i[A B]][i(mod i(o a))(mod i(o b))(+ A B)])(map(fn[& v]v)(C a)(C b))))](map #(map last %)(partition-by first(map(fn[p c][p(last c)])(reductions + (map #(if(or(=(% 1)0)(=(% 2)0))1 0)c))c)))))

```

Ungolfed and verbose:

```
(def f (fn[a b]
         (let [c(->> (map (fn[& v]v) (cycle a) (cycle b))
                     (map-indexed (fn[i[A B]][i (mod i(count a)) (mod i(count b)) (+ A B)]))
                     (take-while #(or(=(% 0)0)(>(% 1)0)(>(% 2)0))))]
           (->> (map (fn[p c][p(last c)]) (reductions +(map #(if(or(=(% 1)0)(=(% 2)0))1 0)c)) c)
                (partition-by first)
                (map #(map last %))))))

```

Starts by "merging" an infinite cycle of collections `a` and `b`, adds metadata on each element's index within the collection, takes until both sequences start from index 0 again.

This collection `c` is then merged with partition data (a cumulative sum of ones and zeroes), partitioned and the last element (being sum of items) is selected.

I think for significant improvements a totally different approach is required.
> 1 votes

# Answer
# C++14, 206 bytes

As unnamed generic lambda, requiring input containers `P`,`Q` and output container `R` to be like `vector<vector<int>>`.

```
[](auto P,auto Q,auto&R){R.clear();auto a=P.begin(),b=Q.begin(),x=P.end(),y=Q.end();auto A=a,B=b;do{R.emplace_back();while(a!=x&&b!=y)R.back().push_back(*a+++*b++);a=a==x?A:a;b=b==y?B:b;}while(a!=A||b!=B);}

```

Ungolfed and usage:

```
#include<vector>
#include<iostream>

using namespace std;

auto f=
[](auto P,auto Q,auto&R){
 R.clear();               //just clear the output to be sure
 //a and b are the iterators, x and y is the end
 auto a=P.begin(),b=Q.begin(),x=P.end(),y=Q.end();
 //just some abbreviations for .begin()
 auto A=a,B=b;
 do{
  R.emplace_back();      //add new vector
  while(a!=x&&b!=y)      //while not at the end of one vector
   R.back().push_back(*a+++*b++);  //add the pointed elements and advance
  a=a==x?A:a;            //reset if at the end
  b=b==y?B:b;
 }while(a!=A||b!=B);     //if both were resetted, then finish
}
;

int main(){
 vector<int> A = {0, 3, 2, 2, 8, 4};
 vector<int> B = {7, 8, 7, 2};
 vector<vector<int>> R;
 f(A,B,R);
 for (auto c:R){
  for (int x:c)
   cout << x << ", ";
  cout << endl;
 }
 cout << endl;
}

```
> 0 votes

# Answer
## Mathematica 112 Bytes

This could probably be improved upon. The idea is to create a 2D array with the second element used to track the lessor of the counter i mod the length of each input array.

```
Split[Table[{#[[1,(m=Mod[i,d=Length/@#,1])[[1]]]]+#[[2,m[[2]]]],Min@m},{i,LCM@@d}],#2[[2]]>#1[[2]]&][[;;,;;,1]]&

```

Usage

```
%@{{0,3,2,2,8,4},{7,8,7,2}}

```
> 0 votes

# Answer
## JavaScript (ES6), 131 bytes

```
(a,b,g=(r,[n,...d]=a,[m,...e]=b,s=[])=>1/n?1/m?g(r,d,e,[...s,n+m]):g([...r,s],[n,...d]):1/m?g([...r,s],a,[m,...e]):[...r,s])=>g([])

```

Slightly ungolfed:

```
(a,b,r=[],[n,...d]=a,[m,...e]=b,s=[])
=>1/n?1/m?f(a,b,r,d,e,[...s,n+m])
         :f(a,b,[...r,s],[n,...d],b,[])
     :1/m?f(a,b,[...r,s],a,[m,...e],[])
         :[...r,s]

```
* If both arrays `d` and `e` contain numbers, the sum of the first number is appended to `s` and the remaining elements are processed recursively
* If one of the arrays contains numbers, the array of sums `s` is appended to the result `r` and the other array is reset to its initial array
* If both arrays are empty then simply return the result with the last sums appended.

Sadly this solution doesn't have the ruthless efficiency of @Arnauld's, but at least I think it's a beautiful solution.
> 0 votes

# Answer
# Jelly, 17 bytes

```
Ẉæl/
ẈḍⱮÇ§kṁ€ÇSƊṖ

```

Try it online!

## How it works

```
Ẉæl/ - Helper link. Takes an array [A, B] on the left
Ẉ    - Lengths; [len(A), len(B)]
   / - Reduce by:
 æl  -   LCM
       This yields R := lcm(length(A), length(B))

ẈḍⱮÇ§kṁ€ÇSƊṖ - Main link. Takes [A, B] on the left
Ẉ            - [len(A), len(B)]
   Ç         - Call the helper link on [A, B]
  Ɱ          - Over each integer i = 1, 2, ..., R:
 ḍ           -   Yield [x, y] where:
                   x = 1 if len(A) % i == 0 else 0
                   y = 1 if len(B) % i == 0 else 0
    §        - For each pair, yield 0 if x = y = 0 else a non-zero element
          Ɗ  - To [A, B]:
        Ç    -   Yield R
       €     -   Over each element A, B:
      ṁ      -     Mold to length R
         S   -   Columnwise sums
     k       - Partition this array on the right at the non-zero indexes on the left
           Ṗ - Remove the trailing empty array

```
> 0 votes

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


title: Write A Book Cipher

text:
# Question
Title: Write A Book Cipher
# Introduction

## Book cipher

A Book cipher is a very unique method of a encipher. Here's how's it done:

* You have a book / a document or a article (something full of text, the more pages of text the better).
* You have a message to convey (a secret, of some sort)
* You simply-put read trough the text and the secret message *(may come from input, or reading it from 2 separate files)* \- split it into words *(so, separate spaces, commas and \[dots\])* **so, ',' , '.' and spaces is the only requirement, how is not really that hugely important** and you keep the count of how many words there are in the text, now input the **secret message *(note, the secret's words must be in the text, so if you secret was "My Secret" then, the words "My" and "Secrets" must both exist in the text.***) and output the position of the inputted **secret message**. (E.g if the word "My" was nearly at the first page, maybe the 20th Word in the text, the program should print out '20'. Same with the word "Secrets", if that maybe were later, (let say the 93th word in the text) then your program should print out '93'.

**Note the data type of input and output:**

output numbers: Integers.

Input numbers: Integers

( **Excluding if the secret actually contains a number, then it does not need to be treated as a int. Can be a plus if it does but is not necessary.**)

### Mini Example:

document.txt - file that contains text.

Secret: "My Secret"

(in the text, this is the 20th and the 93th word) (Note, this is only a made up secret, it is not from a real file, or a real input) a more better example is below.

## Program input:

You enter "My Secret"

## Program output:

> 20

> 93

`And, again - you enter those numbers(**Integers**):`

> 20 93

## Program outputs:

> My

> Secret

*this is just to show how input and outputs are related to each other.*

For reference (if needed) You have a Python3 implementation available at my GitHub page, to see a book cipher in action here: GitHub - Book cipher in Py3

* Why is this challenge interesting?

I personally think this is a educational (and interesting) challenge ( one might also exercise, because of how simple it might seem to make, but really took myself - literally **years** to even **know** **how** **to** **implement** this correctly)

Interesting article to get some background of what Cicada3301 is (**not my site**) - https://www.clevcode.org/cicada-3301/

Wikipedia: Cicada3301

I created this challenge both to, see other peoples methods of solving this (you are free to use any programming language!) and also - how long it would take others (For me, really I think it took more than 4 years actually - even in Python3. It looks simple but, for me - *really not*)

* A motivating fact: There are **still** so little info (especially on example codes) on the internet(at least by the time writing this challenge) about just, book cipher ***implementations***

# Challenge

I would highly suggest making dedicated functions for this challenge

* (instead of writing all code in the main() function - but it's totally fine to have it all in main!)

### Operation:

Here's how the program should read, process, and output the result:

First, take the text (the book/document, with the lots of text, (**not the secret**)) and:

**Note: The text can either be entered or read from a file. You choose this.**

1. read it (From a file, or enter it as input)
2. split it into words (by, I.e detecting '.', spaces(' '), and commas ',') (Or if you already have split the input & are ready to move on to step 3, do that :) )
3. count the number of words.

Repeat this process with the Secret input part.

So, the input secret part should be:

* read it (from, again a file or enter it as input)
* split it (i.e if your input was "My Secret" - split it into words like so: "My" "Secret")

### My Python3 implementation only separate spaces.

The Key sequence - this is the n*th* words your text contains, e.g the 93th word in above example "Secrets".

### The winner will be chosen by how short the code is. (So, the shortest code = **win**)

# Example Input and Output

`example file used 'document1.txt'in this section is available at the GitHub page.`  `as well as the Python3 file used in the example below.`

`The output of your program should match the output of the Python3 program.`

# Input:

`python3 bookcipher.py`

> input text: a house with a Bob inside

# Output:

> you entered these words: \['a', 'house', 'with', 'a', 'Bob', 'inside'\]

> 2

> 3

> 5

> 2

> 0

> 30

# Input again: (decrypting)

> input key-sequence sep. With spaces: 2 3 5 2 0 30

> a

> house

> with

> a

> Bob

> inside

# Answer
> 3 votes
# , 112 bytes

```
function(x,t,w=function(x)el(strsplit(x,"[^a-zA-Z]")))`if`(is.integer(x),Reduce(paste,w(t)[x]),match(w(x),w(t)))

```

Try it online!

**Ungolfed code**

```
book_cypher=function(x,t){          # define book_cyper function with args:
                                    # x=either the message (if it's text) or the code (if it's a vector of integers)
                                    # t=the text of the book
  w=function(x){                    # we need to split-up strings into words in 3 places, so we
                                    # define the helper function 'w' to do this:
    el(                             #   get the first 'el'ement of
       strsplit(x,"[^a-zA-Z]"))     #   splitting the argument on any character except a-z and A-Z
                                    #   (note that with the clarified challenge rules we can also do this with [., ]
                                    #   to split only on dots, commas & spaces)
  }                                 #
                                    # now the main function body:
  if(is.integer(x)){                # if the agument is of type 'integer' we need to decode:
    Reduce(paste,w(t)[x])           #   split the text using helper function 'w',
                                    #   and select the elements at indices given by the argument
                                    #   ('Reduce(paste())' is just a golfy way of joining the elements
                                    #   back together into a space-separated string)
  } else {                          # otherwise, we need to encode:
    match(w(x),w(t)))               #   split the message and the text using helper function 'w',
                                    #   and use 'match' to find the indices of the elements of the split text
                                    #   that match each element of the split message.
  }
}

```

# Answer
> 3 votes
# Jelly, 36 (14?) bytes

**36 bytes** if we must write a program/function which encodes if given a string and decodes if given a list of integers:

```
Ñi@€Ñ}
“. , ”yḲ¹Ƈ
ị€Ç}K
⁸ŒṘ€FḊm3$⁼¤ŀ

```

A full program accepting two arguments:

* the message string or list of integers; and
* the book text.

which prints either a list of integers (when given a message string) or the decrypted message (if given a list of integers).

**Try it online!**

---

**14 bytes** if we *only* need to write an encoder:

```
“. , ”yḲ¹Ƈ)iⱮ/

```

A dyadic Link accepting a list `[message, book_text]` which yields a list of integers.

**Try it online!**

# Answer
> 3 votes
# Husk, 32 bytes

```
?ö;msm€₁⁰₁ö;m!₁⁰mrwo√←²
wm(?c' √

```

Try it online!

If input is a string of letters/words: encodes to string of integers:
input: `"this is my secret message"`+book, output: `"1 5 7 12 9"`

If input is a string of integers: decodes to string of words:
input: `"1 5 7 12 9"`+book, output `"this is my secret message"` (try it)

---

Encoder (15 bytes) and Decoder (15 bytes) would total 30 bytes as separate programs (with 9 bytes of shared code).

# Answer
> 1 votes
# , 23 bytes

```
(i.~cut@rplc&', . ')~;:

```

Try it online!

This takes the document text as the left argument and the string of words as the right argument.

The main verb:

* `;:` Chops the secret string into boxed words
* `rplc&', . '` Replaces commas and periods with space.
* `cut` Cuts the remaining text on spaces into a boxed list of words.
* `i.~` Finds the index of each input word within that list.

# Answer
> 1 votes
# C (gcc), ~~154~~ 147 bytes

Thanks to ceilingcat for the -7.

I'm assuming from the challenge that I can have a pre-split array of secret words and that the indexes must be 1-based.

Takes an array of the word list and a string which contains one or more 1-based indexes or words, and returns the inverse of each word/index. These may be mixed: for example, if `my test` returns `5 10`, then `my 10` returns `5 test`. The words are case-sensitive.

How it works:

```
f(char **a, char *s) {
  int i,t,v;
  char *u;

  for(
    t=NULL; // initialize the tokenizer
    t=strtok(t?NULL:u=strdup(s),"., "); // tokenize the input on first call
    printf(v?"%s ":"%d ",v?:i+1)) // print either string or index
      for(
        v=(i=atoi(t))?a[i-1]:(i=0); // integer or string?
        !v*a[i]&&strcmp(t,a[i]); // if string, search for match
        i++);
}

```

```
i,t,v;f(a,s)int*a;{for(t=0;t=strtok(t?0:strdup(s),"., ");printf(v?"%s ":"%d ",v?:i+1))for(v=(i=atoi(t))?a[i-1]:(i=0);!v*a[i]&&strcmp(t,a[i]);i++);}

```

Try it online!

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


title: Verify the inequality!

text:
# Question
Title: Verify the inequality!
Left in sandbox for at least 3 days.

I want to verify if this inequality is true:

for \\$n\geq4\\$, if \\$a\_1,a\_2,a\_3,\dots,a\_n\in R\_+\cup\\{0\\}\\$ and \\$\sum\_{i=1}^na\_i=1\\$, then \\$a\_1a\_2+a\_2a\_3+a\_3a\_4+\dots+a\_{n-1}a\_n+a\_na\_1\leq\frac{1}{4}\\$.

## Challenge

Write a piece of program which takes an integer `n` as input. It does the following:

1. Generate a random array `a` which consists of `n` non-negative reals. The sum of all elements should be 1.

> By saying *random*, I mean, every array satisfiying the requirements in 2 should have a non-zero probability of occurrence. It don't need to be uniform. See this related post.

2. Calculate `a[0]a[1]+a[1]a[2]+a[2]a[3]+...+a[n-2]a[n-1]+a[n-1]a[0]`.
3. Output the sum and the array `a`.

> For I/O forms see this post.

## Rules

(Sorry for the late edit...) All numbers should be rounded to **at least** \\$10^{-4}\\$.

Standard loopholes should be forbidden.

## Example

The following code is an ungolfed Python code for this challenge, using library `numpy`. (For discussion about using libraries, see This Link.)

```
import numpy as np

def inequality(n):
    if n < 4:
       raise Exception
    a = np.random.rand(n)
    sum_a = 0
    for i in range(n):
        sum_a += a[i]
    for i in range(n):
        a[i] /= sum_a
    sum_prod = 0
    for i in range(n):
       sum_prod += a[i % n] * a[(i + 1) % n]
    print(a)
    return sum_prod, a

```

## Tip

You could assume that input `n` is a positive integer greater than 3.

---

Your score is the *bytes* in your code. The one with the least score wins.

# Answer
# APL(Dyalog Unicode), 21 bytes SBCS

```
(+/⊢×1∘⌽)⎕←(⊢÷+/)?⎕⍴0

```

Try it on APLgolf!

A tradfn submission which prints the list and returns the sum.

```
                  ⎕⍴0 ⍝ create a vector with input-many 0's
                 ?    ⍝ for each 0, get a random number between 0 and 1
            ⊢÷        ⍝ divide each number by
              +/      ⍝ the sum of all numbers
         ⎕←           ⍝ print the resulting vector
   ⊢×                 ⍝ multiply the vector element-wise
     1∘⌽              ⍝ with the vector rotated to the left by 1
 +/                   ⍝ take the sum of all products

```

If appending the sum to the list is fine as output, this could be 20 bytes: `x,+/x×1⌽x←(⊢÷+/)?⎕⍴0`
> 4 votes

# Answer
# , ~~49~~ 45 bytes

```
a=rexp(scan());a=a/sum(a);a;a%*%c(a[-1],a[1])

```

Try it online!

-4 bytes by Robin Ryder
> 4 votes

# Answer
# JavaScript (ES6),  ~~89~~  88 bytes

Returns `[ array, sum ]`.

```
f=(n,a=[],t=s=0)=>n?f(n-1,[...a,v=Math.random()],t+v):[a.map(k=>(s+=v/t*(v=k),v/t)),s/t]

```

Try it online!

### Commented

```
f = (                      // f is a recursive function taking:
  n,                       //   n = input
  a = [],                  //   a[] = array
  t =                      //   t = sum of non-normalized values
  s = 0                    //   s = sum of a[i] * a[(i + 1) mod n] / t
) =>                       //
n ?                        // if n is not equal to 0:
  f(                       //   do a recursive call:
    n - 1,                 //     decrement n
    [ ...a,                //     pass a new array with all previous elements of a[]
      v = Math.random() ], //     followed by a new random value v in [0,1)
    t + v                  //     add v to t
  )                        //   end of recursive call
:                          // else:
  [                        //   build the answer array:
    a.map(k =>             //     for each value k in a[]:
      ( s +=               //       add to s:
          v / t            //         the previous normalized value v / t,
          * (v = k),       //         multiplied by k (and update v to k)
        v / t              //       yield the normalized value
      )                    //
    ),                     //     end of map()
    s / t                  //     also return the normalized sum
  ]                        //   end of answer array

```
> 2 votes

# Answer
# Julia, 46 bytes

```
n->(a=rand(n);a/=sum(a))=>a[2:end]'*a[1:end-1]

```

Try it online!

returns `array => sum`
> 2 votes

# Answer
# Wolfram Language (Mathematica), 42 bytes

```
{##2,#}&@@#.#|#&[#/Tr@#&@RandomReal[1,#]]&

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~17~~ ~~15~~ ~~14~~ 17 bytes

```
₄Ý.rI£DO/ÐÀ*O‚

```

Outputs as a pair `[array, sum]`.

-2 bytes thanks to *@Neil*.
-1 byte by changing two explicit prints with enclose/overlap builtins `=Ćü*O,` to something similar as my MathGolf answer with pair and implicit print `ÐÀ*O‚`
+2 bytes so duplicated items are possible and +1 byte to maximize the amount of floats possible

Try it online (but uses `[0,1000]` instead of `[0,9876543210]` to speed things up a bit).

**Explanation:**

```
žmÝ               # Push a list in the range [0,9876543210]
   Iи             # Repeat it the input amount of times
                  # (so we can potentially get duplicated items)
     .r           # Randomly shuffle this list
       I£         # Only leave the first input amount of values
         D        # Duplicate this list
          O       # Sum them together
           /      # Divide all values by this sum
                  # (so we now have a list of random values summing to 1)
            Ð     # Triplicate this list
             À    # Rotate the top copy once towards the left
              *   # Multiply the top two lists position-wise together
               O  # Sum this list
                ‚ # Pair the list together with this sum
                  # (after which this pair is output implicitly as result)

```
> 1 votes

# Answer
# , 30 27 25 bytes

-2 to thanks to ovs's rotate idea

```
[:(;1#.]*1|.])@(%+/)?@$&0

```

Try it online!

* `$&0` Duplicate 0 "input" times.
* `?@` And "roll" for each (`?0` produces a random number between 0 and 1).
* `[:...(%+/)` Divide each by sum of all.
* `(;1#.]*1|.])` To that boxed list append `;` the sum of `1#.` the list `]` times `*` the list rotated once to the left `1|.]`.
> 1 votes

# Answer
# Charcoal, 25 bytes

```
ＦＮ⊞υ‽φ≧∕Συυ⊞υΣＥυ×ι§υ⊕κＩ⮌υ

```

Try it online! Like the 05AB1E answer, I generate `n` random numbers between `0` and `999`, then scale them so their sum is 1. A larger range could be obtained at the cost of one or two bytes. Also, it's unclear whether the sum has to be first; printing it last would save two bytes. Explanation:

```
ＦＮ

```

Repeat `n` times...

```
⊞υ‽φ

```

... push a random integer to the predefined empty list.

```
≧∕Συυ

```

Divide the list by its sum.

```
⊞υΣＥυ×ι§υ⊕κ

```

Multiply each element by its neighbour and push the sum to the list.

```
Ｉ⮌υ

```

Print the list in reverse so that the sum is first.
> 1 votes

# Answer
# MathGolf, 11 bytes

```
Äƒ]_Σ/∙╫m*Σ

```

Outputs the array and sum concatenated to one another.

Try it online.

**Explanation:**

```
Ä            # Loop the (implicit) input amount of times,
             # using a single character as inner code-block:
 ƒ           #  Push a random float in the range [0,1]
  ]          # Wrap all values on the stack into a list
   _         # Duplicate this list
    Σ        # Take the sum of it
     /       # Divide all values in the list by this sum
             # (so we now have a list of random values summing to 1)
      ∙      # Triplicate this list
       ╫     # Rotate the top copy once towards the left
        m*   # Multiply the top two lists position-wise together
          Σ  # Take the sum of that list
             # (after which the entire stack joined together is output implicitly)

```
> 1 votes

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

Saved a byte thanks to Kevin Cruijssen!!!
Saved 3 bytes thanks to Danis!!!

```
def f(n):l=[random()for i in[0]*n];l=[e/sum(l)for e in l];return l,sum(a*b for a,b in zip(l,l[1:]+l))
from random import*

```

Try it online!
> 1 votes

# Answer
# Python 3 \+ numpy, 75 bytes

```
from numpy import*
def f(n):x=random.rand(n);x/=sum(x);return x,x@roll(x,1)

```

Try it online!
> 1 votes

# Answer
# MATL, 13 bytes

```
l&rts/ttlYS*s

```

Try it online!

**Explanation**

```
             % Implicitly retrieve input (N) as an integer
l            % Push the literal 1 to the stack
&r           % Create an N x 1 array of random floats
t            % Duplicate this array
s            % Sum the elements of this array
/            % And perform element-wise division of the original array by this sum
             % to get the array, A
tt           % Duplicate A (twice)
lYS          % Circularly shift A by 1 element
*            % Perform element-wise multiplication with A
s            % Compute the sum
             % Implicitly display A and the sum of the products

```
> 1 votes

# Answer
# Ruby, ~~83 82 72~~ 71 bytes

```
->n{k=(1..n).map{rand};p=k[~-s=0]/z=k.sum;[k.map{|x|s+=p*x/z;p=x/z},s]}

```

Try it online!

-4,-1,-6 from ASCII-only!

-4, shortening it further.

-1 more byte from ASCII-only.
> 1 votes

# Answer
# Jelly, 18 bytes

No built-in for random floats, so half the code is that!

```
2ṗ⁹XHCḅ.)÷S$µṙ1ḋƊ,

```

A monadic Link accepting an integer, `n`, which yields a list containing a non-negative float (the sum of products) and the generated list of non-negative floats of length `n` which sums to `1`.

**Try it online!** (Note that  (\\$256\\$) has been replaced with `9` (\\$9\\$) for speed - generating all \\$2^{256}\\$ lists of bits would take a while. Using a number as big as \\$256\\$ is not necessary, it's just terse.)

### How?

(Bug fixed above, will update this section later.)

Note: Uses 256 random bits to generate a random float in \\$\[0,1\]\\$.

```
2ṗ⁹XHCḅ.)µ÷Sṙ1ḋƊ, - Link: n
         )        - for each:
2                 -   2
  ⁹               -   256
 ṗ                -   (256) Cartesian product (2 implicitly -> [1,2])
   X              -   pick one at random        e.g.  [1,2,2,1, ... ,1,2]
    H             -   halve                           [0.5,1,1,0.5, ... ,0.5,1]
     C            -   complement                      [0.5,0,0,0.5, ... ,0.5,0]
       .          -   a half                          0.5
      ḅ           -   convert (list) from base (0.5)  a float in [0,1]
         µ        - start a new monadic chain         (call that x)
           S      - sum                               sum(x)
          ÷       - divide                            normalised(x)
               Ɗ  - last three links as a monad:      (call that Y=[y1,y2,...,yn])
                  -   one                             1
            ṙ     -   rotate left by (1)              [y2,...,yn,y1]
              ḋ   -   dot product (with Y)            y1.y2+y2.y3+...+yn.y1
                , - pair                              [y1.y2+y2.y3+...+yn.y1, Y]

```
> 0 votes

---
Tags: code-golf, math, arithmetic, random
---