title: Minecraft Mirrored

text:
# Question
Title: Minecraft Mirrored
*This is Calvin. Just trying to get 20 rep so this user can chat in the PPCG Minecraft Server chatroom.*

Write a program or function that takes in a positive integer.

If the integer is even (2, 4, 6, ...), print or return this exact ASCII art string:

```
                       __    __   __             __  ___
  /\  /\    |  |\  |  |     /    |  |     /\    |     |
 /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   |
/        \  |  |  \|  |__   \__  |   \  /    \  |     |

```

If the integer is odd (1, 3, 5, ...), print or return this exact ASCII art string:

```
                       __    __
\        /  |  |  /|  |     /    |   /  \ __ /  |     |
 \  /\  /   |  | / |  |--  |     |--/    \  /   |--   |
  \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_

```

You may assume the input is always a positive integer.

In both output cases there may optionally be any number of trailing spaces up to the right edge of the "T" on each line, and/or a single trailing newline. Note how there are two columns of spaces between each letter.

**The shortest code in bytes wins.**

# Answer
# JavaScript (ES6), ~~343~~ ~~336~~ ~~289~~ ~~267~~ ~~265~~ 260 bytes

Just for fun... :) (Thanks to Xufox for cutting off 46 bytes, and encouraging me to cut off another 37 on my own.)

```
n=>`887141${n%2?`
98/202/05/4|3/29 1 /2|5|
 92/92/30 / 0--2|5|--/492/3|--3|
29/29/40/2013912|1|59/4|12_|_`:`3185121_
2/92/9409205/405/94|5|
 /29/2930 9 0--2|5|--94/193|--3|
/892029013912|392/492|5|`}`.replace(/\d/g,x=>+x?x<2?'__':x<9?' '.repeat(x):'\\':'|  |')

```

Called as `a(4)` or similar. Try it here:

```
a=n=>`887141${n%2?`
98/202/05/4|3/29 1 /2|5|
 92/92/30 / 0--2|5|--/492/3|--3|
29/29/40/2013912|1|59/4|12_|_`:`3185121_
2/92/9409205/405/94|5|
 /29/2930 9 0--2|5|--94/193|--3|
/892029013912|392/492|5|`}`.replace(/\d/g,x=>+x?x<2?'__':x<9?' '.repeat(x):'\\':'|  |')
document.getElementById("a").innerHTML = "<pre>"+a(2)+"</pre>";
document.getElementById("b").innerHTML = "<pre>"+a(3)+"</pre>";
```

```
<p id="a"></p>
<p id="b"></p>
```

I've condensed the whitespace into strings of digits from `2` to `8` (e.g. `887` = 23 spaces). Each digit is then replaced with the corresponding number of spaces. `0` represents `| |`, and `1` represents `__`. All in all, this program is 170 bytes shorter than the two strings combined (203 + 227 = 430), so I'm happy. :)

**Edit:** Somehow, it's exactly the same length as the only other entry at this point.... o\_o

**Edit 2:** Saved some space by changing `n%2<1?` to `n%2?` and swapping the strings. Also took advantage of the fact that the beginnings of the two strings are the same to reduce another 5 bytes.

**Edit 3:** `|2|` seemed to show up an awful lot, so simplified each occurence to `x`, saving 7 bytes. Xufox's suggestions cut off another 40 bytes.

**Edit 4:** Xufox's suggestion to replace `\n` with actual line breaks paid off, removing 6 bytes from the total. Changing `x` to `0` and `__` to `1` (insert evil laugh here), then combining all of the (insert plural of Regex here), as he did in his entry, saved an extra 16 bytes.

**Edit 5:** Since I've chosen to use the ES6 standards, I used custom template string interpolation to shave off 2 final bytes.
> 24 votes

# Answer
## Matlab, ~~343~~ 341

```
a=' -/\_|';
if mod(input(''),2)
x='003C00E00E000L0005N5000I000005550I0000I0055N4UVYO26R4004400400U005300UUXO060O060003C00C30CO00IO00UUUS060S5B54000';else
x='0I2000L0000L000E05H50C0000000555000C00C00H554UVYO26R4004400400U000250WUU006O006O0I2002I00O0I0O0C0UUU006S05BT0004';end
disp(a(reshape(dec2base(base2dec(reshape(x,[],7),36),6),4,[])-47))

```

The input number is provided from stdin.

Sample run:

```
>> a=' -/\_|';
if mod(input(''),2)
x='003C00E00E000L0005N5000I000005550I0000I0055N4UVYO26R4004400400U005300UUXO060O060003C00C30CO00IO00UUUS060S5B54000';else
x='0I2000L0000L000E05H50C0000000555000C00C00H554UVYO26R4004400400U000250WUU006O006O0I2002I00O0I0O0C0UUU006S05BT0004';end
disp(a(reshape(dec2base(base2dec(reshape(x,[],7),36),6),4,[])-47))
1
                       __    __   __             __  ___
  /\  /\    |  |\  |  |     /    |  |     /\    |     |
 /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   |
/        \  |  |  \|  |__   \__  |   \  /    \  |     |

```
> 12 votes

# Answer
# CJam, ~~158~~ ~~149~~ ~~145~~ 138 bytes

```
li2%"A+×rµ^ÅÆÿ»£ºoU#ü T^U^ÝZe<ÄÊKÞÒ£^ÛWWø5Úí§¹T^Úêer^^°^Ã}Ã^A0R2"281b7b"/
 -_\|"f=N/S3**_"_ ":T/TW%*4/zW%1m>N*1>"\/"_W%er"^W^]5OU"{i_32>T=t}/\4/zN*?

```

The above uses caret notation, since the code contains unprintable characters.

Try it online in the CJam interpreter.

If the permalink doesn't work in your browser, you can copy the code from this paste.

### Example run

```
$ LANG=en_US
$ xxd -ps -r > minecraft.cjam <<< 6c69322522412bd772b585c6ffbba3ba6f5523fc2054159d5a653cc4ca4bded2a39b5757f835daeda7b9549aea65721eb0837dc30130523222323831623762222f0a202d5f5c7c22663d4e2f53332a2a5f225f20223a542f5457252a342f7a5725316d3e4e2a313e225c2f225f5725657222171d354f55227b695f33323e543d747d2f5c342f7a4e2a3f
$ cjam minecraft.cjam <<< 2; echo
                       __    __   __             __  ___
  /\  /\    |  |\  |  |     /    |  |     /\    |     |
 /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   |
/        \  |  |  \|  |__   \__  |   \  /    \  |     |
$ cjam minecraft.cjam <<< 1; echo
                       __    __
\        /  |  |  /|  |     /    |   /  \ __ /  |     |
 \  /\  /   |  | / |  |--  |     |--/    \  /   |--   |
  \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_

```

### Idea

Instead of encoding the MINECRAFT string (padded to achieve a constant line length) directly, we'll encode a "zipped" version of it, where rows and columns have been transposed.

After zipping and removing the linefeeds, this string (let's call it **R**) has to be encoded:

```
   /  /  /   \    \   /  /   \    \    \         |||         ||| \    \    \ |||         |||_ -__ -_          |  / \_  __  _         |||_ - _ -  |\    \           /  /  /_  \_   \    \         |||_ - _ -         _   _|||_

```

There are many runs of spaces, so we'll replace each occurrence of a space triplet with a linefeed.

This leaves us with seven different characters (`\n -/\_|`), so we assign each of them a number from **0** to **6** and consider the resulting array digits of a base 7 number, which we then encode as a byte string.

Decoding works by reversing the steps from above.

The mirrored string can be constructed from the original one.

If we reverse the order of the four rows and swap the soliduses, we obtain the following:

```
\        /  |  |  /|  |__   /__  |   /  \    /  |     |
 \  /\  /   |  | / |  |--  |     |--/    \__/   |--   |
  \/  \/    |  |/  |  |     \    |  |     \/    |     |
                       __    __   __             __  ___

```

Somehow similar, but we'll clearly have to rotate the rows to bring the bottom row to the top:

```
                       __    __   __             __  ___
\        /  |  |  /|  |__   /__  |   /  \    /  |     |
 \  /\  /   |  | / |  |--  |     |--/    \__/   |--   |
  \/  \/    |  |/  |  |     \    |  |     \/    |     |

```

That would be it if it wasn't for those pesky underscores.

If we read the original string from top to bottom and ignore linefeeds (thus obtaining **R**) and replace each underscore followed by space with a space followed by an underscore before shifting the rows, this is the result:

```
                         _     _                      _
\        /  |  |  /|  |_    /_   |   /  \ __ /  |     |
 \  /\  /   |  | / |  |--  |     |--/    \  /   |--   |
  \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_

```

Much better! All that's left to do is deleting the first space of the first row (shifting all underscores in the first row one character left), moving the misplaced underscores in **E** and **C** one row up and discarding the underscore over **T**.

### Code

```
li2%           e# Read an integer from STDIN and push its parity.

"A+×rµ^ÅÆÿ»£ºoU#ü T^U^ÝZe<ÄÊKÞÒ£^ÛWWø5Úí§¹T^Úêer^^°^Ã}Ã^A0R2"

281b7b         e# Convert the byte string from base 281 to base 7.
"/\n -_\\|"f=  e# Replace each digit by its corresponding character.
N/S3**         e# Turn linefeeds into three spaces.
_              e# Copy the resulting string.
"_ ":T         e# Define T.
/TW%*          e# Replace occurrences of T with T reversed.
4/z            e# Split into chunks of length 4 and zip.
W%1m>          e# Reverse and rotate the rows.
N*             e# Join the rows, separating by linefeeds.
1>             e# Discard the first character.
"\/"_W%er      e# Swap the soliduses.
"^W^]5OU"      e# Push the string that corresponds to [23 29 53 79 85].
{              e# For each character:
  i            e#   Push its code point.
   _32>        e#   Push 1 iff the code point is larger than 32.
       T=      e#   Select the element at that index from T = "_ ".
         t     e#   Replace the element at the code point's index with that char.
}/             e#
\              e# Swap the partially generated MINECARFT string on top.
4/z            e# Split into chunks of length 4 and zip.
N*             e# Join the rows, separating by linefeeds.
?              e# Select the first string iff the input was odd.

```
> 11 votes

# Answer
# Pyth - 182 bytes

Uses base encoding approach. Since indexing is modular in Pyth, I don't even have to do anything for the even odd, just put it in the correct order, and use `@Q`. As a bonus this also works with negative numbers.

```
@mjbcs@L"_| /\\-"jCd6 56,"EWbòH\x00B)þKÙ£ÄIOõìæ«FFãbÐÄBØ\«¼,vã<RN>º:w÷ò¾<éifP9e|ÉWf!FÔèà""EWbòH\x00B)þOHÿ$@ËþçX'D[¾«Â?°´=&£üá ¹»ázH×Æz3äkÕg{`!|ðY!ðGV"Q

```

I had tries only encoding the first one, then flipping and switching the slashes, but the first and last line were too hard.

I could save 6 bytes by putting actual null bytes in the code, but that's too much trouble.

Try it online here.

It looks really bad online because the output box is too small and wraps. I recommend fiddling with the dev-console and changing the `col-md-5` to a `col-md-7`.
> 10 votes

# Answer
# JavaScript (ES6), ~~312~~, ~~285~~, ~~281~~, ~~272~~, ~~270~~, ~~263~~, ~~262~~, 260

*For previous edits see the edit history.*

**Edit 5:** In the conversion, I switched the number associated with `-` (now 0) and whitespace (now 1). In the resulting block, the numbers 1, 2 and 3 weren’t used as much anymore. This allowed me to use an array with the missing numbers.

**Edit 6:** Improved the array literal. I tried this previously, but used `777` and `77` as strings instead of numbers and noticed only now that I had missed this.

**Edit 7:** The “Golfed code” is a function, as specified by the question and there’s no need for `f=` to meet this specification. Thus, removing it, saving two bytes.

---

Runnable in Firefox 39:

```
// Testing:

f=

// Golfed code:

n=>[...`11111113ss17ss1pp11117pp3ppp
97dj3dj7822j78z213e17z3v8397gm78212
7f3kf3k1z27k7z20021200k17fppk1z001z
d7983987j2287jz2ss1lss2aabj3d7987j2aa3aza`.replace(/[123]/g,x=>[,777,'77z',77][x])].map(a=>isNaN(i=parseInt(a,36))?a:'- /\\_|'[n%2?i%6:~~(i/6)]).join``

// Testing:

;document.body.appendChild(document.createElement('pre')).innerHTML=f(0);
document.body.appendChild(document.createElement('pre')).innerHTML=f(1);
document.body.appendChild(document.createElement('pre')).innerHTML=f(2);
document.body.appendChild(document.createElement('pre')).innerHTML=f(35);
```

It’s based on the base 6 number system and each ASCII character stands for a number:

```
"-": 0
" ": 1
"/": 2
"\": 3
"_": 4
"|": 5

```

Then, I’ve combined the number representation of each ASCII string. For example: when the first ASCII string contains a `/` at one position and the *other one* contains a `\` at *the same position*, that position becomes `32`, which is base 6 (`20` in decimal). If you convert this to base 36 (to get *one* base-36 number for every *two* base-6 numbers), you get `k`.

All this was done beforehand and the function basically undoes this process.

~~Now the two JavaScript answers both have one other answer each, that has the same byte count…~~

---

PS: As a note to myself and a reference to others, this is the code I used:

```
// 1. ASCII here
a=`|\\-/ _`;

// 2. ASCII here
b=`/|\\_ -`;

// Note: the ASCII strings’ backslashes have to be escaped!

[...a]
  .map((c,i)=>parseInt((c+b[i])
    .replace(/-/g,'0')
    .replace(/ /g,'1')
    .replace(/\//g,'2')
    .replace(/\\/g,'3')
    .replace(/_/g,'4')
    .replace(/\|/g,'5'),6))
  .map(c=>isNaN(c)
    ?`
`
    :c.toString(36))
  .join``
// Returns "wn3g7o", which is then put into the function as the block at the top.

```
> 9 votes

# Answer
# CJam, 136 bytes

```
"^ASÓ8¥È÷^K¯¾/^HÕ2^ÄË1jÒÝ^D^Á0îl;)HR§û|^Ê^Þ^ÇÝÅ^ßNlz^TfÑ^Øj>À^Ã 4#bH\¿^Äî·íì^E^A~(¿ø³(ú´,^È(¡j>è?#'»vçPïju87)×"
265b8b[S9*'|3*+S2*]"/-_\| "+f=s4/56/ri=zN*

```

The above uses caret notation, since the code contains unprintable characters.

The linefeed is solely for "readability". Try it online in the CJam interpreter.

If the permalink doesn't work in your browser, you can copy the code from this paste.

### Example run

```
$ LANG=en_US
$ xxd -ps -r > minecraft.cjam <<< 220153d338a5c8f70bafbe2f08d53284cb316ad2dd048130ee6c3b294852a7fb7c8a9e87ddc59f4e6c7a1466d1986a3ec08320342362485cbf84eeb7edec05017e28bff8b328fab42c8828a16a3ee83f2327bb76e750ef6a75383729d7223236356238625b53392a277c332a2b53322a5d222f2d5f5c7c20222b663d73342f35362f72693d7a4e2a
$ cjam minecraft.cjam <<< 2; echo
                       __    __   __             __  ___
  /\  /\    |  |\  |  |     /    |  |     /\    |     |
 /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   |
/        \  |  |  \|  |__   \__  |   \  /    \  |     |
$ cjam minecraft.cjam <<< 1; echo
                       __    __
\        /  |  |  /|  |     /    |   /  \ __ /  |     |
 \  /\  /   |  | / |  |--  |     |--/    \  /   |--   |
  \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_

```

### Idea

This approach has some similarities to the one in my other answer, but it is a lot simpler and (rather disappointingly) a bit shorter.

We search for a way to encode the following string:

```
                       __    __   __             __  ___                       __    __
  /\  /\    |  |\  |  |     /    |  |     /\    |     | \        /  |  |  /|  |     /    |   /  \ __ /  |     |
 /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   |  \  /\  /   |  | / |  |--  |     |--/    \  /   |--   |
/        \  |  |  \|  |__   \__  |   \  /    \  |     |   \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_

```

After padding each row (to achieve a constant line length), zipping (transposing rows and columns) and removing the linefeeds, this string has to be encoded:

```
   /  /  /   \    \   /  /   \    \    \         |||         ||| \    \    \ |||         |||_ -__ -_          |  / \_  __  _         |||_ - _ -  |\    \           /  /  /_  \_   \    \         |||_ - _ -         _   _|||_    \    \    \   /  /   \    \   /  /  /           |||         |||   /  /  /   |||         |||_ -__ -_          |  / \_  __  _         |||  -_  -_  /| /           \    \  _ \ _ /  /  /           |||  -_  -_           _ |||   _

```

We'll replace each substring `" |||"` with a **0**, each substring `" "` with a **1** and the characters of `"/-_\| "` with **2** to **7**, forming an array of base 8 digits, which can be encoded as a byte string.

Decoding works by reversing the steps from above.

### Code

```
"^ASÓ8¥È÷^K¯¾/^HÕ2^ÄË1jÒÝ^D^Á0îl;)HR§û|^Ê^Þ^ÇÝÅ^ßNlz^TfÑ^Øj>À^Ã 4#bH\¿^Äî·íì^E^A~(¿ø³(ú´,^È(¡j>è?#'»vçPïju87)×"

265b8b        e# Convert from base 265 to base 8.
[S9*'|3*+S2*] e# Push ["         |||" "  "].
"/-_\| "+     e# Concatenate to push ["         |||" "  " '/' '-' '_' '\' '|' ' '].
f=            e# Select the elements that correspond to the base 8 digits.
s4/           e# Flatten and chop into chunks of length 4 (columns).
56/           e# Chop into two subarrays of 56 columns.
ri            e# Read an integer from STDIN.
=             e# Select the corresponding subarray.
              e# Arrays wrap around, so [A B]0= eq. [A B]2= and [A B]1= eq. [A B]3=.
zN*           e# Zip and join the rows, separating by linefeeds.

```
> 6 votes

# Answer
# Racket, ~~443~~ ~~434~~ 386 Bytes

```
(require file/gunzip net/base64)(define(f n)(define o(open-output-bytes))(gunzip-through-ports(open-input-bytes(base64-decode #"H4sIAK8Lt1UAA22Q3Q3AIAiE352CBcwtRHLpHg7f8lubahRUDuVD5DjItrH9REgOEWgskfVMDeca1GWcSmN2WFBtlUTdzdmSOT0BpEpGnjxUAf2RmvPq1OyKGF6N5V1nvgYcWjeod/Hj8JotBRtH0qM48OeoWrBxJH23KL/dOMh4IDXe8MUbT1AqtKkBAAA="))o)(list-ref(string-split(get-output-string o)"a")(modulo n 2)))

```

Just for kicks.

```
(require file/gunzip net/base64)
(define (f n)
  (define o (open-output-bytes))
  (gunzip-through-ports
   (open-input-bytes
    (base64-decode #"H4sIAK8Lt1UAA22Q3Q3AIAiE352CBcwtRHLpHg7f8lubahRUDuVD5DjItrH9REgOEWgskfVMDeca1GWcSmN2WFBtlUTdzdmSOT0BpEpGnjxUAf2RmvPq1OyKGF6N5V1nvgYcWjeod/Hj8JotBRtH0qM48OeoWrBxJH23KL/dOMh4IDXe8MUbT1AqtKkBAAA="))
   o)
  (list-ref (string-split (get-output-string o) "a") (modulo n 2)))

```

N.B. you may need the `#lang racket` line to run in DrRacket.
> 4 votes

# Answer
# 05AB1E, ~~179~~ ~~177~~ 176 bytes

```
"
 -/\_|"•ÿ%Ò´Åçδ’Üå·Äm…½µƵδø5)ǝ®∊∊Ý®þCĀ₆áÝoþ²ši¤Æ%ßû¤%¦Ï≠θĀ5¾₃ʒŸQ>Šn°η8±8d¸6':…é’b…÷‡ö©«&‡huÑ¦%λÁZÊJÌ₅ú∞°»ó₄ι«ÓW´×ƒ×ùqiò2D1āwθóÆË²’
Tι#и∊²ý‚KʒFæΩZºÿÏ";ηiʒæøвøïž‚è°ć½∊•7вèJ2äIè

```

Try it online.

**Explanation:**

```
•ÿ%Ò´Åçδ’Üå·Äm…½µƵδø5)ǝ®∊∊Ý®þCĀ₆áÝoþ²ši¤Æ%ßû¤%¦Ï≠θĀ5¾₃ʒŸQ>Šn°η8±8d¸6':…é’b…÷‡ö©«&‡huÑ¦%λÁZÊJÌ₅ú∞°»ó₄ι«ÓW´×ƒ×ùqiò2D1āwθóÆË²’
Tι#и∊²ý‚KʒFæΩZºÿÏ";ηiʒæøвøïž‚è°ć½∊•

```

is the compressed number:

```
669530978249988431396781816197276307266403407188962925862194299697873953319419752813246251351417090709766331736351616127424760949905163941809417778114834562736028512279028673309866195447599979612590918985644583407413903825059942009898007791080822453262749380245316127735585410697701790387188175543639634091138422651942833048832372950797322005040161476426127678479662921265139425

```

Try it online.

converts it to Base-7 as list, so we get the list of digits:

```
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,5,5,1,1,1,1,5,5,1,1,1,5,5,1,1,1,1,1,1,1,1,1,1,1,1,1,5,5,1,1,5,5,5,0,1,1,3,4,1,1,3,4,1,1,1,1,6,1,1,6,4,1,1,6,1,1,6,1,1,1,1,1,3,1,1,1,1,6,1,1,6,1,1,1,1,1,3,4,1,1,1,1,6,1,1,1,1,1,6,0,1,3,1,1,4,3,1,1,4,1,1,1,6,1,1,6,1,4,1,6,1,1,6,2,2,1,1,6,1,1,1,1,1,6,2,2,4,1,1,1,1,3,5,5,4,1,1,1,6,2,2,1,1,1,6,0,3,1,1,1,1,1,1,1,1,4,1,1,6,1,1,6,1,1,4,6,1,1,6,5,5,1,1,1,4,5,5,1,1,6,1,1,1,4,1,1,3,1,1,1,1,4,1,1,6,1,1,1,1,1,6,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,5,5,1,1,1,1,5,5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,4,1,1,1,1,1,1,1,1,3,1,1,6,1,1,6,1,1,3,6,1,1,6,1,1,1,1,1,3,1,1,1,1,6,1,1,1,3,1,1,4,1,5,5,1,3,1,1,6,1,1,1,1,1,6,0,1,4,1,1,3,4,1,1,3,1,1,1,6,1,1,6,1,3,1,6,1,1,6,2,2,1,1,6,1,1,1,1,1,6,2,2,3,1,1,1,1,4,1,1,3,1,1,1,6,2,2,1,1,1,6,0,1,1,4,3,1,1,4,3,1,1,1,1,6,1,1,6,3,1,1,6,1,1,6,5,5,1,1,1,4,5,5,1,1,6,5,5,6,1,1,1,1,1,4,3,1,1,1,1,6,5,5,1,1,5,6,5]

```

Try it online.

`è` indexes each digit in the string `"\n-/\_|"`, and `J` then joins the entire list together, which gives us the following:

```
                       __    __   __             __  ___
  /\  /\    |  |\  |  |     /    |  |     /\    |     |
 /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   |
/        \  |  |  \|  |__   \__  |   \  /    \  |     |                       __    __
\        /  |  |  /|  |     /    |   /  \ __ /  |     |
 \  /\  /   |  | / |  |--  |     |--/    \  /   |--   |
  \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_

```

Try it online.

splits the string into two parts.
take the input, and indexes it (with automatic wrap-around) to get one of the two parts, which is then being output implicitly.

Huge thanks to *@MagicOctopusUrn*'s ASCII compressor which was used to generate the compressed number and Base-7 transliteral. Try it online. (After which the transliterate has been golfed by reversing the string and number on the stack, using `в` instead of `B` to make it a list of digits, and index into the string with `è`.
> 4 votes

# Answer
# Perl, ~~292~~ ~~259~~ 246 bytes

```
$_="Svv __SS__S nnSv nnSnnn
i kjSkj hw|j h|wS /SwrhSi pq hwS |
 mSlmSlS |S| l |S|--wS |--lSSmnnlS |--S |
k ihSih jw|h j|S|__S g__S|oosjSk ih jS|ooSo|o";s/v/SSSSS/g;s/w/S|S/g;s/S/  /g;<>&1?y"g-s"\\/\\  /\\ ___ |":y"g-s"\\  \\/\\/_ /\\| ";print $_

```

It takes advantage of the fact that the two strings are mostly similar (e.g. the entire I E and C) and makes the string out of characters that are displayed differently depending on which version is being displayed. e.g m means "a forward slash for the right-way-up string, a backward slash in the upside down one". It does a transliteration substitution to display the correct character. Spaces are also run-length encoded using string substitutions.

multi-line:

```
$_="Svv __SS__S nnSv nnSnnn
i kjSkj hS|S|j h|S|SS /SS|SrhSi pq hS|SS |
 mSlmSlS |S| l |S|--S|SS |--lSSmnnlS |--S |
k ihSih jS|S|h j|S|__S g__S|oosjSk ih jS|ooSo|o";
s/v/SSSSS/g;
s/w/S|S/g;
s/S/  /g;
<>&1?
    y"g-s"\\/\\  /\\ ___ |"
:
    y"g-s"\\  \\/\\/_ /\\| ";
print $_

```

Idea:

Since there are only 22 unique columns in the output, it should be possible to store it as 22\*4 = 88 characters with a range of 0-17 (all the possible "dual-meaning" characters), along with a 56 character lookup table with one entry in the range of 0-21 per column. In theory this could be encoded with \< 100 bytes however it's hard to make this a net win because of the more complicated code to decode it.
> 3 votes

# Answer
# C, 251 bytes

```
k(w){char*f="_-/\\|]^^^\0<&*&)&3&(&&WX&J&*&\0t_&/&3&\0`);35)I5M\0a).@7).8-;./.-\0j()(0(1+4()(*+4+4()(04+",*o=f+4,m[229]="",i=7,c=10,p;for(memset(m,32,228);i;c=*f++^(w%2&i--/2==2)*115)for(p=0;*++o;m[(w%2?4-i/6-p/57:p/57)*57+p%57]=c)p+=*o-37;printf(m);}

```

This is a function `k` that receives a parameter and prints the message to `stdout`.

A more readable version:

```
k(w)
{
    char*f="\n_-/\\|", // characters to fill in
        *o= " "// for each character, the list of positions to put it in, difference-encoded
        "]%%^^^\0"                  // for '\n' (newline)
        "<&*&)&3&(&&WX&J&*&\0"      // for '_' (underscore)
        "t_&/&3&\0"                 // for '-' (minus)
        "`);35)I5M\0"               // for '/' or '\' (slashes)
        "a).@7).8-;./.-\0"          // for '\' or '/' (slashes)
        "j()(0(1+4()(*+4+4()(04+",  // for '|' (vertical bar)
        m[229]="",  // message to generate
        i, // index of character, running 7...1
        c, // current character to fill in
        p, // where to place the character
        y; // y-coordinate of the character

    memset(m,32,228); // fill the message with spaces
    for(i=7;--i;)
    {
        c=*f++;
        c^=~w%2|i/2^1?0:115; // flip the direction of slashes, if needed
        for(p=0;*++o;)
        {
            p+=*o-37; // jump to next position
            y=p/57; // extract the y-coordinate
            y=w%2?4-i/5-y:y; // flip the y-coordinate, if needed
            m[y*57+p%57]=c; // place the character
        }
    }
    printf(m); // print the message
}

```

First, it prepares an empty message (filled with spaces). For each character (e.g. `|` or `-`), it has a list of positions to place that character in.

For each position, if the upside-down version should be printed, the position is flipped. That is, its vertical coordinate `y` is replaced by `4-y` or `3-y` (depending on whether the character is an underscore). Also, the directions of the slashes are flipped - this is performed by a `XOR` with `115`.

This control structure is also used to place the newline characters - it seems more efficient to add 4 more coordinates to the list than to write an explicit loop.

---

There are a few minor glitches with this system. First of all, the final letter T looks a bit different in the flipped version:

```
___
 |    |
 |    |
 |   _|_

```

To output it correctly, the code has to place the `|` characters after the `_` characters.

In addition, in order to make sure the control string contains only ASCII characters, I encoded it:

* It records the differences between the positions instead of the positions themselves - this reduces the range
* The numbers in the string have `37` added to them, to shift them into the ASCII Range 32...127. I could add a smaller number, but `37` avoids characters like `"` and `\`, which have to be escaped inside string literals.
* Two of the numbers were greater than 127 - for example, the first `-` character appears at position 137. To account for this, I added an artificial `-` character at another position (79), which is later overwritten - the character `|` also appears at position 79.

---

Another funny thing was that I couldn't use `puts` to output the string - this would produce an extra trailing newline. So I used `printf` instead.

Also, the number `57` appears 4 times in the golfed code - the seemingly long-winded expression `(w%2?4-i/6-p/57:p/57)*57+p%57` makes it possible to eliminate the variable `y`, making the code shorter.
> 3 votes

# Answer
# CJAM, 206

The two ascii pictures are base-216 encoded, one byte = 3 characters.

```
" _\/|-":A;S7*"!D!D"+:B;qi2%{B"h  °°¤8 2 °2,J° °"",4# °³8=Ô° Ó\"# Ó °""\"z °Â89D-D·° z ·!¶"}{B"'    '!J"+"#h °¼88 2 °°  ° °""2/\" °²8=Ô° Óh#L Ó °""  h°°9D-D°,2 h° °"}?]{{i32-__36/A=@6/6%A=@6%A=}/N}/

```

Test it here
> 2 votes

# Answer
# Powershell, ~~275~~ ~~253~~ 248 bytes

```
param($n)$d='8 \83484/7/484302 92984308 92918--118--128||6//0\16116129558| \/ |8 /02083\6/10018/6\302 955776_71 9_7_'
'8\,__,777,/6 /,\6/6\,_8 -- _,88,888,  ,||||||'-split','|%{$d=$d-replace+$i++,$_}
0..3|%{$l=$_;-join$d[(0..55|%{$_*8+$l*2+$n%2})]}

```

Test script:

```
$f = {

param($n)$d='8 \83484/7/484302 92984308 92918--118--128||6//0\16116129558| \/ |8 /02083\6/10018/6\302 955776_71 9_7_'
'8\,__,777,/6 /,\6/6\,_8 -- _,88,888,  ,||||||'-split','|%{$d=$d-replace+$i++,$_}
0..3|%{$l=$_;-join$d[(0..55|%{$_*8+$l*2+$n%2})]}

}

&$f 2
&$f 1

```

Output:

```
                       __    __   __             __  ___
  /\  /\    |  |\  |  |     /    |  |     /\    |     |
 /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   |
/        \  |  |  \|  |__   \__  |   \  /    \  |     |
                       __    __
\        /  |  |  /|  |     /    |   /  \ __ /  |     |
 \  /\  /   |  | / |  |--  |     |--/    \  /   |--   |
  \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_

```

## Main ideas

The compression method is extended method of CJam by Dennis♦:

1. Create a string before compression:
    * chars of the first column of both ASCII arts, then
    * chars of the second column, then
    * chars of the third column and so on...
2. Compress using 10 consecutive replacements (10 because Powershell can use numbers 0..9 as strings, this makes the decompress algorithm shorter. Replacements found by brute force.)

The script for compression:

```
$src =
"                       __    __   __             __  ___", # line1, art1
"                       __    __                         ", # line1, art2
"  /\  /\    |  |\  |  |     /    |  |     /\    |     | ", # line2, art1
"\        /  |  |  /|  |     /    |   /  \ __ /  |     | ", # line2, art2
" /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   | ", # line3, art1
" \  /\  /   |  | / |  |--  |     |--/    \  /   |--   | ", # line3, art2
"/        \  |  |  \|  |__   \__  |   \  /    \  |     | ", # line4, art1
"  \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_"  # line4, art2

$z=-join(0..$src[0].Length|%{
    $p=$_
    $src|%{$_[$p]}
})
$z

```

The before compression string is:

```
   \  /     /\    /    \  \    /    \/      /\    /    \  \    /    \/     /  \                   ||||||                  ||||||  \    /    \/     /  \   ||||||          ||||||__  --____  --__                    ||    //  \\__    ____    __                  ||||||_   -- __   -- _  | \/ |   /  \                    \  /     /\  /__  \  \__  /    \/     /  \                   ||||||_   -- __   -- _                _      __ ||||||_      _

```
> 2 votes

# Answer
## SAS, 442 bytes

```
%macro a(b);&b=tranwrd(&b,put(i,1.),repeat('A0'x,i));%mend;%macro b(z);length a b c d$99;if mod(&z,2)then do;a='992__3__';b='\7/1|1|1/|1|4/3|2/1\0__0/1|4|';c='0\1/\1/2|1|0/0|1|--1|4|--/3\1/2|--2|';d='1\/1\/3|1|/1|1|__2\__1|__|4\/3|__1_|_';end;else do;a='992__3__2__65__1___';b='1/\1/\3|1|\1|1|4/3|1|4/\3|4|';c='0/1\/1\2|1|0\0|1|--1|4|--\3/__\2|--2|';d='/7\1|1|1\|1|__2\__1|2\1/3\1|4|';end;do i=0to 9;%a(a)%a(b)%a(c)%a(d)end;put a/b/c/d;%mend;`

```

Non-golfed:

```
%macro a(b);
  &b=tranwrd(&b,put(i,1.),repeat('A0'x,i));
%mend;

%macro b(z);
length a b c d$99;
if mod(&z,2)then do;
  a='992__3__';
  b='\7/1|1|1/|1|4/3|2/1\0__0/1|4|';
  c='0\1/\1/2|1|0/0|1|--1|4|--/3\1/2|--2|';
  d='1\/1\/3|1|/1|1|__2\__1|__|4\/3|__1_|_';
end;
else do;
  a='992__3__2__65__1___';
  b='1/\1/\3|1|\1|1|4/3|1|4/\3|4|';
  c='0/1\/1\2|1|0\0|1|--1|4|--\3/__\2|--2|';
  d='/7\1|1|1\|1|__2\__1|2\1/3\1|4|';
end;
do i=0to 9;
  %a(a)
  %a(b)
  %a(c)
  %a(d)
end;
put a/b/c/d;
%mend;

```

Tests:

```
data a;
  %b(1)
  %b(2)
  %b(0)
  %b(35)
run;
                       __    __
\        /  |  |  /|  |     /    |   /  \ __ /  |     |
 \  /\  /   |  | / |  |--  |     |--/    \  /   |--   |
  \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_
                       __    __   __             __  ___
  /\  /\    |  |\  |  |     /    |  |     /\    |     |
 /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   |
/        \  |  |  \|  |__   \__  |   \  /    \  |     |
                       __    __   __             __  ___
  /\  /\    |  |\  |  |     /    |  |     /\    |     |
 /  \/  \   |  | \ |  |--  |     |--\    /__\   |--   |
/        \  |  |  \|  |__   \__  |   \  /    \  |     |
                       __    __
\        /  |  |  /|  |     /    |   /  \ __ /  |     |
 \  /\  /   |  | / |  |--  |     |--/    \  /   |--   |
  \/  \/    |  |/  |  |__   \__  |__|     \/    |__  _|_

```

Could possibly save a bit of code by putting them in input blocks, but that adds the restriction that the macro can only be once per datastep which I feel violates the spirit of writing it as a macro. (And I suspect adding a prompt to get input in the datastep adds more characters).
> 1 votes

# Answer
# bash, 247 bytes

```
(($1%2)) && c=tail || c=head
base64 -d <<<H4sIAF/3uFUCA31Q2w3AIAj8ZwoWMLcQyS3i8JWXtWlTI6BwPA7Vz0Nunc9HhKSowlJU57qWJjBoZ/4a41o8aC4NsTBjbMgYkQDStCIrDz3AbmRuYjpzPTOGG5P9/gmKtQddFy8eMbOn4Khb7NE88ObRs+DgUez3iqrtwYPMAoWJhU/KBeJFPOCqAQAA | zcat | $c -n4

```

Strings are concatenated and gziped.
> 1 votes

# Answer
# Haskell, 138 bytes

```
m x=do
 h<-readFile"a"
 return$take 225.drop(225*mod x 2)<$>find((==h).hash.pack)(replicateM 425"/\\|_- ")

```

This is a bit of a hack. I am bruteforcing the SHA256 hash of the concatination of the two minecraft texts, and then splitting them apart and choosing the appropriate text based on parameter x. This is of cource very impractical and cannot be computed in real time, and there may even be collisions along the way for all I know.

Because Haskell cannot have the ASCII representation of that hash in a string, I am reading it from a file called "a", and has therefor added 32 bytes to my score.

* readFile and pack is from Data.ByteString.Char8
* hash is from Crypto.Hash.SHA256

## Explaination:

```
replicateM 425"/\\|_- "

```

Creates a list of every combination of the letters "/\\|\_- " on 425 letters (the length of both minecraft texts combined)

```
find((==h).hash.pack)

```

Pick the first one that matches the hash

```
take 225.drop(225*mod x 2)

```

The first text is 225 letters long, the other one is exactly 200.
> 1 votes

# Answer
# Javascript (ES6), ~~403~~ 296 bytes

(Moved from my previous answer) Trying out a new method:

```
n=>`55555559Å9Å${n%2?`55555558556776}}5Y75Y¥Æ75786¡YAA[7ćA5Fï5¡YFéA8Y§5}\x83AEÅKÅ\x99}5§5\x999\x95`:`Q5555Q9Ý>6¡77¡}}5Y7756¡75768Y¡AA£7ćA5Fû5u¡FéAY55¡}}EÅKÅ}G;5¡}5}`}`.replace(r=/./g,x=>(163+x.charCodeAt()).toString(6).slice(1)).replace(r,x=>' /|\\_-'[x]).match(/.{56}/g).join`
`

```

Note that there is a few unprintable character; these have been replaced with e.g. `\x83`.

The encoding itself is about 40 bytes shorter than the other, but the decoding process is more elaborate. I used the base-216 system that others have used to encode the text. For reference, here's the code I used:

```
// normal MINECRAFT
a='00000000000000000000000440000440004400000000000004400444'+
  '00130013000020023002002000001000020020000013000020000020'+
  '01003100300020020302002550020000025530000144300025500020'+
  '100000000300200200320024400034400200030010000300200000200';

// upside-down MINECRAFT
// un-comment this one to run it
/*
a='00000000000000000000000440000440000000000000000000000000'+
  '30000000010020020012002000001000020001003044010020000020'+
  '03001300100020020102002550020000025510000300100025500020'+
  '003100310000200210020024400034400244200000310000244004240';
*/

console.log(a.replace(/.../g,x=>String.fromCharCode(parseInt(b[i],6)+53)));

```

This basically takes the ASCII text (pre-converted to base 6) and triples it up on itself, changing it to base 216. 53 is then added to remove most non-printable characters.

Suggestions welcome!

---

Here's the original 403-byte code:

```
a=n=>{y=[' ','/','|','\\','_','-'],x=`55555559Å9Å${n%2?`55555555¡55Y}}eA5;5};GÝY}5}¡k;77;} 757Ĉ5G;7ć75§H5AB77Ý8ÝEÑ5H5EÅÕ`:`Q5555Q9Ý6¡k5}\u008FAA5;5}}5k5}5}Y§G77G} 757Ċ5?×7ć7;55GAAI7Ý8ÝA865GA5A`}`;b=x.split('').map(x=>x.charCodeAt(0)-53);for(c=[],i=b.length;i--;){c[i]=b[i].toString(6);while(c[i].length<3)c[i]='0'+c[i]}d=c.join('').replace(/\d/g,x=>y[x]).split('');d[56]=d[112]=d[168]=`
`;return d.join('')};

```

Using a `for` loop, a `while` loop, four variables that were only used once, and a ton of long algorithms for simple things. Boy, have I improved...
> 1 votes

# Answer
# PHP, 225 bytes

Ugly, brute-force solution.

```
echo str_split(gzinflate(base64_decode('dZDdDcAgCITfnYIFzC1Ecos4fOW3Nm2NgsohfIp8DrJtbB8RkkMEGktk7anhXIO6jFNpzA4Lqq2SqLs5WzKnJ4BUycjOQzXQhdScd6dmV8Rwa7rqP9/QukE9ixeGt2wpODASHoWBN0a1ggMj4fuHsuyBQcYDqfH/XrwA')),224)[$argv[1]%2];

```

I compressed then base64 encoded the concatenated strings to be displayed. The code decodes, decompresses and splits it in pieces of 224 characters. The first string is 224 characters without a trailing newline, the second is 201 characters (also no newline after it). The parity of the command line argument (`$argv[1]%2`) is used as index in the array generated by `str_split()`.
> 1 votes

# Answer
# Python, 312 bytes

```
def y(b):
 x=int(['4vwhclv10tuk4z18gf73aimn6zvwkrhxekphfn1lxocj9ezchd1cd1cv97p3f6k12s8hcjznnm5iq3om4vgxvugp3makgu4n3f6qxvdrtl4c0lva12hwt','8uzwdylhtrf6oqnwnck8pfxu25m5844tuo2700v3zoeuvossx1b47rnwyrmqodau3feu3spi9jydhyxvntv48vojx9iq9af78wufzn1'][b%2],36);x<<=69;s="";t=" /\\-|_\n"
 while x:s+=t[x&7];x>>=3
 print s

```

Function prints output given an int
> 0 votes

# Answer
# C, 321 bytes

Encoded the repetition and the character index into a string.

```
main(n,v,p,c)char**v,*p,*c;{c=" _/\\|-\n";for(p=atoi(v[1])%2?"8@8iXivs8rhththrthtPrXt`rhspiprhtPtvpshrshr`thtprpthtmhtPtmrXshr`tm`tvhsrhsrXthtrhthti`sihtitPsrXtihqtq":"8@8iXi`i8PihavhrshrsXthtshthtPrXthtPrsXtPtvprhsrhs`thtpspthtmhtPtmsXris`tm`tvr8shththsthti`siht`shrXshtPtw";*p;p++)for(n=*p/8^15;n--;)putchar(c[*p&7]);}

```
> 0 votes

# Answer
# Python 3, 486 ~~533~~ ~~612~~

```
r=str.replace;m,p=r(r(r('''YYYYY   __YA AYY   A___
  /\  /\YX\  X Y/YX Y/\Y| Y|
 /  \/  \   X \ X--  | Y|--\Y/__\   |--   |
/YY\  X  \XA \A|   \  /Y\  | Y| ''','X','|  |'),'Y','    '),'A','__  '),print;
if int(input())%2==0:p(m)
else:
 q,i,u=m.split('\n')[::-1],0,[[23,24,29,30],[42,43],[],[23,24,29,30,34,35,53,49,50,55]];q.insert(0,q.pop())
 while i<len(q):
  x=list(r(q[i],'_',' '))+[' ']
  for a in u[i]:x[a]='_'
  p(r(r(r(r(''.join(x),'___',''),"\\",'t'),'/',"\\"),'t','/'))
  i+=1

```
> 0 votes

# Answer
# PHP, 263 bytes

```
<?=strtr('3333 20220'.['2 0332 020_
2/\2/\211\113/2113/\212 1
 /2\/2\ 11 \ |1412 14\22/0\ 14 1
/32 \112\|102 \012 \2/22\12 1',
'
\32 /112/|13/212 /2\ 0 /12 1
 \2/\2/ 11 / |1412 14/22\2/ 14 1
2\/2\/211/1102 \010|3\/2102_|_'][$argn&1],[__,"  |","  ","     ","--"]);

```

Try it online!
> 0 votes

# Answer
# Ruby, 290 bytes

```
$><<(gets.to_i%2<1?"xCeCdCnCcC_
c/Bc/Be|ABAAf/e|Af/Be|f|
b/cB/cBd|AbBb|A--Af|--Be/CBd|--d|
/iBAAcB|ACdBCAdBc/eBAf|":"xCeC
Bi/AAc/|Af/e|d/cBbCb/Af|
bBc/Bc/d|Ab/b|A--Af|--/eBc/d|--d|
cB/cB/e|A/AACdBCAC|fB/e|Cc_|_").gsub(?C,'__').tr(?B,?\\).gsub(?A,'c|').gsub(/[a-z]/){|e|' '*(e.ord-97)}

```

Probably a weak and improvable entry. Basically a very simple (handcrafted) compression where lowercase letters mean that many spaces (actually ord(ch) - 'A' spaces) and uppercase letters are just some common terms that saved a few bytes.
> 0 votes

# Answer
# SOGL V0.12, ~~72~~ 71 bytes

```
═j;ΗD^⌡⁾yō⁶⅜┐≡¼τ~≡š┘,┼◄‚4øDqψ∫‛²′Ζdκ↓±ģ░○∙ΘΝ◄ōΞ06║⁶╗i-η}┌^JY³‘''n.2%?№↕

```

Try it Here!

SOGLs vertical mirroring worked perfectly for this.
> 0 votes

# Answer
# Canvas, 70 bytes

```
Ｃ＜aT［≤＾５ｔ‽◂6Ｚｒ!ｖ↓［ｕ0F∙ＯＦ－╫＃ｔ┬ａ*７ＺfK1!&)y＠½（＋M⇵ＰV-¼G:Ｕju╋╷(╫:N‟‾)ｎ⁸２％？↕

```

Try it here!
> 0 votes

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


# Question
Title: Optimizing edge selection from a list of numbers
You are given a list, L, with the length N. L contains N random positive integer values. You are only able to select from the outer edges of the list (left/right), and after each selection every value in the remaining list increase by a factor of the current selection. The goal is to maximize the total sum of the selection you make until the list is empty.

An example of L where N = 3, \[1,10,2\].

Starting list \[1,10,2\], factor = 1.

1. Chosen path left

New list \[10 * factor, 2 * factor\] =\> \[20, 4\], where factor = 2

2. Chosen path right

New list \[10 * factor\] =\> \[30\], where factor = 3

Total value = 1 + 4 + 30 =\> 35.

Output: should be the total sum of all selections, and the list of all the directions taken to get there. 35 (left, right, left). Keep in mind that the the most important part is the total sum. There may exist more than one path that leads to the same total sum, for example 35 (left, right, right).

Test case 1

\[3,1,3,1,1,1,1,1,9,9,9,9,2,1\] =\> 527

(right left left left left left left left left right left left left left)

Test case 2

\[1,1,4,1,10,3,1,2,10,10,4,10,1,1\] =\> 587

(right left left right left left left left left left right right left right)

Rules

This is code-golf, shortest codes in bytes win.

Standard loopholes are forbidden.

# Answer
# , ~~48~~ ~~43~~ 38 bytes

-5 bytes thanks to ngn.

```
{a@*>*+a:x{(+/x*1+<y*|!#x;y)}/:+!2|-x}

```

Try it online! It simply tries all possibilities, and chooses the first one with the maximum value. Left/right encoded as `0`/`1`.

```
{                                    } /functions accepts x
                               +!2|-x  /all possible selections
          { +/x*1+<y*|!#x   }          /calculate the total sum
           (             ;y)           /also record the selection with each sum
         x                   /:        /map over all selections
 a@*>*+a:                              /choose the one with max total sum

```

This can probably be golfed further.
> 2 votes

# Answer
# Haskell, ~~91 90~~ 89 bytes

Encoding the left/right decision as `0`/`1`:

```
(1%)
f%l@(h:t)|x<-f+1,(a,b)<-x%t,(c,d)<-x%init l=max(a+f*h,0:b)(c+f*last l,1:d)
_%l=(0,l)

```

Try it online!
> 0 votes

# Answer
# Ruby, 120 bytes

```
->l{[*(w=[0,1]).product(*[w]*~-s=l.size).map{|x|a,b=l.clone,0;[x,x.sum{|c|(b+=1)*(c>0?a.pop: a.shift)}]}].max_by &:last}

```

Try it online!
> 0 votes

---
Tags: code-golf, optimization
---


title: Write a word equation solver

text:
# Question
Title: Write a word equation solver
## Introduction

Consider the following example:

```
  CODE
+ GOLF
——————
 GREAT

```

This is an equation where each letter represents a decimal digit and the words represent natural numbers (similar letters represent similar digits and different letters represent different digits). The task is to match each letter with its digit value so that the equation is correct. One solution for the equation above is:

```
  9265
+ 1278
——————
 10543

```

## Your task

Your task is to write a program or a function which can solve such equations as seen above.

**Input**

The input is a string in the following format:

```
[A-Z]+\+[A-Z]+=[A-Z]+

```

Example:

1. `CODE+GOLF=GREAT`
2. `AA+BB=CC`

Spaces are omitted and only letters between capital A and Z will be used (no special or small letters).

This string can be read from the standard input, from a file, or as a function parameter.

**Output**

You have the following two options for the output format:

1. the original equation with the digits substituted
2. list of the letters and their values

If there are multiple solutions, any (but only one) of them should be returned. If there are no solutions, the program should return an empty string or null. The output can be returned as a string, can be written to the standard output or a file.

Example:

1. `9265+1278=10543`
2. `A=1 B=2 C=3` (you can use any delimiter)

## Rules

1. To make things easier, numbers are accepted to start with 0, but you can handle numbers with leading 0 as invalid solutions, it's up to you
2. Similar letters represent similar digits and different letters represent different digits
3. You can use any language and the standard library of the chosen language (no external libs)
4. You cannot connect to any resources on the internet (why would you anyways?)
5. This is a code golf task, shortest code wins. Consecutive whitespace characters count as a single character. (So any program written in whitespace automatically wins)

I have a somewhat hackish solution using 179 chars. If something is not clear, please ask me in the comments.

# Answer
# Python - 48 characters

```
exec("".join(map(chr,map(len,'                                                                                '.split("    ")))))

```

Abusing the whitespace rule.

First I converted every character in CesiumLifeJacket's answer to its ASCII value (I could have written my own but I am lazy, and it wouldn't have affected the final score anyway). The long string in my solution is one space for each one of those ASCII values, and tabs separating them. Split at tabs, find the lengths, convert back to characters and execute.

SE converts tabs to 4 spaces each, so copypasting won't work. You'll just have to believe me :)
> 11 votes

# Answer
## Ruby 2.0, 122 characters

Brute force shuffling+eval! ~~This doesn't yet meet the criteria of returning null/empty string when there is no solution; it just loops infinitely.~~ If it can't find a result after ~300 million iterations, it will return nil. Close enough?

```
f=->s{d=*0..9
d.shuffle!&&$.+=1until$.>9**9||z=eval((r=$_.tr(s.scan(/\w/).uniq*'',d*'')).gsub(/\b0/,'').sub ?=,'==')
z&&r}

```

It finds all the unique letters in the input, then repeatedly shuffles the digits 0-9 and attempts to match them up with the letters until it finds a configuration that works.

The code is presented as a function called `f` which returns a string with the numbers substituted, as in Output Option 1 above. Example usage:

```
puts f["AA+BB=CC"]
 #=> 22+44=66
puts f["CODE+GOLF=GREAT"]
 #=> 8673+0642=09315

```

Running time for the `CODE+GOLF=GREAT` example on my machine varies from instantaneous to about 6 seconds - depends on how lucky you are with the shuffles!

I'm particularly unhappy with the `gsub(/\b0/,'')` bit to remove leading zeroes but it was the only thing I could think to prevent `eval` from interpreting the numbers as octal ints.

(**BONUS**: Because it uses eval, it works for arbitrary Ruby expressions and not just addition!)
> 4 votes

# Answer
## LiveScript (179 chars)

It has deterministic and relatively quick running time and works with other operators (+, -, \*) as well.

```
f=(s)->                     # define function that takes parameter s
  c=s.replace /[^A-Z]/g ''  # remove all the non-letters
  if c                      # if any letters remain
    for i from 0 to 9       # loop from 0 to 9
       if s.indexOf(i)<0&&a=f s.split(c.0).join i  # if i is not present in the number, replace the first letter with i and call the function recursively
         return a           # if there is a solution, return it
  else                      # if there are no letters left
    if eval s.replace(/(^|\D)0+(\d)/g,'$1$2').replace \= \==  # if the expression is correct (we need to remove leading 0, because javascript interprets numbers with leading 0 as octal)
       return s  # return solution

f("CODE+GOLF=GREAT")

```
> 4 votes

# Answer
# Python, 256 213 chars

Horrific running time, will try to improve further:

```
q='='
e=input()
v=set(e)-set([q,'+'])
for x in __import__('itertools').permutations(range(10),len(v)):
    t=e
    for l,n in zip(v,x):t=t.replace(l,str(n))
    try:
        if eval(t.replace(q,q*2)):print(t);break
    except:pass

```
> 2 votes

# Answer
# JavaScript 138

```
for(s=prompt(p='1');eval(p.replace('=','!='));)for(p=s,i=64;i++<90;)p=p.replace(new RegExp(String.fromCharCode(i),'g'),10*Math.random()|0)

```

Random bruteforce.
Can take a while (my best shot for `CODE+GOLF=GREAT` is 3 seconds, my worst 3 minutes).
Try it with a simple expression like `A+B=C`
> 2 votes

# Answer
# Haskell, 222

```
import Data.List
z=(\(b,(_:c))->b:z c).span Data.Char.isUpper
j(Just g)=g
main=interact$(\d@[a,b,c]->show$take 1[e|e<-map(zip$nub$d>>=id)$permutations['0'..'9'],(\f->f a+f b==(f c::Int))(read.map(j.(`lookup`e)))]).take 3.z

```

Brute force. Tries every possible matching until it finds one, or after it has finished trying them all. I stretched the output rules: prints something like `[[('C','3'),('O','8'),('D','6'),('E','7'),('G','0'),('L','5'),('F','2'),('R','4'),('A','1'),('T','9')]]` for the solution, and if none exists, prints `[]`. Let me know if I need to change this.
> 2 votes

# Answer
# CJam - 17

```
"

    ""
"f#3b127b:c~

```

Total 975 characters, but 960 of them are whitespace in 2 sequences, so those count as 2 characters, and together with the other 15, we get 17.
975 may seem like a lot, but note that undergroundmonorail's python solution has 18862 characters, they're just on a single line :)

You can run it at http://cjam.aditsu.net/ for short words, but you should probably use the java interpreter for longer ones. With java on my laptop, `SEND+MORE=MONEY` runs in 30-40 sec and `CODE+GOLF=GREAT` in almost 3 min. It doesn't accept numbers starting with 0 (because that's not cool).

Here's a program that generates the program above (also helps if StackExchange doesn't show the whitespace correctly):

```
"{L__&=}:U;
{L!!{L))_9>{;:L;I}{+:L;}?}*}:I;
{{U!_{I}*}g}:M;
{L,N<L,g&}:K;
{I{K{L0+:L;}*MK}g}:G;
{{C#L=}%si}:R;
{XRYR+ZR=PRAb0#0<&}:F;
l'+/~'=/~:Z;:Y;:X;
[X0=Y0=Z0=]:P;
XYZ++_&:C,:NB<{0a:L;{F0{GL}?}g}*
L{XR'+YR'=ZR}{L}?"
127b3b[32 9 A]:cf='"\'"_32c9cAc"\"f#3b127b:c~"

```

The first 11 lines contain the original program (not really golfed) in a string, and the last line does the conversion and adds the decoding part.
> 2 votes

# Answer
# Powershell, 137 bytes

*port of LiveScript*

```
$f={param($s)if($c=$s-replace'[^A-Z]'){0..9|?{$s-notmatch$_}|%{&$f ($s-replace$c[0],$_)}|Select -f 1}elseif($s-replace'=','-eq'|iex){$s}}

```

Ungolfed test script:

```
$f={

param($s)                           # parameter string
$c=$s-replace'[^A-Z]'               # remove all the non-letters
if($c){                             # if any letters remain
    0..9|?{                         # loop from 0 to 9
        $s-notmatch$_               # if $s is not contains current number
    }|%{
        &$f ($s-replace$c[0],$_)    # replace the first letter with current number and call the function recursively
    }|Select -f 1                   # seelct first non-null value (break if found)
}
elseif($s-replace'=','-eq'|iex){    # else if evaluated value if the expression is $true
    $s                              # return $s as solution
}

}

&$f "AA+BB=CC"
&$f "A+AB=A"            # empty because it has no solution
&$f "CODE+GOLF=GREAT"

```

Output:

```
11+22=33
2846+0851=03697

```
> 0 votes

# Answer
# PHP, ~~118~~ 113 bytes

```
for(;;)eval(strtr($argn,"=".$w=substr(count_chars($argn,3),2),"-".$n=str_shuffle(1234567890))."||die('$w
$n');");

```

prints digits below letters and exits program; loops infinitely if unsolvable. Run as pipe with `-nr`.

**breakdown**

```
for(;;)
    eval(                               # 6. evaluate
        strtr($argn,                    # 4. translate letters to digits, "=" to "-"
            "=".$w=substr(              # 2. remove non-letters
                count_chars($argn,3)    # 1. get characters used in the argument
                ,2),
            "-".$n=str_shuffle(1234567890)  # 3. shuffle digits
        )."||die('$w\n$n');"            # 5. if falsy (`A+B-C==0`), print translation and exit
    )
;

```
> 0 votes

# Answer
# PHP, 145 bytes

```
function f($s){for(;$i<10*preg_match("/[A-Z]/",$s,$m);)strpos(_.$s,++$i+47)||f(strtr($s,$m[0],$i-1));$i||eval(strtr($s,"=","-")."||die('$s');");}

```

recursive function, prints solved equation and exits program; returns `NULL` when unsolvable.

Try it online

**breakdown**

```
function f($s)
{
    for(;
        $i<10                   # loop $i from 0 to 9
        *preg_match("/[A-Z]/",$s,$m)    # find a letter; if not found: $i<10*0 == falsy
        ;
    )
        strpos(_.$s,++$i+47)            # find $i in string
        ||f(strtr($s,$m[0],$i-1));      # if not found, replace letter with $i, recurse
    $i||                        # no letter found ($i is unset):
        eval(                   # evaluate:
            strtr($s,"=","-")       # replace "=" with "-"
            ."||die('$s');"         # if falsy (A+B-C==0), print equation, exit program
        );
    # else implicitly return NULL
}

```
> 0 votes

---
Tags: code-golf, math, puzzle-solver
---


title: Read ASCII-Art Text

text:
# Question
Title: Read ASCII-Art Text
Inspired by Golf me an ASCII Alphabet, of which this challenge is (almost) a direct inverse.

---

### Task:

Take a string of ASCII-art text and output the content of the text as regular ASCII text.

---

### Input:

String of ASCII-art text.

Input will only contain instances of ASCII character `#`, spaces and 4 or 5 newlines (a trailing newline is optional). All lines have the same length. (That is, the last ASCII-art letter is padded with trailing spaces.) You can use some other printable ASCII character instead of `#` in the input if you wish.

The input will contain ASCII-art letters `A-Z` and ASCII-art spaces (a 5x5 block of whitespace). No punctuation. There is only one line of ASCII-art text (5 actual lines). There will be no trailing or leading ASCII-art spaces, nor will there be adjacent ASCII-art spaces.

Letter size is 5x5 characters. There is a 1x5 space between each letter. Space between words is a 5x5 block of whitespace (+ 1x5 space on each side, because it is just another letter). There will be no 1x5 space at the end or at the beginning, only between ASCII-art letters.

---

### Output:

String containing the text as ASCII characters `A-Z` \+ spaces. The output can be in lowercase also, if that is somehow easier for your solution. Mixed case is also allowed.

---

### The ASCII-art letters:

```
 ###  ####   ###  ####  ##### #####  ###  #   # ##### ##### #   # #     #   #
#   # #   # #   # #   # #     #     #     #   #   #     #   #  #  #     ## ##
##### ####  #     #   # ####  ####  #  ## #####   #     #   ###   #     # # #
#   # #   # #   # #   # #     #     #   # #   #   #   # #   #  #  #     #   #
#   # ####   ###  ####  ##### #      ###  #   # ##### ###   #   # ##### #   #

#   #  ###  ####   ###  ####   ###  ##### #   # #   # #   # #   # #   # #####
##  # #   # #   # #   # #   # #       #   #   # #   # #   #  # #   # #     #
# # # #   # ####  #   # ####   ###    #   #   #  # #  # # #   #     #     #
#  ## #   # #     #  #  #   #     #   #   #   #  # #  ## ##  # #    #    #
#   #  ###  #      ## # #   #  ###    #    ###    #   #   # #   #   #   #####

```

The space:

```
     |
     | A 5x5 square of spaces.
     | (Padded with |s to make it appear in this post.)
     |
     |

```

---

### Examples:

Input:

```
#   # ##### #     #      ###        #   #  ###  ####  #     ####
#   # #     #     #     #   #       #   # #   # #   # #     #   #
##### ####  #     #     #   #       # # # #   # ####  #     #   #
#   # #     #     #     #   #       ## ## #   # #   # #     #   #
#   # ##### ##### #####  ###        #   #  ###  #   # ##### ####

```

Output: `HELLO WORLD`

Input:

```
 ###   ###   ###  ##### #####
#   # #     #   #   #     #
#####  ###  #       #     #
#   #     # #   #   #     #
#   #  ###   ###  ##### #####

```

Output: `ASCII`

Input:

```
####  ####   ###   ###
#   # #   # #   # #
####  ####  #     #  ##
#     #     #   # #   #
#     #      ###   ###

```

Output: `PPCG`

---

This is , so the shortest answer in bytes wins.

# Answer
# Jelly,  ~~50 44~~  42 bytes

```
ỴZ;6/UOḂḅ7‘ị“¥ŒƲVĊ⁾|W£⁼³ƭÇuʋụzḢĖ0ḢẆẠØsĠỌỊ»

```

**Try it online!** (note the argument does not require the leading newline, but since leading and trailing newlines have no effect I included one to make the multiline string more human-readable)

Results are mixed case (as allowed by the OP in a comment).

### How?

Splits on new lines, transposes, and joins together sub-slices of (up to) six together to get the character representations and reverses each (equating the later base conversion for the final character of length 25 to all the others of length 30). Then maps `'#'` and `' '` to one and zero respectively using the fact that `'#'` has an odd ordinal while `' '` has an even one. Reads each as if it were a base seven number. Effectively takes modulo 81 of each (to yield 27 unique values for the 27 possible cases), and finally indexes into a "magic string" with the correct chars at the correct indexes (modulo indexing is used with a magic string of length 81 to save 2 bytes).

Here is the "magic string" I created along with a (case-insensitive) regex pattern it needed to match (I added "ed" to make it length 81):

```
 ' affectedly Azerbaijan rewaxed naganas jiujitsudankly pase UVB freqHaarlemcoacted'
'^ ..f...e.....z......a..r.w.x...n.g......iuj....d..kly.p.s...vb....qh.....m.o.ct.*'

```

As such it may be compressed, looking up eleven sub-slices as words in Jelly's dictionary (most of which use the leading space default):

```
' affectedly Azerbaijan rewaxed naganas jiujitsudankly pase UVB freqHaarlemcoacted'
 ^          ^          ^       ^       ^        ^     ^    ^   ^    ^      ^

```

which results in the Jelly compressed string, `“¥ŒƲVĊ⁾|W£⁼³ƭÇuʋụzḢĖ0ḢẆẠØsĠỌỊ»`

The rest of the code works as follows:

```
ỴZ;6/UOḂḅ7‘ị“...» - Main link: multi-line string, s   e.g. HI as the #s and spaces
Ỵ                 - split on new lines                     ["#   # #####","#   #   #  ","#####   #  ","#   #   #  ","#   # #####"] (each is actually a list)
 Z                - transpose                              ["#####","  #  ","  #  ","  #  ","#####","     ","#   #","#   #","#####","#   #","#   #"] (each is actually a list)
   6/             - six-wise reduce by
  ;               -     concatenation                      ["#####  #    #    #  #####     ","#   ##   #######   ##   #"] (each is actually a list)
     U            - upend (reverse each)                   ["     #####  #    #    #  #####","#   ##   #######   ##   #"] (each is actually a list)
                  -     note: all except the last will be length 30 and like "     ...", which will become [0,0,0,0,0,...], while the last will be length 25 without those five leading zeros.
      O           - cast to ordinals ('#' -> 35, ' '-> 32) [[32,32,...],[35,32,...]]
       Ḃ          - modulo 2 ('#' -> 1, ' ' -> 0)          [000001111100100001000010011111, 1000110001111111000110001] (each is actually a list)
        ḅ7        - convert from base 7 (vectorises)       [223498370543967315553, 191672428080864454753] (these are now integers)
          ‘       - increment                              [223498370543967315554, 191672428080864454754]
                  -  (modulo 81 these would be [68, 41])
           ị      - index into (modulo & 1-indexed):
            “...» -     the "magic string" described above ' affectedly Azerbaijan rewaxed naganas jiujitsudankly pase UVB freqHaarlemcoacted'
                                                           "Hi"                                   41^                        68^

```
> 14 votes

# Answer
# Python 2, ~~405~~ ~~335~~ ~~234~~ ~~182~~ 171 bytes

```
lambda s,j=''.join:j(' QPVXU_O__FBLK_JMD_CSYZWIENH_AG___TR'[int(j(`ord(y)%2`for y in j(s.split('\n')[x][i:i+5]for x in range(5))),2)%13836%37]for i in range(0,len(s)/5,6))

```

Try it online!

---

Finally shorter than JS
> 16 votes

# Answer
## JavaScript (ES6), ~~204~~ ~~186~~ ~~184~~ 182 bytes

*Saved 18 bytes thanks to Neil*
*Saved 2 bytes thanks to ETHproductions*
*Saved 2 bytes thanks to YairRand*

Breakdown:

* 42-byte lookup table
* ~~162~~ ~~144~~ ~~142~~ 140 bytes of code

```
s=>(a=s.split`
`)[0].replace(/.{6}/g,(_,n)=>' H_JM__WDCSORLU___QKG_P_AFT_N_EI_XBV____YZ'[[0,1,2,4].reduce((p,r,i)=>p+='0b'+a[r].substr(n,5).replace(/./g,c=>1^1-c)<<i*6,0)%178%69%43])

```

### Demo

```
let f =

s=>(a=s.split`
`)[0].replace(/.{6}/g,(_,n)=>' H_JM__WDCSORLU___QKG_P_AFT_N_EI_XBV____YZ'[[0,1,2,4].reduce((p,r,i)=>p+='0b'+a[r].substr(n,5).replace(/./g,c=>1^1-c)<<i*6,0)%178%69%43])

console.log(f(
  ' ###   ###   ###  ##### ##### \n'+
  '#   # #     #   #   #     #   \n'+
  '#####  ###  #       #     #   \n'+
  '#   #     # #   #   #     #   \n'+
  '#   #  ###   ###  ##### ##### \n'
));
```
> 11 votes

# Answer
## Bash \+ ImageMagick \+ Tesseract, 161 bytes

I wanted to try the approach suggested by @stewie-griffin and went for bash + ImageMagick (to convert a string to an image) and Tesseract (to do the OCR). Here's my code, which works for the 'HELLO WORLD' testcase, but fails the other ones. Maybe some tweaking to the parameters (font, font size, kerning, spacing) helps.

```
convert -font Courier-Bold -pointsize 8 -interline-spacing -3 -kerning -3 label:"$(</dev/stdin)" -bordercolor White -border 5%x20% png:- | tesseract stdin stdout

```

Just copy-paste the ascii art into the commandline after running the command. Finish your input by pressing ^d.

Current output for the test cases:

* HELLO WORLD: HELLO WORLD
* ASCII: H5511
* PPCG: PPOG
> 10 votes

# Answer
# Scala, 184 181 bytes

A magic string + modulo solution based on `hashCode` :)

```
(a:String)=>a.split("\n").map(_.grouped(6)map(_.take(5))toArray).transpose.map(l=>"Q__WLUY_XOI_ZN_GEFR_P__JKBMV_S__ __C__D__H_T__A"(Math.abs(l.mkString.hashCode)%106%79%47))mkString

```

Try online (Scalafiddle)

More readable :

```
(a:String) => a.split("\n")
                .map(_.grouped(6)map(_.take(5))toArray)
                .transpose
                .map ( l =>
                    "Q__WLUY_XOI_ZN_GEFR_P__JKBMV_S__ __C__D__H_T__A"(
                        Math.abs(l.mkString.hashCode)%106%79%47
                    )
                )mkString

```

## Explanations

* The initial String (ASCII art) is split into 5 lines (height of ASCII character)
* Each line is split in 6-characters elements (width of ASCII character + 1 space)
* Only the first 5 characters are kept (the space at the end is useless)
* The lines are transposed (each ASCII character is represented as a sequence of 25 characters (5x5), containing either `'#'` or `' '`)
* Each ASCII character representation (sequence) is converted to String and an absolute hashcode is computed for that String (absolute needed because of next modulus)
* 3 consecutive modulus (`% 106 % 79 % 47`) are applied to associate a number ∈ `[0; 47[` for each ASCII character (see explanations below)
* This number is used as an index of the magic string

**How to get the magic string ?**

First, I represented all letters like this :

```
case class Letter(letter: Char, ascii: Seq[Char])

```

Then, I created an alphabet containing ASCII representations of all characters :

*Example :*

```
 ###
#   #
#####
#   #
#   #

```

becomes

```
Letter('A', " ### #   #######   ##   #") // 25 characters from top-left to bottom-right

```

For each letter, an absolute hashcode was computed (all hashcodes are distinct) :

```
val codes = alphabet.map { case Letter(l, a) => (l, Math.abs(a.mkString.hashCode)) }
// codes: Seq[(Char, Int)] = List(( ,253243360), (A,380997542), (B,1221679148), (C,1573119535), (D,307929190), (E,858088672), (F,857996320), (G,750155628), (H,897290147), (I,1518088099), (J,928547488), (K,1184149391), (L,519601059), (M,741735953), (N,2139154001), (O,1625960980), (P,1307658950), (Q,92382816), (R,1221771494), (S,1689301359), (T,1515228067), (U,1390718627), (V,386730851), (W,733134481), (X,628338619), (Y,23919695), (Z,2081560145))

```

Then I tried to decrease each code, but always respecting the fact that each code must be unique (the list grouped by the code must have 27 elements, 1 for each letter). So I tried the first 200 modulus :

```
val mod = (1 to 200).find(modulo => codes.map { case (a,b) => (a, b % modulo) }.groupBy(_._2).size==27).get

```

I found `106` as the first modulo to be applied :

```
val codes2 = codes.map { case (l, c) => (l, c%mod) }
val codes = codes2
// codes: Seq[(Char, Int)] = List(( ,32), (A,46), (B,104), (C,35), (D,38), (E,16), (F,96), (G,94), (H,41), (I,89), (J,102), (K,71), (L,83), (M,105), (N,13), (O,56), (P,20), (Q,0), (R,18), (S,29), (T,43), (U,5), (V,27), (W,3), (X,87), (Y,53), (Z,91))

```

I repeated the previous steps until the smallest modulo. I found :

* 79
* 47
* 44
* 42

*Note :* The last modulo I chose (`47`) is not the smallest here :

* I found 44, but if I had chosen 44, the magic string would have size 44 (instead of 47) **but** I would have to write `%106%79%47%44` (13 characters instead of `%106%79%47` = 10 characters). So in bytes, the code should have had the same size as the one I got
* There is also 42, but then the code should have had 1 byte more than the one I got

Next, I applied the consecutive modulus (`% 79 % 47`) to the last `codes`, to get the definitive codes associated to each letter :

```
codes: Seq[(Char, Int)] = List(( ,32), (A,46), (B,25), (C,35), (D,38), (E,16), (F,17), (G,15), (H,41), (I,10), (J,23), (K,24), (L,4), (M,26), (N,13), (O,9), (P,20), (Q,0), (R,18), (S,29), (T,43), (U,5), (V,27), (W,3), (X,8), (Y,6), (Z,12))

```

Finally, to construct the magic string :

```
val initialMap = (0 until 47).map(i => (i, '_')).toMap
val codesMap = codes.map(i => (i._2, i._1)).toMap

val magicString = (initialMap ++ codesMap).toSeq.sortBy(_._1).map(_._2).mkString
// magicString: String "Q__WLUY_XOI_ZN_GEFR_P__JKBMV_S__ __C__D__H_T__A"

```

*Example :* The letter `A` above is associated to 46 (`380997542 % 106 % 79 % 47`), and the 46th element of the magic string is A :)

## Test cases

```
// assign function to f
val f = (a:String)=>a.split("\n").map(_.grouped(6)map(_.take(5))toArray).transpose.map(l=>"Q__WLUY_XOI_ZN_GEFR_P__JKBMV_S__ __C__D__H_T__A"(Math.abs(l.mkString.hashCode)%106%79%47))mkString

```

**HELLO WORLD :**

```
val asciiArt = """|#   # ##### #     #      ###        #   #  ###  ####  #     ####
                  |#   # #     #     #     #   #       #   # #   # #   # #     #   #
                  |##### ####  #     #     #   #       # # # #   # ####  #     #   #
                  |#   # #     #     #     #   #       ## ## #   # #   # #     #   #
                  |#   # ##### ##### #####  ###        #   #  ###  #   # ##### #### """.stripMargin

f(asciiArt)    // HELLO WORLD

```

**ASCII :**

```
val asciiArt = """| ###   ###   ###  ##### #####
                  |#   # #     #   #   #     #
                  |#####  ###  #       #     #
                  |#   #     # #   #   #     #
                  |#   #  ###   ###  ##### #####""".stripMargin

f(asciiArt)    // ASCII

```

**PPCG :**

```
val asciiArt = """|####  ####   ###   ###
                  |#   # #   # #   # #
                  |####  ####  #     #  ##
                  |#     #     #   # #   #
                  |#     #      ###   ### """.stripMargin

f(asciiArt)    // PPCG

```

## Edits

* Saved 3 bytes by removing `.` before `map`, `toArray` and `mkString`
> 7 votes

# Answer
# PHP, 294 Bytes

```
<?$l=" 00000YE00G0000R000A0Q0000C0BW000K00000000000LT00000J00000000MU0000Z0000DI000000V0000000P00H0000ONF000S00X";preg_match_all("#(.{5})\s#s","$_GET[0] ",$t);for($i=0;$i<$c=count($a=$t[1])/5;$i++)$s.=$l[bindec(strtr($a[$i].$a[$i+$c].$a[$i+2*$c].$a[$i+3*$c].$a[$i+4*$c]," #","01"))%106];echo$s;

```

Try it online!

Expanded

```
$l=" 00000YE00G0000R000A0Q0000C0BW000K00000000000LT00000J00000000MU0000Z0000DI000000V0000000P00H0000ONF000S00X"; # search string mod 106
preg_match_all("#(.{5})\s#s","$_GET[0] ",$t); # Regex take each group of five chars followed by a whitespace
for($i=0;$i<$c=count($a=$t[1])/5;$i++)
  $s.=$l[bindec(strtr($a[$i].$a[$i+$c].$a[$i+2*$c].$a[$i+3*$c].$a[$i+4*$c]," #","01"))%106]; # join each groups make a binaray make a decimal mod 106
echo$s; # Output

```

## Converting the Input to an image format

@Stevie Griffin search a solution to get this from an image. I think he want **not really** the image format I have use.

```
echo'<svg xmlns="http://www.w3.org/2000/svg" width="100%"><switch><foreignObject x="0" y="0" width="100%" height="300"><body xmlns="http://www.w3.org/1999/xhtml"><pre>'.$_GET[0].'</pre></body></foreignObject></switch></svg>';

```

SVG can contains HTML parts if then included in a foreignObject. So I put a pre Element in a SVG.

## Image Output

```
<svg xmlns="http://www.w3.org/2000/svg" width="100%"><switch><foreignObject x="0" y="0" width="100%" height="300"><body xmlns="http://www.w3.org/1999/xhtml"><pre>#   # ##### #     #      ###        #   #  ###  ####  #     ####
#   # #     #     #     #   #       #   # #   # #   # #     #   #
##### ####  #     #     #   #       # # # #   # ####  #     #   #
#   # #     #     #     #   #       ## ## #   # #   # #     #   #
#   # ##### ##### #####  ###        #   #  ###  #   # ##### #### </pre></body></foreignObject></switch></svg>
```

## Solving from Image Changes

SVG is machine readable so after saving the SVG as "i.svg" you need only replace `$_GET[0]` with `preg_replace("#(^.*e>)(.*)(</p.*$)#s","$2",join(file("i.svg")))` in the way with normal input + 55 Bytes
> 4 votes

# Answer
# C,  ~~225~~  209 bytes

*Thanks to @ceilingcat for saving 16 bytes!*

```
i,j,k,l,n,m;f(char*s){l=index(s,10)-s+1;for(i=0;i<l/6;++i){for(m=j=0;j<5;m+=n*(exp10(j++)+.1))for(n=k=0;k<5;)n+=(s[i*6+j+k*l]==35)<<k++;for(j=0;"Qi Y$>W);Xa%d^F4K-]7jcMAG="[j++]-32-m%77;);putchar(n?64+j:32);}}

```

Try it online!
> 2 votes

# Answer
# Powershell, ~~152~~ 146 bytes

```
-join$(for($t=$args-split'
';$c-lt$t[0].Length;$c+=6){$s=0;$t|% s*g $c,5|% t*y|%{$s+=$s+$_}
'_ISRJ_BK_HFQPL_MYNCE _TXDAO_VWUZ__G'[$s%578%174%36]})

```

Test script:

```
$f = {

-join$(for($t=$args-split'
';$c-lt$t[0].Length;$c+=6){$s=0;$t|% s*g $c,5|% t*y|%{$s+=$s+$_}
'_ISRJ_BK_HFQPL_MYNCE _TXDAO_VWUZ__G'[$s%578%174%36]})

}

&$f @"
#   # ##### #     #      ###        #   #  ###  ####  #     ####
#   # #     #     #     #   #       #   # #   # #   # #     #   #
##### ####  #     #     #   #       # # # #   # ####  #     #   #
#   # #     #     #     #   #       ## ## #   # #   # #     #   #
#   # ##### ##### #####  ###        #   #  ###  #   # ##### ####
"@

&$f @"
 ###   ###   ###  ##### #####
#   # #     #   #   #     #
#####  ###  #       #     #
#   #     # #   #   #     #
#   #  ###   ###  ##### #####
"@

&$f @"
####  ####   ###   ###
#   # #   # #   # #
####  ####  #     #  ##
#     #     #   # #   #
#     #      ###   ###
"@

&$f @"
       ###  ####   ###  ####  ##### #####  ###  #   # ##### ##### #   # #     #   # #   #  ###  ####   ###  ####   ###  ##### #   # #   # #   # #   # #   # #####
      #   # #   # #   # #   # #     #     #     #   #   #     #   #  #  #     ## ## ##  # #   # #   # #   # #   # #       #   #   # #   # #   #  # #   # #     #
      ##### ####  #     #   # ####  ####  #  ## #####   #     #   ###   #     # # # # # # #   # ####  #   # ####   ###    #   #   #  # #  # # #   #     #     #
      #   # #   # #   # #   # #     #     #   # #   #   #   # #   #  #  #     #   # #  ## #   # #     #  #  #   #     #   #   #   #  # #  ## ##  # #    #    #
      #   # ####   ###  ####  ##### #      ###  #   # ##### ###   #   # ##### #   # #   #  ###  #      ## # #   #  ###    #    ###    #   #   # #   #   #   #####
"@

```

Output:

```
HELLO WORLD
ASCII
PPCG
 ABCDEFGHIJKLMNOPQRSTUVWXYZ

```

Note:

1. `$t|% s*g $c,5|% t*y|%{$s+=$s+$_}` is shortcut for `$t.substring($c,5).toCharArray()|%{$s+=$s+$_}`
2. `("abcd","efgh").substring(1,2)` returns the array `("bc","de")`
3. `("bc","de").toCharArray()` returns the array `('b','c','d','e')`
> 2 votes

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


title: Golf me an ASCII Alphabet

text:
# Question
Title: Golf me an ASCII Alphabet
Don't you find that reading simple text isn't appealing enough? Try our

```
#####  ###   ###  ##### #####       ##### ##### #   # #####   #
#   # #     #   #   #     #           #   #      # #    #     #
#####  ###  #       #     #           #   ####    #     #     #
#   #     # #   #   #     #           #   #      # #    #
#   #  ###   ###  ##### #####         #   ##### #   #   #     #

```

Much more fancy isn't it? But it's pretty long to write by hand, it would be wonderful if someone did a program that do it for me !

**Your task**, if you volunteer to help me, will be to write a program or a function that takes a string containing `[a-zA-Z\s\n]` only, and output (or return) the ascii writing of it!

You must use the following alphabet to format your output:

```
##### ####   ###  ####  ##### #####  ###  #   # ##### ##### #   # #     #   #
#   # #   # #   # #   # #     #     #     #   #   #     #   #  #  #     ## ##
##### ####  #     #   # ####  ####  #  ## #####   #     #   ###   #     # # #
#   # #   # #   # #   # #     #     #   # #   #   #   # #   # #   #     #   #
#   # ####   ###  ####  ##### #      ###  #   # ##### ###   #  #  ##### #   #

#   #  ###  ####   ###  ####   ###  ##### #   # #   # #   # #   # #   # #####
##  # #   # #   # #   # #   # #       #   #   # #   # #   #  # #   # #     #
# # # #   # ####  #   # ####   ###    #   #   #  # #  # # #   #     #     #
#  ## #   # #     #  ## ##        #   #   #   #  # #  ## ##  # #    #    #
#   #  ###  #      #### # #    ###    #    ###    #   #   # #   #   #   #####

```

The space:

```
     |
     | it's a 5x5 square of spaces
     | but had to pad it with |s to make it appear in this post
     |
     |

```

As this is a fixed-width font, the space character is also surrounded by spaces, resulting in a 7-width space between the two letters.

```
a b
     1234567       -- these numbers are just for the example, you don't have to output them
#####       ####
#   #       #   #
#####       ####
#   #       #   #
#   #       ####

a  b
     1234567890123
#####             ####
#   #             #   #
#####             ####
#   #             #   #
#   #             ####

```

When you encounter a newline, as in the input

```
ascii
text

```

Just make sure to separate the two blocks of text by at least one empty line

```
#####  ###   ###  ##### #####
#   # #     #   #   #     #
#####  ###  #       #     #
#   #     # #   #   #     #
#   #  ###   ###  ##### #####

##### ##### #   # #####
  #   #      # #    #
  #   ####    #     #
  #   #      # #    #
  #   ##### #   #   #

```

Also, you are allowed to replace the `#`s with any other character as long as it is in the printable ASCII range, and is not spaces. You could for instance use `A`s for the letter A, `B` for the letter B and so on.

As this is (and moreover ) the winning submission will be the one that solve this challenge in the least byte possible, have fun!

# Answer
> 7 votes
## Python 3, 375 bytes

```
f=lambda i:"\n\n".join("\n".join(map(" ".join,zip(*[[x.replace("0"," ")[a*5:a*5+5]for a in range(5)]for x in[["{:025b}".format(int(c,36))for c in'0 JPCFL J2UKE 92Y3Y J2KAM JOMCF JOMC0 92B72 AYP81 JFM3J JFMHO AZC7M AB6ZJ B5I5T B43N5 92YWE J2UJ4 92YY7 J2UQC 926UM JFM2S AYE5Q AY8G4 AYHKH AT6Q9 AT6KK AWU7'.split()][x!=" "and ord(x)-64]for x in j.upper()]])))for j in i.split("\n"))

```

See this code running on ideone.com.

The same code, but somehow nicely indented, formatted and commented:

```
f = lambda i: \

    # join multiline strings together using an empty line as separator:
    "\n\n".join(

        # join the string lines of one big output line together:
        "\n".join(

            # join the corresponding rows of the letters together using " ":
            map(" ".join, zip(*

                # make a list (output line) of list (output characters)
                # of strings (single character's rows):
                [

                    # replace 0s with spaces and split the bit strings into
                    # chunks of 5 characters - the rows of each letter:
                    [x.replace("0", " ")[a*5 : a*5+5] for a in range(5)]

                    for x in [

                        # split the space separated character codes and
                        # convert them from base 36 to
                        # base 2 strings of length 25:
                        ["{:025b}".format(int(c, 36)) for c in

                         # the encoded font data (reformatted):
                         '0 JPCFL J2UKE 92Y3Y J2KAM JOMCF JOMC0 92B72 '
                         'AYP81 JFM3J JFMHO AZC7M AB6ZJ B5I5T B43N5 92YWE '
                         'J2UJ4 92YY7 J2UQC 926UM JFM2S AYE5Q AY8G4 AYHKH '
                         'AT6Q9 AT6KK AWU7'.split()]

                        # select element 0 if we want a space, else find
                        # out the index from the ASCII code of the letter:
                        [x != " " and ord(x) - 64]

                        # repeat for every character in the input line:
                        for x in j.upper()
                    ]
                ]
            ))

        # repeat for every line in the input
        ) for j in i.split("\n")
    )

```

I also decided to go for **base 36** encoding as that's the highest base Python's built-in `int()` natively supports. Here is a short Python 3 script I wrote (ungolfed) that converts font definitions like in the question into base 36 codes: My converter on ideone.com

The result consists of the character `1` as enabled pixel and a space  as disabled pixel. Here's a single example run:

Input (line break as `\n`):

```
Hello World
Python rocks

```

Output:

```
1   1 11111 1     1      111        1   1  111  1111  1     1111
1   1 1     1     1     1   1       1   1 1   1 1   1 1     1   1
11111 1111  1     1     1   1       1 1 1 1   1 1111  1     1   1
1   1 1     1     1     1   1       11 11 1   1 11    1     1   1
1   1 11111 11111 11111  111        1   1  111  1 1   11111 1111

1111  1   1 11111 1   1  111  1   1       1111   111   111  1   1  111
1   1  1 1    1   1   1 1   1 11  1       1   1 1   1 1   1 1  1  1
1111    1     1   11111 1   1 1 1 1       1111  1   1 1     111    111
1       1     1   1   1 1   1 1  11       11    1   1 1   1 1 1       1
1       1     1   1   1  111  1   1       1 1    111   111  1  1   111

```

# Answer
> 4 votes
# Clojure, 552 bytes

```
(defn t[s](print(reduce #(str %1"\n"%2)(map #(apply str %)(let[a[:jpcfl :j2uke :92y3y :j2kam :jomcf :jomc0 :92b72 :ayp81 :jfm3j :jfmho :azc7m :ab6zj :b5i5t :b43n5 :92ywe :j2uj4 :92yy7 :j2uqc :926um :jfm2s :aye5q :ay8g4 :ayhkh :at6q9 :at6kk :je7mn :0]](map(fn[o](map #(str(.replace %"0"" ")"\n")(map(fn[w](reduce #(str %1(.substring %2 w(+ w 5))"0")""(map #(str(apply str(repeat(- 25(count %))"0"))%)(map #(Integer/toString(Integer/valueOf(name %)36)2)(map a(map #(if(= % \space)26(-(int %)97))(.toLowerCase o)))))))(range 0 25 5))))(.split s"\n")))))))

```

Each letter in ascii is represented as a binary string with # - 1, space - 0. Then it's converted to base 36 so that it only takes 5 chars to store + ":" to let Clojure know that it should be treated as symbol. Then the input is split by newline symbol and for each line we convert a letter in 36 base back to binary base and get first \[0:5\] symbols add newline symbols, get next \[5:10\] symbols and so on.

You can see it running here - https://ideone.com/y99ST5

# Answer
> 1 votes
# SOGL, 137 bytes

```
 °f`7-π⅛χ%sΤ↕ņLRΕ⅓9׀b∫rr(¶æKGTΧ3;■ΦΤg¼⁰¡Νg‽}○eΧ²Y∫Οαν⌡l′}¾(8╔ <%╤∙i.d↔ū∫Æo┌jyŗ▲δ⁶=╗$↑yōΛ3h¼╔◄┼)‘’«n.{5{ø}¹,uR{8+:Ahwha’#=?X’«@*}┼L@*┼}pøO

```

Explanation:

```
...‘’«n.{5{ø}¹,uR{8+:Ahwha’#=?X’«@*}┼L@*┼}pøO
...‘                                           push a string with the letter data                            ["..."]
    ’«n                                        split in lengths of 25                                        [[".", ".", ".",...]]
       .{                                      repeat input times                                            [[".", ".", ".",...]]
         5{ø}                                  push 5 empty strings                                          [[".", ".", ".",...], "", "", "", "", ""]
             ¹                                 wrap those in an array                                        [[".", ".", ".",...], ["", "", "", "", ""]]
              ,                                get a string input                                            [[".", ".", ".",...], ["", "", "", "", ""], "Hello World"]
               u                               lowercase it                                                  [[".", ".", ".",...], ["", "", "", "", ""], "hello world"]
                R{                       }     itirate over the ordinals of the string                       [[".", ".", ".",...], ["", "", "", "", ""], 104]
                  8+                           add 8 to the ordinal                                          [[".", ".", ".",...], ["", "", "", "", ""], 112]
                    :A                         save on variable A                                            [[".", ".", ".",...], ["", "", "", "", ""], 112]
                      h                        swap 2 items one below the stack                              [["", "", "", "", ""], [".", ".", ".",...], 112]
                       w                       get the ord+8th item of the letter data array (modulo length) [["", "", "", "", ""], [".", ".", ".",...], "-----  -    -    -  -----"]
                        h                      swap 2 items one below the stack                              [[".", ".", ".",...], ["", "", "", "", ""], "-----  -    -    -  -----"]
                         a                     load the variable A                                           [[".", ".", ".",...], ["", "", "", "", ""], "-----  -    -    -  -----", 112]
                          ’#=?     }           if equals to 40 then                                          [[".", ".", ".",...], ["", "", "", "", ""], "----- -     -     - -----"] (temporalily switching to space case; it incorrectly picks "N" for space)
                              X                delete the string                                             [[".", ".", ".",...], ["", "", "", "", ""]]
                               ’«@*            push a string with 25 spaces                                  [[".", ".", ".",...], ["", "", "", "", ""], "                         "]
                                    ┼          add the string vertically-then-horizontally to the array      [[".", ".", ".",...], ["", "", "", "", ""], ["-   -", "-   -", "-----", "-   -", "-   -"]] (back to "H")
                                     L@*       push a string with 10 spaces                                  [[".", ".", ".",...], ["", "", "", "", ""], ["-   -", "-   -", "-----", "-   -", "-   -"], "          "]
                                        ┼      add the string vertically-then-horizontally to the array      [[".", ".", ".",...], ["", "", "", "", ""], ["-   -  ", "-   -  ", "-----  ", "-   -  ", "-   -  "]]
                                          p    output the resulted line                                      [[".", ".", ".",...], ["", "", "", "", ""]]
                                           øO  append to output an empty line

```

note: currently this language can't really accept multiline input string so I've made it ask for a number and read the next x lines as the input.

The first string is

```
"------ -  - -  - -  ----------- - -- - -- - - - -  --- -   --   --   - - - ------   --   --   - --- ------ - -- - -- - --   ------- -  - -  - -  -     --- -   --   -- - -  -- -----  -    -    -  ------   --   -------   --   --  ---   -------    -    -----  -    --  -  --    -----    -    -    -    ------ -     -   -   ---------- -     -     - ----- --- -   --   --   - --- ------ -  - -  - -   -    --- -   --   --  -- ---------- -- - - -- -   -    -   - - -- - -- - -   - -    -    ------    -    ----     -    -    ----- --     --     -  -- --   -----   -   -     - ------   - - -   -   - - -   --     -     --- -   -    -   --  --- - ---  --   -"

```

compressed using a custom dictionary that uses " " and "-" (the compression has a special mode with "\n -|/\_" available so even more compression!)
It contains 25 chars per ascii char in the order of the alphabet. they are ordered top-down then right.
the chars go like

```
16b
27c
38d . . .
49e
5af

```

and that's the same way that  adds them to an array.

# Answer
> 1 votes
# C (gcc), ~~326~~ ~~322~~ ~~321~~ 317 bytes

-8 bytes thanks to ceilingcat

```
#define X!!putchar
char*p,*q;i,j;f(int*s){for(;p=strtok(p?0:strdup(s),"\n");X(10))for(i=0;i<5;i+=X(10))for(q=p;*q;q+=X(32))for(j=0;j<5;)X((*q-32?"OAOAA?A?A?>A1A>?AAA?O1?1OO1?11>1IA>AAOAAO444OO4457A97591111OAKEAAACCIA>AAA>?A?11>AAIN?A?35>1>@>O4444AAAA>AA::4AAEKAA:4:AA:444O842O"[(*q&~32)*5-325+i]-48:0)>>j++&1?35:32);}

```

Try it online!

# Answer
> 1 votes
# Powershell, ~~261~~ 253 bytes

```
$args-split'
'|%{$s=$_
0..5|%{$l=$_
-join($s|% *per|% t*y|%{$c='_ONO__NQ__QAQQNONON_QQQQQ?QQQQAAAQDDIA[SQQQQADQQQJJ(_OAQOOY_DDGAUUQOQONDQJUDD$QQQQAAQQDEEAQYQAYCPDQJ[JD"QONO_ANQ_GI_QQNA^ENDNDQQD?'[$l*26+$_-65+222*!($_-32)]
0..5|%{' #'[(+$c-shr$_)%2]}})}}

```

Test script:

```
$f = {

$args-split'
'|%{$s=$_
0..5|%{$l=$_
-join($s|% *per|% t*y|%{$c='_ONO__NQ__QAQQNONON_QQQQQ?QQQQAAAQDDIA[SQQQQADQQQJJ(_OAQOOY_DDGAUUQOQONDQJUDD$QQQQAAQQDEEAQYQAYCPDQJ[JD"QONO_ANQ_GI_QQNA^ENDNDQQD?'[$l*26+$_-65+222*!($_-32)]
0..5|%{' #'[(+$c-shr$_)%2]}})}}

}

&$f "ascii art
text"

```

Output:

```
#####  ###   ###  ##### #####       ##### ####  #####
#   # #     #   #   #     #         #   # #   #   #
#####  ###  #       #     #         ##### ####    #
#   #     # #   #   #     #         #   # ##      #
#   #  ###   ###  ##### #####       #   # # #     #

##### ##### #   # #####
  #   #      # #    #
  #   ####    #     #
  #   #      # #    #
  #   ##### #   #   #

```

## Note:

`$s|% *per|% t*y` is shortcut for `$s|% toUpper|% toCharArray`

## About space:

For each character of the source string, the script takes a symbol (bit mask) from the magic string `'_ONO__NQ...'`. However, the index goes beyond the magic string for a space. In this case, the bit mask `$c` becomes empty. It means zero for all bits.

## About blank line:

The script displays 6 rows for each symbol instead of 5. The index goes beyond the magic string for a blank line too. So, the row 6 contains spaces only.

It is best seen if you print another character instead of a space. For example `·`.

```
#####··###···###··#####·#####·······#####·####··#####·
#···#·#·····#···#···#·····#·········#···#·#···#···#···
#####··###··#·······#·····#·········#####·####····#···
#···#·····#·#···#···#·····#·········#···#·##······#···
#···#··###···###··#####·#####·······#···#·#·#·····#···
······················································
#####·#####·#···#·#####·
··#···#······#·#····#···
··#···####····#·····#···
··#···#······#·#····#···
··#···#####·#···#···#···
························

```

# Answer
> 0 votes
# JavaScript (ES6), ~~292~~ ~~287~~ 278 bytes

```
s=>s.split`
`.map(s=>`vfefvvehvvh1hhefefevhhhhhv
hhhh111h4491rjhhhh14hhhaa8
vf1hffpv4471llhfhfe4hal444
hhhh11hh4551hph1p3g4hara42
hfefv1ehv79vhhe1u5e4e4hh4v`.replace(/.{26}/g,S=>s.replace(/./g,c=>'012345'.replace(/./g,x=>' #'[(P=parseInt)(S[P(c,36)-10]||0,36)>>x&1])))).join`

`

```

### Demo

```
let f =

s=>s.split`
`.map(s=>`vfefvvehvvh1hhefefevhhhhhv
hhhh111h4491rjhhhh14hhhaa8
vf1hffpv4471llhfhfe4hal444
hhhh11hh4551hph1p3g4hara42
hfefv1ehv79vhhe1u5e4e4hh4v`.replace(/.{26}/g,S=>s.replace(/./g,c=>'012345'.replace(/./g,x=>' #'[(P=parseInt)(S[P(c,36)-10]||0,36)>>x&1])))).join`

`

O.innerText = f('HELLO WORLD\nTHIS IS A TEST')
```

```
<pre id=O></pre>
```

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


title: Japanese pitch accent numbers

text:
# Question
Title: Japanese pitch accent numbers
> Your challenge is to turn a Japanese word and a dictionary pitch accent number into a new string where the rises and falls in pitch are marked: e.g. **(2, ウシロ)**`ウ/シ\ロ`.
>
> To help you out with this, I'll explain a little about Japanese phonology.

# Background: on *moras*

For the purpose of this challenge, we will write Japanese words in katakana, the simplest Japanese syllabary. A word consists of one or more **moras**, each of which consists of

1. one of:

```
アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンッガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ

```
2. **optionally** followed by one of:

```
ャュョ

```

For example, シャッキン consists of 4 moras: **シャ, ッ, キ, ン**.

*※ The three optional characters are small versions of katakana `ヤユヨ` (ya yu yo).
For example, キャ is **ki + small ya**, pronounced **kya** (1 mora), whereas キヤ is **kiya** (2 moras).*

# Background: pitch accents

Japanese words are described by a certain contour of high and low pitches. For example, **ハナス** (**hanasu**, speak) is pronounced

```
   ナ
  /  \
ハ    ス–···

```

meaning the pitch goes up after **ハ ha**, then falls after **ナ na**, and stays low after **ス su**.
(That is to say: Unaccented grammar particles after **su** will be low again).

We might describe this contour as “low-high-low-(low…)”, or `LHL(L)` for short.

In a dictionary, the pitch of this word would be marked as **2**, because the pitch falls after the *second* mora. There are a few possible pitch patterns that occur in Tōkyō dialect Japanese, and they are all given a number:

* **0**, which represents `LHHH…HH(H)`. This is *heibangata*, monotone form.

```
   イ–バ–ン–···                ···
  /                  or       /
ヘ                          ナ

```
* **1**, which represents `HLLL…LL(H)`. This is *atamadakagata*, “head-high” form.

```
イ                          キ
  \                  or       \
   ノ–チ–···                   ···

```
* **n ≥ 2**, which represents `LHHH…` (length **n**) followed by a drop to `L…L(L)`.
For example, センチメエトル has pitch accent number **4**:

```
   ン–チ–メ
  /       \
セ         エ–ト–ル–···

```

Such a word must have **≥ n** moras, of course.

*※ Note the difference between* **ハシ \[0\]** *and* **ハシ \[2\]**:

```
   シ–···                シ
  /            vs       /  \
ハ                    ハ     ···

```

You can hear the different pitch accent numbers demonstrated here ♪.

# The challenge

Given an integer **n ≥ 0** (a pitch accent number as above) and a valid word of at least **n** moras, insert `/` and `\` into it at points where those symbols would occur in the diagrams above; i.e. at points in the word where the pitch rises or falls.

The output for **(2, ハナス)** would be:

```
ハ/ナ\ス

```

And the output for **(0, ヘイバン)** would be:

```
ヘ/イバン

```

Remember: you must correctly handle sequences like キョ or チャ as a single mora.
The output for **(1, キョウ)** is `キョ\ウ`, not `キ\ョウ`.

> **Instead of `/` and `\`, you may pick any other pair of distinct, non-katakana Unicode symbols.**

This is : the objective is to write the shortest solution, measured in bytes.

# Test cases

One per line, in the format `n word → expected_output`:

```
0 ナ → ナ/
0 コドモ → コ/ドモ
0 ワタシ → ワ/タシ
0 ガッコウ → ガ/ッコウ
1 キ → キ\
1 キヤ → キ\ヤ
1 キャ → キャ\
1 ジショ → ジ\ショ
1 チュウゴク → チュ\ウゴク
1 ナニ → ナ\ニ
1 シュイ → シュ\イ
1 キョウ → キョ\ウ
1 キャンバス → キャ\ンバス
2 キヨカ → キ/ヨ\カ
2 キョカ → キョ/カ\
2 ココロ → コ/コ\ロ
2 ジテンシャ → ジ/テ\ンシャ
3 センセイ → セ/ンセ\イ
3 タクサン → タ/クサ\ン
4 アタラシイ → ア/タラシ\イ
4 オトウト → オ/トウト\
6 ジュウイチガツ → ジュ/ウイチガツ\

```

Generated by this reference solution.

# Answer
# Retina 0.8.2, 68 bytes (UTF-8)

```
\d+(.[ャュョ]?)
$1/$&$*1\
/1\b

/.
/
+`1(1*.)(.[ャュョ]?)
$2$1

```

Try it online! Link includes test cases. Explanation:

```
\d+(.[ャュョ]?)
$1/$&$*1\

```

Convert the number to unary, wrap it in `/\`, and insert it after the first mora.

```
/1\b

```

If the number was 1, then delete it and the `/`, leaving the `\`.

```
/.
/

```

Subtract 1 from the number, but in the case of `0`, this deletes the `\`, leaving the `/`.

```
+`1(1*.)(.[ャュョ]?)
$2$1

```

Move the `\` one mora to the right for each remaining `1`.
> 2 votes

# Answer
# Jelly, 32 bytes

```
O%62ḟ€“579‘œṗ⁸Ḋ⁹‘+Ị$,2¤œṖżCØ.ḟƊ}

```

A full program accepting a list of characters and a non-negative integer which prints using `0` for `/` and `1` for `\`.

**Try it online!** Or see the test-suite.

### How?

```
O%62ḟ€“579‘œṗ⁸Ḋ⁹‘+Ị$,2¤œṖżCØ.ḟƊ} - Main Link: list of characters S, integer N
O                                - convert to ordinals
 %62                             - modulo by 62
      “579‘                      - code-page indices list = [53,55,57]
                                 -   (representing the three optional characters)
     €                           - for each ordinal:
    ḟ                            -   filter discard if in [53,55,57]
             ⁸                   - chain's left argument, S
           œṗ                    - partition before truthy indices
                                 -   (so before the non optional character positions)
              Ḋ                  - dequeue (remove the leading empty list)
                       œṖ        - partition at indices...
                      ¤          - nilad followed by (links) as a nilad:
               ⁹                 -   chain's right argument, N
                ‘                -   increment
                   $             -   last two links as a monad:
                 +               -     add
                  Ị              -     insignificant? (1 if 1; 0 if 2+)
                    ,2           -   pair with 2
                               } - use right argument, N, for...
                              Ɗ  - last three links as a monad:
                          C      -   compliment = 1-N
                             ḟ   -   filter discard if in...
                           Ø.    -   bits = [0,1]
                                 -     (i.e. if N=0:[0], if N=1:[1], otherwise:[0,1])
                         ż       - zip together
                                 -   e.g. [[["ジュ"],0],[["ウ","イ","チ","ガ","ツ"],1]]
                                 - implicit (smashing) print
                                 -   e.g. ジュ0ウイチガツ1

```
> 1 votes

# Answer
# APL (Dyalog), 45 characters / 51 bytes\* / 83 bytes

```
{S←⍵⊂⍨~⍵∊'ャュョ'⋄S[⍺~0],←'\'⋄S[0~⍨⍺≠1],←'/'⋄∊S}

```

Try it online!

The second score only applies if the three Katakana characters in the code can be counted as a different encoding than the other portion of the code.
> 1 votes

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

```
n=>s=>s.replace(/.[ャュョ]?/g,s=>i=--n-i?s+1:n?s:s+2,i=0)

```

Try it online!
> 1 votes

# Answer
# Perl 6, ~~63~~ 60 bytes

*-3 bytes thanks to Lynn's suggestion to use other separators than `/ \`*

```
->\n{&{S:g[.<[ャュョ]>?]=$/~7 x!$++*?+^-n~1 x(++$==n>0)}}

```

Try it online!

Curried function. Uses `7 1` instead of `/ \`.

### Explanation

```
->\n{     # Block taking argument n
  &{      # Return a block
    S:g   # Replace globally
    [.<[ャュョ]>?]  # regex for mora
    =$/            # with match
     ~7            # followed by 7
      x!$++*?+^-n  # if i==1 and n!=1
                   # should be read as (! $++) * (? +^ - n)
                   # +^ is bitwise negation like ~ in C
                   # ? converts to Bool like !! in C
                   # so ?+^-n is like !!~-n or !!(n-1) or n!=1
     ~1            # followed by 1
      x(++$==n>0)  # if i==n and n>0
  }
}

```
> 1 votes

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