title: Print a Ternary Value

text:
# Question
Title: Print a Ternary Value
Put simply, you are to print out the following number:

```
0202020100110020122120012121100120121020202100012110002002010110211221012021112010200012112021220120022222102211121110110201220020202001111212210010100222100112101201122100222120201002002020200011110002211002202100022210212020112002020000120222111121112002112101000011112021202002210220022121002011021000202102101010210220022011011210102021110111212122201122021101211110121100111110122110110201011100022000212022020110211221022001201211120110221212221012220101121222011202112012221010212021120022110020022202020212022222012000012111001022021211110221211001201020202020011122222010010112222002010220111111111101010220120110010102100211000120111022212000220210121222000020212112010102012210201021022020202102102002011100211022101011202222111120100000021221101221220220200102010010021110120012202111012000100021102111102220102021100021001010020020001001222220121221122100102020000000221101220111201210200212111010211122211011210012020010012110110021221010121121202220001112220120221112001021001211112211110112212100001212200021111011200010120221010201110201121021002201221111210102010200200210112020022102110212020112111000121001021202101012000112210101112122220120012022121202101110221120012122120220120010122102110102002222120201102002111100001021001121100211122200011102122022110122000102212201111020200010222211002210021200202210102022221022222101121020102100100111221102211100102000211010012201121121220122021122102201000011221122101101111201102120001002012211020211122102002211111121222112110222212012201221111222010100101120022022111002012122112201212201011022212100010001022010102100120112001012110202210101220021102112210122210010202011211010002122111111221121222002211200201122010022021011110112111020102102001110000201111222220120011111112102212011200021210100210100010

```

This is a randomly generated string of zeroes, ones, and twos. It is 1777 characters long. You may be asking: what makes this challenge interesting or unique?

In normal text compression you would be able to get this down to roughly 29% of its initial size. However, if you were to use a base-4 compression - i.e. using two bits per character - you could actually get that down to 25% of its initial size. The point here is that simply compressing this file will likely not be enough to win this challenge. And, base-4 or base-8 (etc...) compression may not actually be the best solution, because no powers of 2 can be evenly divided by 3. So, you will need to get creative!

# Other

-You are allowed to have a trailing newline after the output

-This challenge was inspired by this question and, while it is true that the premises are largely the same, the biggest and most important difference between the two are that this challenge in not in a friendly base (the linked question is effectively in base-4, which makes compression relatively nice).

-Other than the optional trailing newline, you must output the string/number exactly (i.e. no switching those characters for different characters), as this is

# Scoring

This is . Shortest code in bytes wins! \[If you wish, you can also try to solve this in as few characters as possible - but make sure you still include the byte count\]

# Answer
> 10 votes
# JavaScript (Node.js),  ~~504 481~~  474 bytes

Builds a BigInt from a string encoded in base 126 and converts it to base 3.

Because the data string contains many unprintable characters, it is not shown at all below.

```
_=>0+Buffer(`...`).reduce((n,v)=>n*126n+BigInt(v-1),0n).toString(3)

```

Try it online!

The theoretical length of the string is:

$$\left\lceil\frac{\log(3^{1777})}{\log(126)}\right\rceil=404$$

Because a few characters need to be escaped, we actually need \\$410\\$ bytes to store it in the source.

# Answer
> 10 votes
# Charcoal, 356 bytes

```
”)∨➙γＯＺNh≕◧≧hO=↖Ｌaκ%mNπＣσm‽⌊₂α¶↷⁴Ｌ⁶→ＸγU<¡'²xP`Ｅ←≡¤≔`"⦃NoT3# <≔3P'Ｉ³i↨⁸~⭆ jＬγＤ≡vU[\Ｆ3^¹wＶ6？ξeλ4q⊕XＬHH`⪪CtFνS,{}z↗q"d⊙Ｍρ＆⁼Ｚqu¤ε‹⊙S4ＳＲ*=ＨＤ|νsＸ⁰±s⁹d#αj⧴σZηχº«⎚⌈UKa⍘⌈ＤＩχＲ>\₂Ｎψ ⊗w⸿◨Ｋ´*y↶/§◧?↖Q¶Ｘ＆rÀv⌊↘�§Ｇ≕ⅉβ8⁰Ｉ>∨FＱ¬|F↓&V⪫Ｍ⬤s›ＬïyWuＥ⸿◧H)*⎚↓'kψ‽τ⁻≦lSl∕»RιPζxqv⮌PiＰγ·¿0v∕)¦≦¶=｜w¬!▶¬G⭆iTwＱL↘`×Ｉ↨"`T＆“κh⭆&ι]⊙₂✳→V⊞¶⊖ê{✂wP#⟧⧴f➙<ε<J+→₂→f¹F´ê⪫✂ξ#!We≦qÀηl⁶²∕6m≕▷8χo；wＺ3Xσ≡�+

```

Try it online! Link is to verbose version of code, which is just a Print statement of the original string, which the deverbosifier helpfully compresses using the best supported compression algorithm, which in this case I think is converting from base 3 to bijective base 255.

# Answer
> 6 votes
# Google Sheets, ~~674 635 624~~ 426

Closing parens discounted.

Column A: Padded original number up to something of length divisible by 10, then converted each 10-character chunk into a number. Then converted that into a unicode character (using `UNICHAR`):

```
Ȣ
僂
�
栩
㦱
讛
ꎫ
휾
莡
쉹
苼
䢸
⑅
㦚
紗
ᱨ
竾
횂
㙓
㤁
侏
펵
뫁
艁
ⶂ
败
覤
疒
᠃
�
惦
愮
援
媉
㿂
郸
껙
殰
犅
␱
佭
蟷
䅑
໑
ꘒ

嫌
秿

䂥
勣
굑
�
貇
뀓
�

൉
ᫀ
켑
♱
嚪
ꕈ
떹
葜
脄
ぎ
㪳
垈
㛠
㦸
㕏
㾈
⣏
甒
᚜
�
ઍ
ᕂ
ㄲ
聸
涠
킙
گ
ᆹ
ᄎ
쮾
῵
ࠉ
ꛏ
㖼
⃌
欎
ꬲ
橧
뛕
衠
罡
삼
刜
뿪
裀
췒
⟨
놢
焠
㲪
쁾
ꑉ
럧
ퟬ
걣
ԓ
욾
魕
娑
꠲
쥼
溚
郗
⬙
懦
䱽
汹
䵉
⤩
缶
捳
崉
�
㣿

ᗩ
뛼
믬
笠
俥
뺡
Ὡ
᭰
썴
꾋
ꉟ
쏧
珴
聼
镄
繷
쁁
�
�
�
嗍
ឭ
ዟ
錃
夶
䷙
큇
ⰲ
⻁
圻
淅
韫
㟕
ފ
眪
쾺
㟩
䚜
媤
⁽
暾
耏
೑
敎
ݥ
㳃

```
* `B1` \- `=RIGHT(JOIN(,ArrayFormula(BASE(UNICODE(FILTER(A:A,A:A>0)),3,10))),1777)`
    + Convert A1 back to unicode numbers, then back to Base 3.

## Supplementary Formulae

I added these because copy+paste from the code box drops some characters.

* Padded original number (`A1`) with this formula:

```
=REPT(0,10-MOD(LEN(A1),10))&A1

```
* Converted using this formula, where A2 holds the padded number.

```
=ArrayFormula(UNICHAR(DECIMAL(MID(A2,SEQUENCE(LEN(A2)/10,1,1,10),10),3)))

```
* Byte count done for column `A` with this formula (=347):

```
=ArrayFormula(SUM(LENB(A:A)))

```

# Answer
> 6 votes
# 05AB1E, ~~360~~ 359 bytes

```
0•1"ôÒ^¯ùg©ÞPò–>Δª7н8l9ëŒƶuÚ*'ΛZúΩиç“À¨'Õƒ†ìà\¬Õ¯zʒbGmK_¤Rï1αÉAΛ÷₂*ƶÃ/¿ž-‘`Ž¾η¥ÓEÛ‰±þ»¡{ÒõÆΩf`ÆнÜmÙ*Ë-γèΩ²IĀSRÉ×₃"!ÒVNÑc¥à8¡{øs²†?тλ¢[)¿„œQ6ýÕl…cüÖ₄δðnøÍθds—'>oÉÙÛÄÈ‰Ó|5&þMbǝ¥₄ü¿ö-.ã Äh›µ„çŽœLΩ.Ÿv¹[ïüãDÞw[š²ð,ê∊R–=¿
Ý°–Oôìʒi5ÛtWƒв²ÞΔgîγz₆/pÈv£A~y≠B₄Ý]®©₅^ïr÷Á©Ñþ‰”»«é¸₆Θ™šEΓCΘ‘
™ÕâGε¼"Äθv4¼[F+„ûW¿–ãîvîð._e!ð‘h 4DŽÕ‡ZΩĆ1·ÜY“¨â²Œ₃;öŸrÐÿRƒδ¾ñI₆Œ@Θ˜ß!™∊G¨u[d•3B«

```

Try it online!

Ah yes, 05AB1E. The language designed to perform well with base conversion challenges. Shamelessly compressed using this trick by Kevin

*-1 thanks to @mypronounismonicareinstate*

# Answer
> 5 votes
# brainfuck, ~~3178~~ ~~3073~~ ~~3072~~ ~~2961~~ 2955 bytes

-6 bytes thanks to Jo King

```
++>->>->->->>->>+>->->>->>+>>+>->->->+>>>->+>>+>+>->>+>>>>>>>>->->+>>->+>+>+>+>+>>>>>->+>->->->->>>>->->+>->>+>->>->+>->>>>+>>>->>>>>->>+>->+>+>->->>->+>+>>>->+>->->+>>>+>+>->->+>+>+>>+>>>+>+>>>>>>>+>+>>+>->->->>->>>+>>>->+>->+>->>->->>+>+>+>>->>+>+>>>+>->>>+>->->+>+>>->>->>+>+>->+>->>>+>>->>->->+>>>->+>>->->>+>->>->>->+>+>->>->->->>->->->>+>>+>+>+>->>>->>->+>+>>+>>->+>+>>>+>+>>+>>->+>->->>>>+>+>->+>+>->->+>>>->>->->>->>->+>+>+>>>>>+>+>>->+>+>>->+>>+>+>+>+>->>>+>>>+>+>+>>+>>>>>>>+>+>->->+>->>+>+>>>>+>->+>->>>+>+>>->+>->->>->->->+>>+>->>>->+>>>>>->>>->>+>+>>>+>+>>>->->->->>->+>+>->>+>+>>>+>->+>+>>->+>+>>+>>>+>>>->+>+>>->->>->>>+>->->->+>->>->->>>>+>+>->>>+>+>>>>->->>->->>+>->>->+>->>+>>>->>+>+>+>+>+>->>+>+>+>+>->+>->>->>+>+>->+>->->+>>+>->->>+>+>->->>>+>+>+>+>->>->->->+>->+>->>>>>->+>+>>+>+>->>->->->+>+>>->>>+>+>->+>+>>+>->>>>->->->+>+>+>>>>+>->->>>+>>>->->>+>->>->->->->>>>>+>->->+>->>>->+>->+>>+>+>+>+>->->+>->>->>>+>->>+>+>>->>->->+>>->+>+>->+>>+>+>>+>>->->+>>>+>+>->>>>->>+>->+>>+>>+>+>->+>>->->+>>->+>+>+>+>>+>>>>->>->>+>+>>>->->->+>>->>->>+>->+>>+>->>->->>+>>->->->>>>+>>>->+>->+>>+>->>>+>->>+>+>->->+>->+>>>->>+>->->+>->->+>->>->+>->>->>+>>>>>+>+>>->+>+>->->>+>->>+>>>->+>->>>>->+>->>->>+>+>->+>>->>->->->+>>>->>>>>+>->->->+>+>>+>>->->->->>+>>+>+>>>->>>>>+>+>>>>>+>>->->>+>->>->->+>>>>+>+>->+>>->+>+>+>>>>->->->+>+>+>->+>>+>>>+>>->>->>+>+>>+>->->>>->>>+>>->->>->->+>->+>>->->>+>>>->>>+>+>+>>>>+>->>->>>>+>>+>->->+>->>+>>->+>>>>->+>+>>->>>+>+>->->->->->->->+>->+>->>->->>+>+>>>+>+>>+>>->+>+>+>+>+>>->->>->->->+>->->+>->->>->>->->>+>->->->>>+>->+>->>->+>+>+>->>>>>+>->>>+>->->->>->->->+>>->>>>+>->+>+>>->->+>>->>>>+>->->>->->>->+>->>->->+>->+>+>->+>+>>+>+>>->>>+>+>>+>->->->->->->>->+>>>>>+>+>+>+>->+>>>->>->>+>+>->>>+>->->>>>->+>->->+>->>+>->>+>->+>->+>->+>+>->>+>->>->+>->>+>+>>->+>->>->>->+>>>+>>+>->+>->->->->+>+>+>>+>>->>+>->+>+>->->->+>>+>+>+>->>>>->+>>->->->>>+>->->>+>->>->>->->>>->+>>->+>+>->>->>->>>>>>>>>>>->+>+>->>->+>->->+>+>+>+>>>->>->->>->+>+>+>+>+>>>>->->+>->+>->+>->+>->>->+>>->->>>+>>+>+>->>>>>+>>+>->+>+>->>->->>>>+>>->->->->+>>->+>+>+>+>+>->+>>+>->+>->+>->+>+>+>->->+>->->>>+>+>->->+>>>+>->+>>+>->>->>+>+>+>>->+>>>+>->+>>>->+>+>+>>+>>>->>->+>+>+>>->>+>+>+>>+>>+>+>->>>->+>>>>+>>->+>>->->+>+>->>+>+>>>+>->>>->+>->+>+>->+>>+>->->->+>+>->->->>>>->>->+>->>>->>>+>+>>->>>>>>->->>>+>>->>>>>+>>->>>+>->+>+>>>->+>+>+>>+>>+>>>>->>>>+>->+>->>->>+>>>->>>->+>+>->->+>+>->>+>->>->>->>+>->>+>->+>->->->>+>->>>->+>->->>+>>+>+>->->+>+>->>+>+>->->+>->+>>+>->+>>>>>->->->->>->>+>>>+>->->+>>>>+>>>>>+>+>+>->+>>->->->->+>->+>->->+>>>->+>->+>>+>->>+>+>+>->->->>+>->+>+>->->>>+>+>->->->>>>>->->->+>->+>->+>->->+>->->>->+>->+>>+>+>+>->->>+>+>>>->+>>->>+>>>->->>+>+>+>->->>->>->->>+>+>>+>>>>>->->+>->+>->+>->->+>+>>->+>->>>->>>>+>>>>+>+>->>+>+>+>+>+>->->+>>->+>+>>+>->+>>>+>>->->->+>->>->+>>>>+>->+>>->>+>+>>>+>->>>->>->+>->->+>->->->>>+>>->->->>+>->+>->+>->>+>>->+>>->->>>+>>+>>->->+>>+>+>>->+>->->>>->->>->+>->+>->+>---[>-[<+>-----]<.[-]<--]

```

Try it online!

It first stores the number backwards then it adds 49 to the cell before printing it then goes to the cell before that and it does that until it reaches `++`

# Answer
> 4 votes
# MATL, 438 bytes

```
'1ye}Ju:]rrY6|H!R^ 4Fl^/z*F|`[=I"5A3nYj](eaiU/+1dxw5}MWfh-G6uV9@/jQy_)I6D@e?f+5*!4xOE^1+=\.Op`=?K8Wurme+#3F}+v*n\Hd<2e")H*JzcUR.1fg{q 3b+i(xtuj-0]hTrr@<wj?y$uj&2zstc=uDv}p|1_IM1$I)o^p*~~WE/kkG?R<QS=x{%Y5EMLCUVk%$s69A#mHm,6RjN`*tI\,{10o,0zQ_<LK+\uG2p*y\=-vQ?n*1W~`sjgmR2c>tfZ%.vWk=eL"JP{QP /)gR{Et\hjwx dUZVz%\4utDRexe=KI $tv<,P8U mDxuTgi%44;6FYN`i/|HQ&9gpLOtWu<7:[)AH:t?h"h7N#j\X;m(_(L+h!2 zVA"NzMb!`:}|9>mi>s||MrxQE/9M&6:S+.P{Z}n'T210VZa

```

Don't try it online! (it times out).

Here is a GIF file of the program running with the offline MATLAB compiler:

### How it works

```
'1ye}Ju:]rrY6|H!R^ 4Fl^  ···  S+.P{Z}n'   % Push this very long string (not shown in
                                          % full; it contains 427 characters plus the
                                          % 2 enclosing single quotes)
T                                         % Push true. This indicates the that origin
                                          % base is the 95 printable ASCII chars
210                                       % Push number 210
V                                         % Convert to string. This gives the
                                          % destination base, '210'
Za                                        % Base conversion. Implicitly display

```

# Answer
> 4 votes
# Pyth, 361 bytes

This has too many unprintables for TIO, so here's the hexdump:

```
00000000: 746a 6b6a 4322 01bd bf32 7574 a357 55f7  tjkjC"...2ut.WU.
00000010: f4ca 74e0 9fbf 89f3 58ad 59c8 798b b009  ..t.....X.Y.y...
00000020: 60bc 0f8a 71f4 a90e da7b 61a6 6145 9a5b  `...q....{a.aE.[
00000030: 2f16 8968 611f 9b8d 75fb a9f0 0308 7d38  /..ha...u.....}8
00000040: 9acd fdf3 53b1 e7be 2fa4 1ce2 6870 fcae  ....S.../...hp..
00000050: 51df 0aec 521b e506 bb84 df0b f439 2917  Q...R........9).
00000060: 7303 8ac3 0d48 489c 727c 3712 4e66 2ed6  s....HH.r|7.Nf..
00000070: ec54 c5e3 eb14 4b10 8a10 6974 683b fbcd  .T....K...ith;..
00000080: 9976 1731 c976 2d60 b2d8 c644 7641 bcd2  .v.1.v-`...DvA..
00000090: acfd b4da 6026 341f 8994 7cc8 ef94 ff58  ....`&4...|....X
000000a0: 5b47 47c8 a880 1a8e b8ae 385f 632a 306c  [GG.......8_c*0l
000000b0: 4d64 9b80 4e7e fb93 2c51 7484 0e53 2d7c  Md..N~..,Qt..S-|
000000c0: 9e46 10ac 9a6d 3d2f 0237 3fa4 9ae8 056f  .F...m=/.7?....o
000000d0: 5e2e aca5 ac4b 424c f151 d152 094f 8f57  ^....KBL.Q.R.O.W
000000e0: a644 f6ad 7032 f28c e937 3d2c a65f b434  .D..p2...7=,._.4
000000f0: 8279 4ab3 b349 ec8e 0244 44db 50e6 5426  .yJ..I...DD.P.T&
00000100: b177 d3b0 5f95 6d98 7b7f ba7e 0bac 1131  .w.._.m.{..~...1
00000110: 6f77 2710 c024 05d9 88e2 7194 fb5f 00d6  ow'..$....q.._..
00000120: 6204 d12b 5620 0020 3ab6 23ea acdd 05cf  b..+V . :.#.....
00000130: 254e ebed 0448 f957 64a7 47f8 35fb 368f  %N...H.Wd.G.5.6.
00000140: 203e f9c6 aa02 a9f4 4618 c9da 48d0 56d3   >......F...H.V.
00000150: 29ac f370 2178 6d05 e2dc 2985 aca1 8be9  )..p!xm...).....
00000160: 082c c9a6 dfcd 5e22 33                   .,....^"3

```

To run this, put the above hexdump in `a.dump`, run `xxd -r a.dump > a.pyth`, and then run `python3 pyth.py a.pyth`, using `pyth.py` from the Pyth repository.

Basically, the program is

```
tjkjC" ... "3

```

The long string is equivalent to the ternary string with a 1 placed in front, converted from ternary to base 256.

`C` converts the string from base 256 to an integer, `j .. 3` to a ternary list of digits, `jk` to a string, and `t` removes the leading 1.

By sheer luck, this has no characters that need to be escaped (e.g. `"` and `\` in certain cases), so it's shorter than it would have been otherwise. Unfortunately, Pyth's base conversion takes inputs backwards of the sensible choice, so that adds two bytes, and the required output is a string, not a list of digits, which adds another 2 bytes.

# Answer
> 3 votes
# Rust, 551 ~~566~~ bytes (404 ~~405~~ byte code + 147 ~~161~~ byte decoder)

```
fn main(){for x in br#"..."#.chunks(5){let mut v=x.iter().fold(0,|a,x|a*127+*x as u64-(*x>13)as u64);for _ in 0..5*x.len()-3{print!("{}",v%3);v/=3;}}}

```

Formatted:

```
fn main() {
    for x in br#"..."#.chunks(5) {
        let mut v = x
            .iter()
            .fold(0, |a, x| a * 127 + *x as u64 - (*x > 13) as u64);
        for _ in 0..5*x.len()-3 {
            print!("{}", v % 3);
            v /= 3;
        }
    }
}
```

Rust source code is always UTF-8. Looking at the table of encodings for UTF-8, it becomes clear that ASCII contains the most amount of information per byte (7 bits per byte), while the mult-byte encodings all are less than 6 bits per byte.

Because Rust doesn't have arbitrarily large integers, we need to fix a length of bytes we transform at once. In `k` bytes, we can encode $$\lfloor \log\_3 (k\cdot7) \rfloor$$ *trits* (base 3 digits). Looking at these values without the floor, we see that we get pretty close to the optimal information density for `k=5` (4.4 trits/byte vs the optimal 4.4165 trits/byte (for 7 bits per byte)). That means we will encode every 22 trits as 5 bytes.

To embed the data in our source code, we can use the raw byte string literal syntax (the `br#"..."#`) to get it as a `&[u8]` instead of a `&str` (byte string), and not needing to escape special characters. I stumbled into the problem that a raw CR (not part of a CRLF sequence) is not allowed in a raw byte string. So I just added 1 to every byte that was above the ASCII for CR when encoding, and subtracted it again. Fortunately we can still fit 22 trits into `5*log2(127)` bits :)

Then we just need to avoid printing extra zeroes at the end, which I avoided by checking if the second byte was 7 (which only occurred in the final 5-byte-tuple).

**EDIT**: The first byte of the last 5-byte-tuple is zero. We can leave it out to get the same value for `v`, and then we can use `5*x.len()-3` to switch from printing 22 trits to 17 trits at the end, also making the decoder shorter. This also means we are at the theoretical optimum code size! (404 bytes vs 403.0055 (rounded up to 404))

Here's the encoded sequence as a hexdump:

```
00000000: 2439 7e78 2947 2e4b 167f 4608 6e70 135f  $9~x)G.K..F.np._
00000010: 1741 3f2d 6f1a 226b 641e 782c 1e76 752d  .A?-o."kd.x,.vu-
00000020: 0416 4650 045f 473d 3c4e 5229 731b 2961  ..FP._G=<NR)s.)a
00000030: 007f 5b6d 7a71 6a05 3139 7818 2557 747e  ..[mzqj.19x.%Wt~
00000040: 2347 032d 256a 2f4e 7658 6774 4a5a 3700  #G.-%j/NvXgtJZ7.
00000050: 4125 466b 6a2e 5f73 2845 1402 0642 3034  A%Fkj._s(E...B04
00000060: 374d 3902 6379 3f65 5111 2d3c 4453 7540  7M9.cy?eQ.-<DSu@
00000070: 683c 0629 4f00 2815 4d5a 255e 513b 3a45  h<.)O.(.MZ%^Q;:E
00000080: 1f75 3252 087d 0725 273a 3a35 297e 142d  .u2R.}.%'::5)~.-
00000090: 4461 3a3d 086a 5643 4312 2347 305e 7b44  Da:=.jVCC.#G0^{D
000000a0: 1a4a 0e64 4c00 1b6f 0766 2c53 192a 4526  .J.dL..o.f,S.*E&
000000b0: 2f0e 6d2e 3e29 2020 320f 1e59 5a2b 6324  /.m.>)  2..YZ+c$
000000c0: 2f6f 4000 051c 7503 5459 473e 554a 2040  /o@...u.TYG>UJ @
000000d0: 6034 445a 6c53 4637 0c1f 4a14 0750 5313  `4DZlSF7..J..PS.
000000e0: 6e08 3500 3615 0355 6c4f 7d64 2f25 594b  n.5.6..UlO}d/%YK
000000f0: 5666 310e 3d4d 2a54 761d 5f09 627a 3763  Vf1.=M*Tv._.bz7c
00000100: 3647 0302 2057 1904 7a2d 0003 5b06 5a05  6G.. W..z-..[.Z.
00000110: 4d4c 3a1d 7558 392a 1643 2359 3270 3e1c  ML:.uX9*.C#Y2p>.
00000120: 4315 1501 7a4a 3354 1f6a 0f29 6f19 1947  C...zJ3T.j.)o..G
00000130: 172a 6563 0634 442f 4853 3672 1014 6b49  .*ec.4D/HS6r..kI
00000140: 4319 0e12 7903 6a56 467d 5a0f 1313 4658  C...y.jVF}Z...FX
00000150: 526a 5159 362f 5614 3a53 5c6d 2c16 1343  RjQY6/V.:S\m,..C
00000160: 6058 7410 2c17 2d65 5b13 633f 2331 7440  `Xt.,.-e[.c?#1t@
00000170: 3b1c 0160 765d 1355 6950 3e65 1856 156c  ;..`v].UiP>e.V.l
00000180: 7a09 6464 2529 2161 496b 7103 583e 712f  z.dd%)!aIkq.X>q/
00000190: 070e 557f                                ..U.

```

---

Old code (without the removed null byte at the end):

```
fn main(){for x in br#"..."#.chunks(5){let mut v=x.iter().fold(0,|a,x|a*127+*x as u64-(*x>13)as u64);for _ in 0..(if x[1]!=7{22}else{17}){print!("{}",v%3);v/=3;}}}

```

Formatted:

```
fn main() {
    for x in br#"..."#.chunks(5) {
        let mut v = x
            .iter()
            .fold(0, |a, x| a * 127 + *x as u64 - (*x > 13) as u64);
        for _ in 0..(if x[1] != 7 { 22 } else { 17 }) {
            print!("{}", v % 3);
            v /= 3;
        }
    }
}
```

# Answer
> 3 votes
# Raku, 431 bytes

```
say 0,:127[q[ ... ].ords].base(3)

```

Try it online!

Uses conversion from base 127. Since TIO can't really handle carriage returns and to a lesser extent NUL bytes, I've generated and then eval'd the program in the header. I'm lucky that the generated string contained three pairs of `[]` so I was able to use the `q[ ]` quoting construct.

# Answer
> 2 votes
# , ~~454~~ 419 bytes (360-byte string + 59-byte decoder)

```
cat(head(rep(utf8ToInt("I¸{A´ ;ÐÄ` 3’<ˆp>Æ¾]Ò‰}HµÁ‡©+\\m’'šdI°‚Y%ÊúÞ7I\\‰‹Ú(5ÆEÒ&Ì3`NhN·2žJ}¤ø¨~… 5o}F‚URë€©æ¿Œwäo¹¥½QBi›–Ó·ÃRÿ:zW¡wÓ—ÃD“è,ýFé†ƒ0;asO„ô%Ï¬à¹HÐsëÄÐGew,É×¸ªAíDF*ƒ´ÅmO×[ryË*)ÿ?ÛaÁ\rñ§ŒÐS|ØñŽ< {©n£÷6êY•L¡ª}õâ#}°<Í¼GÑ%ªŽqE\"&OÞ8yuM:9hø´Z›4óôêð|·ô»¶‚bÓØå„¨Ôåwé°]{Ì–XrúÿlqLbªYa±|@â¨’Vªïk˜RÀØÐY‡ þÀAŠ¹–È{?Û?¹x(vic7-ï@OÛoËI(ã†ó¬Yµ‘fMƒ¡FÐ4‡ý•†ŸÝ”ße(d")-13,e=5)%/%3^(4:0)%%3,-3),sep="")

```

Try it online!

*(Note that copy-pasting within TIO seems to convert some single-byte utf8 characters to multi-byte versions, resulting in a higher reported byte count. See code footer for check that all characters are indeed encodable in single-byte representation. If anyone can suggest how to avoid the utf8 recoding upon copy-paste within TIO, I'd be grateful!)*

**How?**

The general approach is to encode the base-3 string as a base-243 (=3^5) number, represented by a string of utf8 characters in the range 13-255. The compressed string therefore represents compression to log(3)/log(243) = 0.2 of the original string length. However, to type the string into a program (or, put another way, to be copy-pastable), we need to escape the '\r' (carriage-return), '"' (quote) and '\\' (backslash) characters. So the final average compression for base-3 strings is 0.2 * (243+3)/243 = 0.2024691.

In the particular case of the string in this challenge, we need 356 base-243 characters plus 4 escape '\\' characters = encoded string length of 360 single-byte characters.

Since  cannot natively handle arbitrarily large integers, we decode character-by-character, which is made possible by using 243 = 3^5 as the encoded number base: so every 5 base-3 digits are independently converted to a base-243 number, represented by a single-byte character. See the TIO header for the code to perform this step.
The R decoder is 59 bytes, giving a total size for this particular string of 419 bytes.

```
cat(                                # output...
  head(                             # all first characters of...
    rep(                            # repeats of...
      utf8ToInt("_string_")-13      # utf8 codes of _string_ minus 13...
      ,e=5)                         # x5 each...
    %/%3^(4:0)%%3,                  # converted to base-3 digits...
  -3)                               # except last 3 characters...
,sep="")                            # joining digits without spaces

```

# Answer
> 2 votes
# Ruby \+ `bases`, 588 bytes

```
$><<?0+Bases.val('43ur6p5v87byc6oertnvopy75perajuyj6vvdx4dirisox7zjv1cn2viaoe4ta62al6phj2yiy8wqrx1yki34ihtmasmgf42gboode2gkhqu50yw3ttiblo95td8gb692jshoixb66h1mmcrfekd154h5gvo9b0p98hy6dj8oeq1nn9hihzyah1fmb9i9oqf38x8xrgabaldnxf5d1okwf7gagydqlctacv9x9r8shhnkrcj7xf34rgj3c6gb54kd8apxealduij2tecvzd31re7u1kc0ddesug9zp064abj4yrnoydre17zrfmjlpcho43146gase8zk9kkl348mopxx3qkcdepo3svrxtezb4jra4bzdjn1tytt76g74hroej9zaswy9zb0q55p3urqcbjqylcjhtxjtiadvmosf2ytxznjh3980mxkntwz4thp10ldkowsxymmhpuvbw5o0wh2t5uke1k896sjb4e07txzory0mgqj8jsrupiuvj4x19ncfyo2rspdx4u5wryx6lrlo1bncpi3').in_base(36).to_base(3)

```

I tried converting across multiple bases, and got the shortest string at base 36. This is a pretty simple number conversion.

Try it on repl.it!

# Answer
> 0 votes
# Jelly, 361 bytes

```
“¥ḷɗ4ḄṄƥƭ&Ȯ¡ƲẓḃsÑ}G⁸ƲkẈ$ọ,Ŀ²|6ñĿṘỵHṬżṁm;=İḥɼḶɲ8Œ5Ɓ).yṙṛ7ṫʂṃ¶\Æ\gḷ¢KÞŀȮ]zƇẎẠ×ȷ÷;|Dy[¬Çe⁶Mỵ}ʋ⁵Ż;⁷ɱċlı7¦ĊĠƈỵOḄK³Ñ"}ȷɗİʠỤ,ɓÐṣẓẠẎDỊxĊċ0€⁷ɠ,wⱮȧ)u÷⁷⁵@ṬƓƑLị?`ẊạʋɠḂȧĖ>xRḢ"ls⁾Ạ"×Z⁴Ḃq^ẈƁç⁾ỴM!Ƥzẏ¹G6µ-ż0zĠ⁾Ḅ€Mɦ?ĖḞ/eẸ¹/⁼%Ġ Xẹxȷ`1ḄÄkÄ;Ṫɲ<fLW&Yɲ¡U6ẏu3ƇAɱỤḶWF°SS⁸ṪvC[`°½ḍẏ¬Äạr¿pFR0ḋ@#⁷Ʋyc\⁸ÑQÐẉⱮ#BĠƲ§×ỵMẎṾɠẆ⁹ḲlƲ5ḥÐ}ṘṄḟ|(Ẓ]¶J¿Ȥŀ;µỊ(ȤỌ⁾ÆV²ċ#ɓ¿ŀmYœʋƈḊḟ¬ŀ*ỴḂĿq⁴ḣ¹3¡r⁽Ẋø*+ƇṄỌRƘ’b3ŻṾ€

```

Try it online!

Mostly for completeness. Jelly is slightly worse at compressing than 05AB1E because it uses base 250 instead of 255, but on the other hand, it seems to take fewer bytes to display the number, though it's still 2 bytes longer overall.

## Explanation

```
“...’b3ŻṾ€   Main niladic link
“...’        The integer in base 250
     b3      Convert to base 3
       Ż     Prepend a zero
        Ṿ€   Unevaluate (convert to string) each

```

# Answer
> 0 votes
# Deadfish~, 3366 bytes

```
{{i}ddddd}ddciicddciicddciicddcicdcciccdcciicddciciccdcicddccicicdcicdccdccicicddcicicdcdciicddciicddciicdcdcccicicdccdccciicddcciicddcicdciccdciicdcciccdcdcicicddciicdcccicddcicdciicddcccicicdccicddciicdciccddcicicddcciicccccdcdciiccdcccicdcccdciccdciicddciciccddcciicddciicddciicddcciccccicdciccdcdccicdcicdcciicccdcdcciccicdcdcicicddcicciccdcdcciicccdcicddciicddcicdcciicddcciicddciicddciicddccciccccdccciiccdccdcciiccddciicdcdccciicccdcdciicdcicddciicddciccicddcciicddciicddccccicicddciicccdccccicdcccicddcciicdccicdcdcicdcccciccccicddciicdcicddciicddcciiccdcdciiccddcciiccdcicdcdcciicddciccdciicdcdccciicddciicdcdciicdcdcicdcicdciicdcdciiccddcciiccddciccdciccicdcdcicdciicddciicdcccdcicccicdcicdcicccddcicciccddciicdccdcicicdccccdcicicdccdccicccccdciciccdccdciccdciicddcicdcicccdccciiccddccciicdcicddciiccddciicddciccdciicdcciccdcdciiccddccicicddcicicdcccicddciccdciiccdcicdcicccdcdcicicccddcicdciccicdcicccddciccicddciicdccicddcicicccdcdcicdciicdcicddciicdccicddcciiccdccdcciicddcciicccddciicddciicddciicdcicddciicccccddcicicddccccicicdcccdccicdciiccddciicdcicdccccdciiccdcicdccdccicicddcicdciicddciicddciicddciicddccicccicccccddcicdccicdcicciccccddcciicddcicdciiccddci{c}dcicdcicdciiccddcicicddciccdccicdcicdciicdcdcciicdccdcccicicddcicccdciicccdcicddccciiccddciicdcdcicicdcicccddcccciicddciicdcicdccicddcicdcicdciicddciciccdcdciicddcicdciicdcdciiccddciicddciicddciicdcdciicdcdciicddcciicddcicccdcciicdccdciiccdcdcicdciccicddciiccccdccccicddcicdcccccciicdciccdccdciciccdciccddciiccddciicddccicdciicddcicdccicdcciicdcccdcicicddcciciccddciicdcccdcicicddcccicdccciicdccdciicdccccdciicccddcicdciicddciicdccdccciicdcdccicdcicdcciicddcciicddcccicdccicicccccddcicicdciccdcciccdcdccicdciicddciicddccccccciiccdccdciciccddcicccicddcicicdcdciicddcciicdcicdcccdcicdciicdcccicccdccdciccicdcdccicicddciicddccicdccicicdccdciccdcciicdciccdcdcicdcicicdccicdcicddciicccddcccicccicccddcicicddciiccdcccicddccicdciicdcdccicicdcccciccdccccdcicciccdcicdcdccccicicdciccddccciicdccccdciccicddcccicdcicicddciiccdcdcicdciicddcicccdciicddciccicdcdciicdcdcciiccddciciccdccccicdcdcicdciicddcicdciicddcciicddcciicdcdciccicddciicddcciiccdcdciicdccdciicdcicddciicddciccicdcccdcccicicdcdccicdciicdcicddciicdcdcicdcicicddcccicciccdcdcicdcicccicdciccccddcicicddccicicddciiccdcicdcicddciicdcdcicccdciiccdccicddccicicdciccdcicddciiccddcicicddccicdciciccdcdciicdccdcicdciicddcciiccccdcicddciicddciccdciicddcciicdccccdccccicdciicdcdcciccicdccdcciicdcccicccddcccicccdciicdciccddciiccdccdciciccddcccicdciiccdciccddciccccdciicddciicddcccicdciiccccdccdcciiccdcdcciicdcicddcciicddciiccdcdcicdciicddciiccccdcdciicccccdcdciccicdcdciicddcicdciicdcdccicdcciccciccdccdciiccdcccdccicdciicddccciicdccdcicdcciciccddciccicdccicdciccddciciccddciicdcciccdcdciiccddcicdccccicciccdcciccdcdciccdciccccicddciccdciicdcicddcccicdcciicddciciccdccdciicddciicdccciccdcdciicddcciiccdccccccicdcicccdccicdccdciiccccdcicddciciccddciciccdccccicccddcicdcicdccicdciccicddcciiccddciiccdcccdcciicddcicicdciccdcciccddcicicdciccddcicdciccdciicccdcicdcdcccicdcccicdciiccddcicdcicdciicdcdccicicddciccicddccicdcicicdccdciicddciiccdcdcicdciciccddcciicdccdciicdcciccdcdcicicccdcdccicdciicddciicddciccicdccdcicdccciicdciccdcccccciccdccicdcicccddcciiccdccicddcciicddcicciccddcicdcciiccddciicdcdciccccdciccicdcccdciicddcicdciicdcdciicddccicccdcccciicddciccccicccccddcicicddccicccccccicdcdciiccdcicddciccicddccciicdcicdcdcicdcciicdcdcicdcccicdc

```

Who cares about compression?

# Answer
> 0 votes
# Deadfish~, 3354 bytes

```
oiioddoiioddoiioddoiodooioodooiioddoioioodoioddooioiodoiodoodooioioddoioiododoiioddoiioddoiiododoooioiodoodoooiioddooiioddoiodoioodoiiodooioododoioioddoiiodoooioddoiodoiioddoooioiodooioddoiiodoiooddoioioddooiiooooododoiioodoooiodooodoioodoiioddoioiooddooiioddoiioddoiioddooiooooiodoioododooiodoiodooiiooododooiooiododoioioddoiooioododooiiooodoioddoiioddoiodooiioddooiioddoiioddoiioddoooioooodoooiioodoodooiiooddoiiododoooiiooododoiiodoioddoiioddoiooioddooiioddoiioddooooioioddoiiooodooooiodoooioddooiiodooiododoiodooooiooooioddoiiodoioddoiioddooiioododoiiooddooiioodoiododooiioddoioodoiiododoooiioddoiiododoiiododoiodoiodoiiododoiiooddooiiooddoioodoiooiododoiodoiioddoiiodooodoioooiodoiodoioooddoiooiooddoiiodoodoioiodoooodoioiodoodooiooooodoioioodoodoioodoiioddoiodoiooodoooiiooddoooiiodoioddoiiooddoiioddoioodoiiodooioododoiiooddooioioddoioiodoooioddoioodoiioodoiodoiooododoioioooddoiodoiooiodoioooddoiooioddoiiodooioddoioiooododoiodoiiodoioddoiiodooioddooiioodoodooiioddooiioooddoiioddoiioddoiiodoioddoiioooooddoioioddooooioiodooodooiodoiiooddoiiodoiodoooodoiioodoiodoodooioioddoiodoiioddoiioddoiioddoiioddooioooioooooddoiodooiodoiooiooooddooiioddoiodoiiooddoi{o}doiodoiodoiiooddoioioddoioodooiodoiodoiiododooiiodoodoooioioddoiooodoiiooodoioddoooiiooddoiiododoioiodoioooddooooiioddoiiodoiodooioddoiodoiodoiioddoioioododoiioddoiodoiiododoiiooddoiioddoiioddoiiododoiiododoiioddooiioddoiooodooiiodoodoiioododoiodoiooioddoiioooodooooioddoiodooooooiiodoioodoodoioioodoiooddoiiooddoiioddooiodoiioddoiodooiodooiiodooodoioioddooioiooddoiiodooodoioioddoooiodoooiiodoodoiiodoooodoiioooddoiodoiioddoiiodoodoooiiododooiodoiodooiioddooiioddoooiodooioioooooddoioiodoioodooioododooiodoiioddoiioddoooooooiioodoodoioiooddoioooioddoioiododoiioddooiiodoiodooodoiodoiiodoooiooodoodoiooiododooioioddoiioddooiodooioiodoodoioodooiiodoioododoiodoioiodooiodoioddoiioooddoooioooioooddoioioddoiioodoooioddooiodoiiododooioiodooooioodoooodoiooioodoiododooooioiodoiooddoooiiodoooodoiooioddoooiodoioioddoiioododoiodoiioddoiooodoiioddoiooiododoiiododooiiooddoioioodooooiododoiodoiioddoiodoiioddooiioddooiiododoiooioddoiioddooiioododoiiodoodoiiodoioddoiioddoiooiodooodoooioiododooiodoiiodoioddoiiododoiodoioioddoooiooioododoiodoioooiodoiooooddoioioddooioioddoiioodoiodoioddoiiododoiooodoiioodooioddooioiodoioodoioddoiiooddoioioddooiodoioioododoiiodoodoiodoiioddooiioooodoioddoiioddoioodoiioddooiiodoooodooooiodoiiododooiooiodoodooiiodoooioooddoooiooodoiiodoiooddoiioodoodoioiooddoooiodoiioodoiooddoioooodoiioddoiioddoooiodoiioooodoodooiioododooiiodoioddooiioddoiioododoiodoiioddoiioooododoiiooooododoiooiododoiioddoiodoiiododooiodooioooioodoodoiioodooodooiodoiioddoooiiodoodoiodooioiooddoiooiodooiodoiooddoioiooddoiiodooioododoiiooddoiodooooiooioodooioododoioodoiooooioddoioodoiiodoioddoooiodooiioddoioioodoodoiioddoiiodoooioododoiioddooiioodooooooiodoiooodooiodoodoiioooodoioddoioiooddoioioodooooioooddoiodoiodooiodoiooioddooiiooddoiioodooodooiioddoioiodoioodooiooddoioiodoiooddoiodoioodoiiooodoiododoooiodoooiodoiiooddoiodoiodoiiododooioioddoiooioddooiodoioiodoodoiioddoiioododoiodoioiooddooiiodoodoiiodooioododoioiooododooiodoiioddoiioddoiooiodoodoiodoooiiodoioodooooooioodooiodoioooddooiioodooioddooiioddoiooiooddoiodooiiooddoiiododoioooodoiooiodooodoiioddoiodoiiododoiioddooiooodooooiioddoiooooioooooddoioioddooioooooooiododoiioodoioddoiooioddoooiiodoiododoiodooiiododoiodoooiodo

```

Try it online!

The TIO link links to an interpreter I made in Python. The interpreter that already exists in TIO crashes since the code is too long.

First time using Deadfish~

---
Tags: code-golf, kolmogorov-complexity, compression
---


title: A problem of rarity

text:
# Question
Title: A problem of rarity
Given a positive input \\$n \> 0\\$, output the amout of two types based on their rarity. The two types are called \\$A\\$ and \\$B\\$, we know the followings:

* \\$n\\$ is a limited input and the maximum is \\$nmax\\$
* At the start \\$B\\$ is twice as rare as \\$A\\$
* As the presence of \\$A\\$ increade the rarity of \\$B\\$ decreases
* When \\$n\\$ = \\$nmax\\$, \\$A\\$ will be equal to \\$B\\$
* When \\$n\\$ is not \\$nmax\\$, \\$A\\$ cannot be equal to \\$B\\$
* The value of \\$A\\$ and \\$B\\$ cannot be decimal.

## Example

```
nmax = 10

n = 1, output = [1A, 0B]
n = 2, output = [2A, 0B]
n = 3, output = [2A, 1B]
n = 4, output = [3A, 1B]
n = 5, output = [3A, 2B]
n = 6, output = [4A, 2B]
n = 7, output = [4A, 3B]
n = 8, output = [5A, 3B]
n = 9, output = [5A, 4B]
n = 10, output = [5A, 5B]

```

Shortest code win.

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

```
m=>n=>[a=n/2+(n<m)|0,n-a]

```

Try it online!

# JavaScript (Node.js), 24 bytes

```
m=>n=>[b=n-(n<m)>>1,n-b]

```

Try it online!
> 6 votes

# Answer
# JavaScript (ES6), 28 bytes

Expects `(nmax)(n)`. Returns `[B,A]`.

(This is based on my current understanding of the task.)

```
m=>n=>[b=n/2-(n<m&~n)|0,n-b]

```

Try it online!
> 4 votes

# Answer
# Python, ~~266~~ 63 bytes

*And we're down to less than ~~half~~ ~~one-third~~ ~~one-quarter~~ ~~two-sevenths~~ one-quarter of my original*, so a lot less scuffed than anything I've put out, but it's a first answer:

```
def a(b,c):
 m=(b<c)*(1-.5*(b%2))
 return int(b/2+m),int(b/2-m)

```

Takes advantage of the fact that \\$\frac {a+1} {b+1} \< \frac a b\\$, if \\$a \> b\\$: after that, it's just handling evens and a few exception cases.

-58 due to Wasif and a lambda of `str(int(n))`, plus dropping of whitespace.

-24 due to Wasif and the lambda function 2.

-14 by Wasif again and more cleaner conditionals.

-5 due to Wasif *again* by dropping the last else.

-15/-1 to Dominic van Essen and Lyxal respectively.

-3 from Wasif (making a return) and -6 from Dominic Van Essen again.

-39 from pxeger due to input semantics, taking us under halfway.

-9 from pxeger and -7 from Lyxal, taking us under 100, by returning a tuple instead of a list.

-2 from Dominic Van Essen, also managing to fix an error in the process

-14 from Dominic Van Essen again, with a nice simplification.

So far, total bytes saved:

* Wasif: 104
* pxeger: 48
* Dominic Van Essen: 47
* Lyxal: 8
> 3 votes

# Answer
# Husk, ~~11~~ 10 bytes

```
Se≠¹÷2+¹←=

```

Try it online!

```
Se≠¹÷2+¹←=      # full program:
Se≠⁰÷2+⁰←=²⁰    # here with implicit final arguments added for clarity;
      +⁰        # add to n:
        ←       # one less than
         =²⁰    # 1 if n==m
                # (in other words, subtract 1 from n if n==m),
    ÷2          # now integer divide by 2,
Se              # and construct a 2-element list of the result together with
  ≠⁰            # the difference between itself and n

```
> 1 votes

---
Tags: code-golf, math, number, array
---


title: Jimmy needs a new pair of shoes!

text:
# Question
Title: Jimmy needs a new pair of shoes!
Jimmy has had a busy last week with all these platforms and ropes, and poor Jimmy doesn't even have legs or feet to stand on!

---

Your job is to take a string containing multiple Jimmys and give them legs and shoes!

Get input in the form of a Jimmy String

Jimmy String =\> `/o\ /o\ /o\`

containing only `/o\` and

give each Jimmy in the input a pair of feet that look like this:

```
 /o\
_/ \_

```

Turn the inputed floating head Jimmy string into Jimmy with feet string, like so:

```
// Input

       /o\   /o\          /o\

// Output

       /o\   /o\          /o\
      _/ \_ _/ \_        _/ \_

```

If 2 Jimmys are close together they must move over to make room, Jimmys will always move towards the right to make room for other Jimmys.

```
// Input

/o\/o\

// Output

 /o\  /o\
_/ \__/ \_

```

Other Jimmys that are further away must not be moved unless necessary

```
// Input

/o\/o\      /o\

// Output

 /o\  /o\   /o\
_/ \__/ \_ _/ \_

// Input

/o\/o\    /o\

// Output

 /o\  /o\  /o\
_/ \__/ \__/ \_

```

Standard rules and loopholes apply,

This is code-golf, so may the shortest answer win.

# Answer
> 3 votes
# Python 2, ~~131~~ ~~120~~ ~~115~~ ~~114~~ ~~121~~ 118 bytes

```
o=1;W=[]
for g in map(len,input().split('/o\\')):W+=[' '*(g-o)];o=max(o-g,0)+2
for q in' /o\ ','_/ \_':print q.join(W)

```

Try it online!

4 bytes thx to movatica; 10 bytes lost for bug fix.

# Answer
> 3 votes
# Charcoal, 28 bytes

```
 Ｆ⌕Ａθ/«Ｊ∧ι⊖ι¹ＷＫＫ→Ｐ_/ \_Ｍ↗/o\

```

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

```

```

Print a space to defeat Charcoal's automatic left margin.

```
Ｆ⌕Ａθ/«

```

Loop over all of the left arms.

```
Ｊ∧ι⊖ι¹

```

Jump to the desired left foot location. Note that Charcoal has no problem drawing at `(-1, 1)`, but the question does not allow that, so we have to take care to avoid drawing at negative positions.

```
ＷＫＫ→

```

Move past any existing output.

```
Ｐ_/ \_Ｍ↗/o\

```

Output the feet and then move to output the Jimmy.

# Answer
> 3 votes
# Ruby `-p`, ~~77~~ 75 bytes

The "don't move Jimmy if not needed" rule was quite an ordeal to work around but I think it worked out quite well. Shorter than Python by quite a bit (at time of writing), at least.

-2 bytes from recursive.

```
r=/(\\ ?|^)(\S+) ?/
gsub(r){"#$1 #$2"}while~r
puts$_
gsub(/ .o. ?/,'_/ \_')

```

Try it online!

# Answer
> 3 votes
# PowerShell, 96 bytes

```
($o=$args-split'/o.'|%{' '*($w=($l+=$_.Length-1)*($l-gt0));$l-=$w+1})-join' /o\ '
$o-join'_/ \_'

```

Try it online!

Unrolled:

```
$o=$args-split'/o.'|%{
    $len += $_.Length-1
    $width = $len*($len-gt0)    # len or 0, if len < 0
    ' '*$width
    $len -= $width+1
}
# $o is array of space strings now
$o-join' /o\ '
$o-join'_/ \_'

```

# Answer
> 2 votes
# Python 2, ~~152~~ ~~148~~ 140 bytes

```
o=[-4]
for i,c in enumerate(input()):o+=[max(i,o[-1]+5)]*('/'==c)
for s in' /o\ ','_/ \_':print''.join('%*s'%(b-a,s)for a,b in zip(o,o[1:]))

```

Try it online!

# Answer
> 2 votes
# Retina, ~~40~~ 37 bytes

```
\+`(^|\S.)(/\S*) ?
$1 $2
 /o. ?
_/ \_

```

Try it online!

Thanks to Value Ink for golfing off 3 bytes.

# Answer
> 2 votes
# Stax, ~~29~~ ~~28~~ ~~24~~ 25 bytes

```
¢▄▌ß╙EVäN»0►,δñï◙,Θ╙BÅhΓ?

```

Run and debug it

There was a bug in the 24 byte solution that caused some off-by-1 errors in some cases.

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

```
s=>` /o\\
_/ \\_`.replace(/.*/g,j=>s.split(/.o./).map(s=>s.slice(n,l=s.length,n=n>l?n-l+2:2),n=1).join(j))

```

Try it online!

# Answer
> 1 votes
# MATLAB, 111 bytes

Try it online

```
function J(s)
s=[' ' s];s=replace(s,{'\/','\ /'},'\  /');for k=find(s=='o')
o(k-2:k+2)='_/ \_';end
char(s,o)

```

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


# Question
Title: Codegolf Rainbow : Draw in Black-and-White
## Introduction:

(Source: Wikipedia)
When we look at a rainbow it will always have the colors from top to bottom:
Red; orange; yellow; green; blue; indigo; violet

If we look at these individual rings, the red ring is of course bigger than the violet ring.
In addition, it's also possible to have two or even three rainbow at the same time.

All this above combined will be used in this challenge:

## Challenge:

Given an integer `n`, output that many rings of the (possibly more than one) 'rainbows', where we'll use the letters `vibgyor` for the colors.

See the test cases below to see how they are built upwards from `n=1`, and how the spacing should be handled (at `n=8`). As you can see, one space is added between two rainbows, including spacing at the top, before we add the ring of the next rainbow in line.

## Challenge rules:

* You are allowed to use capital `VIBGYOR` instead of lowercase
* There should be a space between the individual rainbows
* Any amount of leading and/or trailing spaces/new-lines are allowed, as long as the actual rainbow (wherever it is placed on the screen) is correct
* The input will always be a positive integer (`>= 1`). The behavior when `n=0` is therefore undefined, and the program/function can do whatever it wants (outputting nothing; outputting the rainbow of `n=1`; random output; fail with an error; etc.)
* You are allowed to output a list/array of strings or 2D array/list of characters if you want (you could add the actual pretty-printing code in the TIO footer).
* *Ignore the fact that the outputs looks more like Mayan temples than rainbows.. xD*

## General rules:

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

## Test cases (first `n=1` through `n=10`, and `n=25`):

```
1:
 vvv
v   v

2:
  iii
 ivvvi
iv   vi

3:
   bbb
  biiib
 bivvvib
biv   vib

4:
    ggg
   gbbbg
  gbiiibg
 gbivvvibg
gbiv   vibg

5:
     yyy
    ygggy
   ygbbbgy
  ygbiiibgy
 ygbivvvibgy
ygbiv   vibgy

6:
      ooo
     oyyyo
    oygggyo
   oygbbbgyo
  oygbiiibgyo
 oygbivvvibgyo
oygbiv   vibgyo

7:
       rrr
      rooor
     royyyor
    roygggyor
   roygbbbgyor
  roygbiiibgyor
 roygbivvvibgyor
roygbiv   vibgyor

8:
         vvv
        v   v
       v rrr v
      v rooor v
     v royyyor v
    v roygggyor v
   v roygbbbgyor v
  v roygbiiibgyor v
 v roygbivvvibgyor v
v roygbiv   vibgyor v

9:
          iii
         ivvvi
        iv   vi
       iv rrr vi
      iv rooor vi
     iv royyyor vi
    iv roygggyor vi
   iv roygbbbgyor vi
  iv roygbiiibgyor vi
 iv roygbivvvibgyor vi
iv roygbiv   vibgyor vi

10:
           bbb
          biiib
         bivvvib
        biv   vib
       biv rrr vib
      biv rooor vib
     biv royyyor vib
    biv roygggyor vib
   biv roygbbbgyor vib
  biv roygbiiibgyor vib
 biv roygbivvvibgyor vib
biv roygbiv   vibgyor vib

25:
                            ggg
                           gbbbg
                          gbiiibg
                         gbivvvibg
                        gbiv   vibg
                       gbiv rrr vibg
                      gbiv rooor vibg
                     gbiv royyyor vibg
                    gbiv roygggyor vibg
                   gbiv roygbbbgyor vibg
                  gbiv roygbiiibgyor vibg
                 gbiv roygbivvvibgyor vibg
                gbiv roygbiv   vibgyor vibg
               gbiv roygbiv rrr vibgyor vibg
              gbiv roygbiv rooor vibgyor vibg
             gbiv roygbiv royyyor vibgyor vibg
            gbiv roygbiv roygggyor vibgyor vibg
           gbiv roygbiv roygbbbgyor vibgyor vibg
          gbiv roygbiv roygbiiibgyor vibgyor vibg
         gbiv roygbiv roygbivvvibgyor vibgyor vibg
        gbiv roygbiv roygbiv   vibgyor vibgyor vibg
       gbiv roygbiv roygbiv rrr vibgyor vibgyor vibg
      gbiv roygbiv roygbiv rooor vibgyor vibgyor vibg
     gbiv roygbiv roygbiv royyyor vibgyor vibgyor vibg
    gbiv roygbiv roygbiv roygggyor vibgyor vibgyor vibg
   gbiv roygbiv roygbiv roygbbbgyor vibgyor vibgyor vibg
  gbiv roygbiv roygbiv roygbiiibgyor vibgyor vibgyor vibg
 gbiv roygbiv roygbiv roygbivvvibgyor vibgyor vibgyor vibg
gbiv roygbiv roygbiv roygbiv   vibgyor vibgyor vibgyor vibg

```

# Answer
> 5 votes
# Python 2, ~~84~~ ~~82~~ 81 bytes

-2 bytes thanks to ElPedro.

```
n=input();n+=n/7;w=''
while-~n:w+=" vibgyor"[n%8];print' '*n+w+w[-1]+w[::-1];n-=1

```

Try it online!

# Answer
> 4 votes
# Dyalog APL, ~~41~~ ~~39~~ 38 bytes

```
↑{⌽(⌽,⊃,A↑⊢)⍵↑A⍴' vibgyor'}¨-⍳A←⌈⎕×8÷7

```

Try it online!

A similar approach to others: `A←⌈⎕×8÷7` finds the height of the rainbow (also the width of the longest 'half row' to the left/right of the centre) and assigns it to `A` for later use, while `¨-⍳` iterates through the values 1..A, negating them to select on the correct side when used with .

`A⍴' vibgyor'` generates a 'half row' and `⍵↑` selects the correct length substring. `(⌽,⊃,A↑⊢)` generates the full row in reverse (which takes fewer characters to do), starting with a reversed half row (), then the centre character taken from the beginning of the half row string () and finally a right padded version of the half row (`A↑⊢`). The final  reverses the row into the correct orientation and  turns the vector of rows into a 2D array.

**Edit:** -2 thanks to dzaima

**Edit:** -1 thanks to ngn

# Answer
> 3 votes
# Canvas, ~~29~~ ~~28~~ 26 bytes

```
７÷Ｕ＋｛ <ibgyor＠¹×／ｎ｝⇵Ｋ２＊∔─↶

```

Try it here!

Explanation:

```
7÷U+                          ceil(input/7) + input
    {             }         for n in 1..the above
      <ibgyor@                in the string " <ibgyor", pick the nth character
              ¹×              repeat n times
                /             create a diagonal of that
                 n            and overlap the top 2 stack items (the 1st time around this does nothing, leaving an item for the next iterations)
                   ⇵        reverse the result vertically
                    K       take off the last line (e.g. " <ibgyor <ib")
                     2*     repeat that vertically twice
                       ∔    and append that back to the diagonals
                        ─   palindromize vertically
                         ↶  and rotate 90° anti-clockwise. This rotates "<" to "v"

```

~~25~~ ~~24~~ 22 bytes after fixing that ｍold should cycle if the wanted length is bigger than the inputs length and fixing  for like the 10th time

# Answer
> 3 votes
# JavaScript (ES6), 100 bytes

Returns an array of strings.

```
f=(n,a=[i='   '])=>++i<n+n/7?f(n,[c=' vibgyor'[i&7],...a].map(s=>c+s+c)):a.map(s=>' '.repeat(--i)+s)

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~32~~ ~~31~~ 23 bytes

```
.•VvÈ©•¹∍¬„ v:RηεÂ¬ý}.c

```

Try it online!

-1 thanks to Kevin Cruijssen and -8 thanks to Adnan

---

**Explanation (Stack example w/ input of 3):**

```
.•VvÈ©•                  # Push 'aibgyor'           | ['aibgyor']
       ¹∍                # Extend to input length.  | ['aib']
         ¬               # Push head.               | ['aib','a']
          „ v:           # Replace with ' v'.       | [' vib']
              R          # Reverse.                 | ['biv ']
               η         # Prefixes.                | ['b', 'bi', 'biv', 'biv ']
                ε   }    # For each....             | []
                 Â¬ý     # Bifurcate, join by head. | ['b','b']       ->    ['bbb']
                                                    | ['bi','ib']     ->   ['biiib']
                                                    | ['biv','vib']   ->  ['bivvvib']
                                                    | ['biv ',' vib'] -> ['biv   vib']
                     .c # Center the result.        | Expected output.

```

# Answer
> 3 votes
# Haskell, ~~114~~ ~~110~~ 101 bytes

Thanks to \[nimi\]\[1\] for -~~4~~ 13 bytes!

```
f n=""#(n+1+div n 7)
w#0=[]
w#n|x<-cycle"r vibgyo"!!n=((' '<$[2..n])++reverse w++x:x:x:w):(x:w)#(n-1)

```

Try it online!

# Answer
> 2 votes
# Python 2, 108 bytes

```
n=input()-1
n+=n/7+2
o=[]
for s in(' vibgyor'*n)[:n]:o=[s+l+s for l in[s]+o]
for l in o:print l.center(n-~n)

```

Try it online!

# Answer
> 2 votes
# , 130 bytes

```
function(n,k=n%/%7*8+1+n%%7,a=el(strsplit(' vibgyor'/k,'')))for(i in k:1)cat(d<-' '/(i-1),a[c(k:i,i,i:k)],d,sep='','
')
"/"=strrep

```

Try it online!

* -6 bytes thanks to @JayCe

# Answer
> 2 votes
# Jelly, 31 bytes

```
:7+‘µ“ vibgyor”ṁṚ,Ṛjṛ/ƲƤṭ"ḶṚ⁶ẋƲ

```

Try it online!

Check out a test suite!

**ಠ\_ಠ** This is overly complicated because Jelly doesn't have a centralize function...

# Answer
> 2 votes
# Charcoal, 30 bytes

```
↶≔… vibgyor⁺²÷×⁸⊖Ｎ⁷θθ⸿Ｅθ✂θκ‖Ｏ←

```

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

Change the drawing direction to upwards.

```
≔… vibgyor⁺²÷×⁸⊖Ｎ⁷θ

```

Calculate the height of the rainbow and repeat the literal string to that length.

```
θ⸿

```

Print the central line of the rainbow.

```
Ｅθ✂θκ

```

Print the right half of the rainbow by taking successive slices and printing each on its own "line".

```
‖Ｏ←

```

Reflect to complete the rainbow.

# Answer
> 2 votes
# Jelly, 28 bytes

```
:7+‘“ vibgyor”ṁµṫJZz⁶U;"⁸ŒBṚ

```

A monadic link accepting an integer which yields a list of lists of characters.

**Try it online!** (footer joins with newline characters)

Or see the test-suite.

### How?

```
:7+‘“ vibgyor”ṁµṫJZz⁶U;"⁸ŒBṚ - Link: integer
:7                           - integer divide by seven (number of full rainbows)
   ‘                         - increment (the input integer)
  +                          - add (gets the number bands)
    “ vibgyor”               - list of characters = " vibgyor"
              ṁ              - mould like the result above (as a range)
               µ             - start a new monadic chain
                 J           - range of length
                ṫ            - tail (vectorises) (gets the suffixes)
                  Z          - transpose
                   z⁶        - transpose with filler space character
                             -   (together these pad with spaces to the right)
                     U       - reverse each
                             -   (now we have the left side of the rainbow upside down)
                        ⁸    - chain's left argument, as right argument of...
                       "     -   zip with:
                      ;      -     concatenation
                             -   (adds the central character)
                         ŒB  - bounce (vectorises at depth 1)
                             -   (reflects each row like [1,2,3,4] -> [1,2,3,4,3,2,1])
                           Ṛ - reverse (turn the rainbow up the right way)

```

# Answer
> 2 votes
# PowerShell, ~~108~~ ~~98~~ ~~89~~ 85 bytes

```
param($x)($x+=$x/7-replace'\..*')..0|%{' '*$_+-join(" vibgyor"*$x)[$x..$_+$_+$_..$x]}

```

Try it online!

This one feels pretty alright now. Banker's rounding is still the devil and I figured out how to make a non-dumb join. I tried monkeying with $ofs to not much success. Speaking of, the results without joins look pretty good, a bit melty:

```
         vvv
        v     v
       v   rrr   v
      v   r ooo r   v
     v   r o yyy o r   v
    v   r o y ggg y o r   v
   v   r o y g bbb g y o r   v
  v   r o y g b iii b g y o r   v
 v   r o y g b i vvv i b g y o r   v
v   r o y g b i v     v i b g y o r   v

```

# Answer
> 2 votes
# Haskell, 106 ~~113~~ bytes

I can't yet comment other posts (namely this) so I have to post the solution as a separate answer.

Golfed away 7 bytes by ovs

```
p x=reverse x++x!!0:x
u m|n<-m+div(m-1)7=[(' '<$[z..n])++p(drop(n-z)$take(n+1)$cycle" vibgyor")|z<-[0..n]]

```

Try it online!

(Old version, 113 bytes)

# Answer
> 1 votes
# Python 2, ~~132~~ 131 bytes

```
def f(n):
 t=n+n/7;s=('vibgyor '*n)[:t];r=[s[~i:]+t*' 'for i in range(t)]
 for l in zip(*r+3*[' '+s]+r[::-1])[::-1]:print''.join(l)

```

Try it online!

---

Saved:

* -1 byte, thanks to Jonathan Frech

# Answer
> 1 votes
# Red, 153 bytes

```
func[n][r: take/last/part append/dup copy"""roygbiv "n l: 9 * n + 8 / 8
repeat i l[print rejoin[t: pad/left take/part copy r i l last t reverse copy t]]]

```

Try it online!

## Slightly more readable:

```
f: func[ n ] [
    r: copy ""
    append/dup r "roygbiv " n
    r: take/last/part r l: 9 * n + 8 / 8
    repeat i l [
        print rejoin [ t: pad/left take/part copy r i l
                       last t
                       reverse copy t ]
    ]
]

```

# Answer
> 1 votes
# Java (JDK 10), 184 bytes

```
n->{int h=n+n/7,i=h+1,w=i*2+1,j,k=0;var o=new char[i][w];for(;i-->0;o[i][w/2]=o[i][w/2+1])for(j=w/2;j-->0;)o[i][j]=o[i][w+~j]=i<h?j<1?32:o[i+1][j-1]:" vibgyor".charAt(k++%8);return o;}

```

Try it online!

Prints an extra leading and trailing space for each multiple of 7.

## Explanation

```
n->{                             // IntFunction
 int h=n+n/7,                    //  Declare that height = n + n/7
     i=h+1,                      //          that index  = h + 1
     w=i*2+1,                    //          that width  = (h+1)*2+1
     j,                          //          j
     k=0;                        //          that k      = 0
 var o=new char[i][w];           //  Declare a 2D char array
 for(;                           //  Loop
   i-->0;                        //    Until i is 0
   o[i][w/2]=o[i][w/2+1]         //    After each run, copy the middle letter.
 )
  for(j=w/2;                     //   Loop on j = w/2
   j-->0;                        //     Until j = 0
  )                              //
   o[i][j]                       //    copy letters to the left side,
    =o[i][w+~j]                  //      and the right side
    =i<h                         //      if it's not the last line
     ?j<1                        //        if it's the first (and last) character
      ?32                        //          set it to a space.
      :o[i+1][j-1]               //          else set it to the previous character on the next line.
     :" vibgyor".charAt(k++%8);  //      else assign the next letter.
 return o;                       //  return everything
}

```

## Credits

# Answer
> 1 votes
# Stax, 23 bytes

```
⌡G'5h!M╩EV[Ez ▼>≈<S⌡⌡0`

```

Run and debug it

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

```
" vibgyor"  string literal
,8*7/^      input * 8 / 7 + 1
:m          repeat literal to that length
|]          get all prefixes
Mr          rectangularize, transpose array of arrays, then reverse
            this is the same as rotating counter-clockwise
m           map over each row with the rest of the program, then implicitly output
            the stack starts with just the row itself
  _h        push the first character of the row
  _r        push the reversed row
  L         wrap the entire stack in a single array

```

Run this one

# Answer
> 1 votes
# V (vim), 105 bytes

```
"aDiaibgyor<esc>0vg_y$@ap0l@alhd$:s/a/ v/g
qqYP0xjYP!!rev
gJkhq2@a@qylpp02ld$0VG:center<c-r>=2*(<c-r>a+ceil(1+<c-r>a/7))

```

Try it online!

There's many possible saves here, but for now I'm just happy I got it working.

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


title: Make a Unicorn interpreter

text:
# Question
Title: Make a Unicorn interpreter
Recently, I made a made a typo and I wrote unicorn instead of unicode, I did what any normal person would do and I made an esolang out of it. In this challenge you will be writing a Unicorn interpreter.

Because Unicorn programs are horrible long, you'll have to write a short interpreter to compensate for this.

## Example

These are the transpiled result, not the actual interpreted result your program should output

```

1

alert([x=(p=prompt())/2+Math.sqrt(p*p/4-prompt()),p-x])

"Hello, World!"

```

## Specification

* Unicorn is divided into "sections" which are space-separated
* Each section represents a character
* The number of unicorns () in each section is converted to it's associated character (i.e. 32 unicorns -\> `chr(32)` -\> ).
* If the section contains goats (), the length of the amount of goats should be *doubled*, then converted to the associated character
* If the section contains any other characters, the program should ignore the character.
* Each section (character) should be joined to form a program
* This resulting program should be evaluated in the language you have written the program in. (e.g. JavaScript's `eval`, Python's `exec`)
* Unicorns are unicode `U+1F984`; goats are unicode `U+1F410`.
* If you choose a compiled language, you may output/save the compiled, compiled unicorn code

(unicorns) and  (goats) all count as one byte for this challenge.

If your language doesn't support emojis, you may identify unicorns as (`u`) and goats as (`g`). You may not support emojis *and* `u`,`g`

---

If you really want to see the ~~unicodes~~ unicorns, here is a picture of this post

---

**+50 bounty:** to the shortest program in (the original) Unicorn while being under 6500 chars. You must use this version, it must run on Firefox, Chrome, or Safari.

# Answer
# Pyth - ~~23~~ 17 bytes

```
.vsmC+/d\y/d\cz

```

Try it online.

It works by splitting the input by spaces, then for each section counting the number of unicorns and number of goats * 2 then adding them, then taking the char at the code point. It finished by summing the char array and pyth-evaling.
> 9 votes

# Answer
# Unicorn (ES6), ~~5934~~ 5278 bytes

Under the custom encoding, this is 5278 bytes (1 byte per char); but with UTF-8, it would 4 bytes per char (though only 1 for a space), or 20869 total.

```
(too many Unicorns and Goats to reasonably display here)

```

Instead, here's a pastebin. This Unicorn code transpiles to this JS snippet:

```
s=>eval(s.replace(/\S+ ?/g,c=>String.fromCharCode(c.length>>1<<c.charCodeAt()%2)))

```

Now, this isn't the shortest possible version; this is shorter:

```
s=>eval(s.replace(/\S+ ?/g,c=>String.fromCharCode(c.length>>1<<("">c))))

```

However, the one unicorn in there would transpile to 56034 goats, thus multiplying the score by roughly 11.

Here's the function I used to transpile to Unicorn:

```
function g(s){return s.replace(/./g,function(c){i=c.charCodeAt();return(i%2?"".repeat(i):"".repeat(i/2))+" "}).slice(0,-1)}
```

```
<textarea id=O cols=100></textarea><button id=P onclick="Q.value=g(O.value);R.innerHTML=(Q.value.length+Q.value.split(' ').length-1)/2">Run</button><br><textarea id=Q rows=10 cols=100>Output appears here.</textarea><br><p>Length: <span id=R>0</span><br></p>
```

Note: I haven't actually tested the program, as there isn't an online interpreter that I could find (although I suppose I could hook up the .js file to HTML...?)
> 23 votes

# Answer
# Python ~~179~~ 176 bytes

**EDIT**: I just learnt s.split(' ')=s.split()

Here is the second "actual" programming language Unicorn interpreter. I call this version of Unicorn "UnicornPy" pronounced as "unicorn pie". I am making this much too official!

```
s=raw_input()
s=s.replace('','')
s=s.replace('','u')
for i in s:
    if i not in "ug ":
        s=s.replace(i,'')
s=s.split()
for i in s:
    s[s.index(i)]=chr(len(i))
exec(''.join(s))

```

For some reason, it needs me to convert the unicorn and goat emojis to u and g. I do not know why.

Try it here!
> 4 votes

# Answer
# Ruby, 78 Bytes

```
eval ARGV[0].gsub(/[^ug ]/,'').split.map{|b|(b.size*(b[0]=='u'?1:2)).chr}.join

```

It basically reads the first command line argument, splits it at every space character, maps the size of the block to the appropriate character and joins it all together.

Edit: Forgot the requirement that all other characters should be ignored
> 3 votes

# Answer
# Unicorn ES6 (Invalid), 3379 bytes

This is invalid because it uses the latest version of Unicorn with rainbows, sun with clouds, and sparkles. Thanks to @ETHproductions for the JS code to interpret unicorn.

```
code is in the paste bin below

```

Pastebin: http://pastebin.com/raw/Q9Kd4ixA
This is only 3379 bytes if sparkles, sun/clouds, and rainbows also are 1 byte.
> 3 votes

# Answer
# PHP, 83 ~~80~~ ~~86~~ ~~87~~ bytes

## Now Unicorn-ready

For the cost of **3 bytes** I made this unicorn ready:

```
$a=mb_substr_count;foreach(explode(" ",$argv[1])as$b)echo chr($a($b,)+2*$a($b,));

```

Takes an input from command line, like:

```
$ unciorns.php " "

```

This will output `32`.

**Demo**

Try before buy

---

Unfortunately OS X 10.10.5 ~~doesn't support~~ is hiding Unicorns. Here's the alternative `ug`-approach (**80 bytes**):

```
$s=substr_count;foreach(explode(' ',$argv[1])as$c)echo chr($s($c,u)+2*$s($c,g));

```

Takes an argument from command line, like:

```
$ php unicorns.php "uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuug uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu"

```

Try the *ug*-version

---

**Edits**

* *Saved* **1 byte** due to massive refactoring. This version is already discarded again, since I managed to golf the original even further:

Demo discarded version (**86 bytes**)

```
for($_=$argv[1].' ';$c=$_[$i++];)$t+=u==$c?1:(g==$c?2:(' '==$c?-$t+!print chr($t):0));

```
* *Saved* **6 bytes** by replacing `for` with `foreach`
* *Added* **3 bytes** making it *Unicorn-ready*.
> 1 votes

# Answer
## Mathematica, 118 bytes

```
a=StringCount;ToExpression@FromCharacterCode[If[#~StringTake~1=="u",#~a~"u",2IntegerLength[#~a~"g"]]&/@StringSplit@#]&

```

Performs exactly as described in the specification. I couldn't use emoji in Mathematica string literals without the interpreter exploding, so I used `u` and `g`.
> 1 votes

# Answer
# Rust, 426 bytes

```
use std::io::Write;macro_rules!c{($n:expr,$a:expr)=>(println!("{}",std::str::from_utf8(&std::process::Command::new($n).arg($a).output().unwrap().stdout).unwrap());)}fn main(){let d:String=std::env::args().skip(1).next().unwrap().split(' ').map(|s|s.chars().fold(0u8,|a,c|a+match c as char{''=>1,''=>2,_=>0}) as char).collect();std::fs::File::create("o").unwrap().write_all(d.as_bytes()).unwrap();c!("rustc","o");c!("o","");}

```

This probably can be golfed the hell down, but type safety and checked errors are quite verbose.

Since Rust is a compiled language, this program outputs the decoded program to a file and invokes the compiler on said file, then executes the resulting binary.

Ungolfed:

```
use std::io::Write;

macro_rules! command {
    ($name:expr,$argument:expr) => (println!("{}", std::str::from_utf8(
        std::process::Command::new($name)
                              .arg($argument)
                              .output()
                              .unwrap()
    ));)
}

fn main() {
    let decoded: String = std::env::args()
        .skip(1) //ignore program name
        .next().unwrap().split(' ') //get first arg split on spaces
        //transform every section in a char
        .map(|section| section.chars()
            .fold(0u8, |accumulator, chr| accumulator + match chr as char {
            '' => 1,
            '' => 2,
            _ => 0
        }) as char)
        //convert iterator to string
        .collect();

    std::fs::File::create("o").unwrap()
        .write_all(decoded.as_bytes()).unwrap();
    command!("rustc", "o");
    command!("o", "");
}

```
> 1 votes

# Answer
# Python 3, ~~94~~ 86 bytes

This is a simple parser that works even if you mix `u` and `g` in one section.

```
s=input().split();exec(''.join(chr(sum([[0,2][j<"u"],1][j>"g"]for j in i))for i in s))

```

As an example (using `u` and `g` in separate sections):

```
gggggggggggggggggggggggggggggggggggggggggggggggggggggggg ggggggggggggggggggggggggggggggggggggggggggggggggggggggggg uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu ggggggggggggggggggggggggggggggggggggggggggggggggggggggg gggggggggggggggggggggggggggggggggggggggggggggggggggggggggg gggggggggggggggggggg uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu

```

should parse to

```
print(1)

```
> 1 votes

# Answer
# Ruby, 75 characters

A nifty ruby interpreter that replaces all  with `' '` (a space) and all  with `' '` (two spaces), and gets the length of each segment.

I call this version of Unicorn ~~RubyUnicorn~~ *Rubycorn*.

```
->s{eval s.split(a=' ').map{|r|r.gsub('',a).gsub('',a*2).size.chr}.join}

```
> 1 votes

# Answer
# Racket, 200 bytes

```
(define(f s)(eval(read(open-input-string(list->string(map integer->char(map(λ(x)(foldl(λ(y a)(case y[(#\u)(add1 a)][(#\g)(+ a 2)]))0 x))(map string->list(string-split s)))))))(make-base-namespace)))

```

Ungolfed:

```
(define(f s)
  (eval(read(open-input-string
             (list->string ;;back to string
              (map integer->char ;;back to char
                   (map(λ(x)
                         (foldl(λ(y a)
                                 (case y
                                   [(#\u)(add1 a)]
                                   [(#\g)(+ a 2)]))
                               0 x))
                       (map string->list (string-split s))))))) ;;splitting by space, converting to list of chars
       (make-base-namespace)))

```

It starts by splitting the string into list of strings by spaces, then creates a list of chars per splitted string. Then each list of chars is reduced into a number by adding 1 if unicorn, 2 if goat. Finally, each list containing the sum is made a list of chars, then a string which is passed to eval.

Try it online!
> 1 votes

# Answer
# JavaScript, 140 154 141 bytes

```
var s='';i.split(" ").forEach((e)=>{s+=String.fromCharCode((e.split("").length-1)+2*(e.split("").length-1));});console.log(eval(s));

```

It splits the input string in an array of strings, using space as a needle. It then proceeds to count the amount of unicorns and goats\*2 and concatenate the summed result to what will be evaluated.

More readable:

```
var s = '';
i.split(" ").forEach((e) => {
    s+=String.fromCharCode((e.split("").length-1)+2*(e.split("").length-1));
});
console.log(eval(s));

```

---

**Edit:**

Updated code to accept an argument from CLI, use: `node unicorn.js " "`

```
var s='';process.argv[2].split(' ').forEach((e)=>{s+=String.fromCharCode((e.split('').length-1)+2*(e.split('').length-1));});console.log(eval(s));

```

Ungolfed:

```
var s = '';
process.argv[2].split(' ').forEach((e) => {
    s+=String.fromCharCode((e.split('').length-1)+2*(e.split('').length-1));
});
console.log(eval(s));

```

---

**Edit 2:**

Edited to accept input as a function parameter, use `node unicorn.js`

```
i=>{var s='';i.split(' ').forEach((e)=>{s+=String.fromCharCode((e.split('').length-1)+2*(e.split('').length-1));});return eval(s);};

```

Ungolfed:

```
i =>{
    var s = '';
    i.split(' ').forEach((e) => {
        s+=String.fromCharCode((e.split('').length-1)+2*(e.split('').length-1));
    });
    return eval(s);
};

```

Try it online!
> 1 votes

# Answer
# RProgN, 25 bytes

```
~`''R'(+)%s*'{Lc}R do

```

## Explained

```
~                             # Zero Space Segment
 `                         # The String literal ""
   ''                   # The String literal ""
       R                     # Replace, turning all goats into twonicorns
        '(+)%s*'          # The pattern string "(+)%s*", which is "A fewnicorns, then as much whitespace as possible, or none.
                 {Lc}R      # Replace with the result of the function, which converts the captured subgroup to it's Length, then to a char.
                       do   # Straight up do it.

```

Once again, RProgN falls into the trap of being consistently okay.

Try it online!
> 1 votes

# Answer
# Perl 6, 67 bytes

```
{use MONKEY-SEE-NO-EVAL;EVAL [~] .words».&{chr m:g/\/+2*m:g/\/}}

```
> 0 votes

# Answer
# SmileBASIC, 125 bytes

```
INPUT S$WHILE LEN(S$)R=ASC(POP(S$))IF R-32THEN C=C+!(R-117)+2*!(R-103)ELSE O$=CHR$(C)+O$C=0
WEND
SAVE"TXT:@",CHR$(C)+O$EXEC"@

```

Using PRGEDIT to execute the code without saving would have been a lot nicer, but also a lot longer.

code:

```
INPUT CODE$ 'making the user type 1000s of characters just so I could save 2 or 3
WHILE LEN(CODE$)
 CHAR$=POP(CODE$) 'I convert the code backwards, since POP( is shorter than SHIFT(
 IF CHAR$==" " THEN
  UNSHIFT OUT$,CHR$(CHAR)
  CHAR=0
 ELSE
  INC CHAR,(CHAR$=="u")+(CHAR$=="g")*2
 ELSE
WEND
SAVE "TXT:@",CHR$(CHAR)+OUT$
EXEC "TXT:@"

```
> 0 votes

# Answer
# Stax, 14 bytes

```
ü┴(gÇ%╩[↑÷>7♫░

```

Run and debug it
> 0 votes

---
Tags: code-golf, interpreter
---


title: Ball game King of the hill

text:
# Question
Title: Ball game King of the hill
# AND THE WINNER IS....

> Command Master's "Ball Pulling"!

Note: Competition is over, but more submissions are welcome!

Ball game is a game I invented where two players start with 100 energy each. Every turn, each player independently chooses an amount of energy to spend. Whoever spends more energy brings the ball 1 unit closer to their side - if they spend the same, it's a tie. If the ball is on someone's side, 4 units away from the center, the person who's side it's on wins. If both players run out of energy before it has reached one side or the other, it's a draw.

An example game might look like this:

```
rem P1  3  2  1  0  1  2  3  P2 rem
75  25              o        33  67
50  25           o            8  59
25  25        o               8  51
0   25     o                 18  33
0   0         o              15  18
0   0            o            6  12
0   0               o        12   0
                DRAW

```

Your job is to make a bot for this game, in javascript.

# Rules

The bot is a function taking three values:

The player's energy, as a number.
The player's previous moves, as an array of numbers.
The ball position, as a number between -3 and 3 inclusive. Positive is closer to the player, negative is further. The function must return an integer between 1 and 100 (Not NaN).

No messing with other bots.

No global variable access, as in standard KoTH rules.

# Controller

This controller can do two things: It can 1v1 two bots, and it can run a tournament with each bot facing every other bot 100 times. The 1v1 setting generates a log of the game, and the tournament setting creates a leaderboard. The tournament is scored by +1 point for winning, nothing for drawing or losing.

Bots should be added to the bots object.

```
var bots = {
  "25er": function(myE, myPrev, pos) {
    return 25;
  },
  "random": function(myE, myPrev, pos) {
    return Math.floor(Math.random() * 36) + 1;
  },

  "Ball pulling": function(myE, myPrev, pos) {
    return Math.max(1,Math.floor(myE * [0.10808232641486629,0.30174603004818334,0.2358032944932353,0.10406266397506114,0.25013297998583794,0.4608205872385916,0.5635474208925423][3-pos] + [-25.20386503823533,-4.62324162626722,-7.69195538879287,-5.7156191657689925,-3.221187031407233,-16.758418842577605,-4.233010800850232][3-pos] + Math.random() * [23.13539398461274,-3.257894925941551,-0.09547522996644178,-0.09187251666187485,-1.1010525700900573,-9.874021194357677,2.831769191532314][3-pos]));
},

  "Decay": (energy, previous, position) => {
    return energy == 100 ? 30 : Math.ceil(energy * 0.15);
  },

  "waiter": (myE, myPrev, pos) => {
    if (pos == 3) {
      // If 1 space from winning, spend all energy to try and win
      return myE;
    } else if (pos == 1) {
      return Math.max(1, Math.floor(myE * .06));
    } else if (pos == -3) {
      // If opponent is 1 space from winning, spend 82% energy to try and prevent them from winning, or spend 9 to counter Memory
      return myPrev.length < 9 ? Math.ceil(myE * .82) : Math.min(9, Math.ceil(myE * .82));
    } else if (myPrev.length < 1) {
      // If fewer than 1 turn has been played, "wait" and only spend 1 energy
      return 1;
    } else {
      // Otherwise spend up to 12% of energy
      return Math.max(1, Math.floor(myE * .12));
    }
  },
  "Exhauster": function(myE, myPrev, pos) {
    return pos == -3 ? 28 - myPrev.length : 3;
  },

  "Memory": function(myE, myPrev, pos) {
    if (myPrev.length == 0) return 2;
    prev_pos = 0;
    for (i = 0; i < myPrev.length - 1; i++) {
      if (myPrev[i] > myPrev[i + 1]) {
        prev_pos += 1;
      } else if (myPrev[i] < myPrev[i + 1]) {
        prev_pos -= 1;
      }
    }
    move = myPrev[myPrev.length - 1]
    if (pos == 3) return move;
    if (prev_pos > pos) {
      move = Math.ceil(move * 2.75);
    } else if (prev_pos < pos) {
      move = Math.ceil(move * 0.8);
    }
    return Math.max(1, Math.min(move, myE - 8));
  },
  "just1": (myE, myPrev, pos) => {
    return pos === -3 ? Math.ceil(myE / 4) : 1;
  },

  "Vague Memory": function(myE, myPrev, pos) {
    if (myPrev.length == 0) return 2;
    prev_pos = 0;
    for (i = 0; i < myPrev.length - 1; i++) {
      if (myPrev[i] > myPrev[i + 1]) {
        prev_pos += 1;
      } else if (myPrev[i] < myPrev[i + 1]) {
        prev_pos -= 1;
      }
    }
    move = myPrev[myPrev.length - 1]
    if (pos == 3) return move;
    if (prev_pos > pos) {
      move = Math.ceil(move * 2.75 - 2.4 * Math.random());
    } else if (prev_pos < pos) {
      move = Math.ceil(move * 0.8);
    }
    min_move = Math.round(3.5 * Math.random());
    if (pos < -1) min_move += 2;
    return Math.max(min_move, Math.min(move, myE - 28));
  },
  "table": (myE, myPrev, pos) => {
    if (myE == 0) {
      return 0;
    }
    let w = [
      [-5.6544223, 0.06557736, -0.2641703],
      [0.75869083, -0.011340193, 1.4130216, -1.2559392],
      [0.13409477, 2.9561214, 0.27817196, 0.0030480723, 0.3889832],
      [-2.6868086, -0.3014877, 4.818155, 3.9265578, 1.7512726, 0.097844936],
      [0.68415153, 0.72050923, 1.334225, -1.6574494, 2.4933205, -0.25133085, -1.4409807],
      [1.6410222, -74.064156, -7.7318263, -0.01627013, 2.0059361, -6.7933116, -0.14581795, -1.6378351],
    ];
    let b = [1.8160640001296997, 1.5627140998840332, 3.7942299842834473, -2.4042959213256836, 2.8334028720855713, 312.232177734375];
    let log_weights = [];
    let log_weight_max = -Infinity;
    for (let m = 0; m < myE; m++) {
      let f = [m / (myE - 1), (myE - 50) / 29.15475947, 0.5 * pos, 0, 0, 0, 0, 0, 0];
      for (let l = 0; l < w.length; l++) {
        f[l + 3] = b[l];
        for (let i = 0; i < w[l].length; i++) {
          f[l + 3] += w[l][i] * f[i];
        }
        if (b[l] <= 300) {
          f[l + 3] = Math.max(f[l + 3], 0);
        }
      }
      let log_weight = f[f.length - 1];
      log_weight_max = Math.max(log_weight_max, log_weight);
      log_weights.push(log_weight);
    }
    let Q = 0;
    let M = 0;
    for (let m = 0; m < log_weights.length; m++) {
      let q = Math.exp(log_weights[m] - log_weight_max);
      Q += q;
      if (Math.random() * Q <= q) {
        M = m;
      }
    }
    return M + 1;
  },

  "Pacemaker": (myE, myPrev, pos) => {
  if (myPrev.length === 0) return 4; // https://xkcd.com/221/
  if (pos === 3) return Math.round(myE * 0.99);
  if (pos === -3) return Math.max(1, Math.round(myE * 0.4));
  return Math.max(1, Math.min(myE, Math.round(myE / (7 - pos))));
},

 "Fraction": function(myE, myPrev, pos) {
   return ((myPrev.length===3)&&(pos===-3))? 25 : Math.floor(myE/(pos+4)*0.395)
 },
'chair': function(myE, myPrev, pos) {
    let c = 0x69b82a691f395b79b7fb2bb83cb5f2a40ce32e4a4c4a055f7c50e68a3f81e123197280dfbec638e3b036a9b53677122f2fa83447501ece2a63d766e983ff858cda2da01ac621bb3084c1055a2fe83e6a7450c29fa99549d3cc6f1c556550b2397f417e915b65d47a9d6c1b267aaab5171d3e8a7fbad4788e9cb795cdc11759ba232730ad0a3635a8a9c5564afdf5b82c380687a8af1b1f1ca4d36ac668b32cafe39afdda16421be9d955ce70cfab6c987dc407e97792f647a43ecd0f191fecdbc60ef782519410655f3054395cc0e1c68f893f416806ad502b9b945166b61110f7d72c0d5437d32235007c26b64f787f1147e3ce1966a4ff6fb564d47db1b191801e811052dd5c31bee7fed77afae4799debec9349e224155780fbd65684d2503356b0c71805a41994fd48f043ee745d8bc8e12bb8105cb97edef8e08f2d5467649aceb5ee668168420ad4b4b0d9c33cf4577b19827220dec3377c1bdf627fa1b3015b59b0a5e4b456f4d18abbbc4d22bde46c7596a7cbabb4536fa325561e50e1bdffeee5fb17a6222ae7f5d894c824920227b4f45aa369e8d3956b68ad8ba2499c5b4f925b42983544c1c9cbff22bb3774c138c0b04b47be0a91c73164b0729d0fd4521be988e78584d5974fc0083452e6127507a59956104d84ad3bc481325d21295ebfc63ea8c4708251a1df30a3f7e906b9acba9eda44f60091c6765466a6f9dbc5a83862ad358d0a41f7d4d099670b2e6302d9a1d5dbfb54a1698e3f9d9956ad90e53n;
    return myE <= 1 ? myE : Number((c / (83n ** BigInt(myE * 7 + pos - 11))) % 83n + 1n);
},
'Indecisive Tracker': (myE, myPrev, pos) => {
  const RESULT = { WIN: 0, DRAW: 1, LOSE: 2 }
  const RESULT_ENCODING_OFFSET = [0, 1, 2]
  const RESULT_WEIGHT = [1, 0, -1]
  const MIN_SPENDING = 1
  const posToAggressionFactor = [0, 0.3, 0.2, 0, 0, 0, 0.1, 0.8, 0]
  const posToRiskAppetite = [0, 1, 0.4, 0.1, 0.1, 0.1, 0.2, 0.3, 0]
  let encodeResult = (E, lastResult) => E + RESULT_ENCODING_OFFSET[lastResult]
  let decodeResult = (E) => RESULT_ENCODING_OFFSET.findIndex(e => e === (E - MIN_SPENDING) % RESULT_ENCODING_OFFSET.length)
  let getResultFromPos = (posBefore, posAfter) => {
    return posBefore < posAfter ? RESULT.WIN
         : posBefore > posAfter ? RESULT.LOSE
                                : RESULT.DRAW
  }
  let BallMove = (prevPos, currE, nextE, finalPos) => {
    let currResult = nextE == null ? getResultFromPos(prevPos, finalPos)
                                   : decodeResult(nextE)
    let nextPos = prevPos + RESULT_WEIGHT[currResult]
    let enemyE = currResult === RESULT.LOSE ? currE + 1
               : currResult === RESULT.DRAW ? currE
                                            : 1
    return {
      enemyE: enemyE,
      myE: currE,
      posBefore: prevPos,
      posAfter: nextPos,
      result: currResult
    }
  }
  const GOAL = 8
  let normalizedPos = pos + 4
  let goalDistance = GOAL - normalizedPos
  let minimumReservedEnergyPerTileDistance = 3
  let spendableEnergy = myE - ((goalDistance - 1) * minimumReservedEnergyPerTileDistance)
  let prevPos = 0
  let prevResult = RESULT.DRAW
  let gameMoves = new Array()
  for (i = 0; i < myPrev.length; i++) {
    let currMove = BallMove(prevPos, myPrev[i], myPrev[i+1], pos)
    prevPos = currMove.posAfter
    prevResult = currMove.result
    gameMoves.push(currMove)
  }
  let myRandom = (min, max, spacing) => {
    if ((spacing ?? 0) === 0) spacing = 1
    let maxEncodingOffset = Math.max.apply(null, RESULT_ENCODING_OFFSET)
    let adjustedMin = Math.floor((min + maxEncodingOffset) / spacing) * spacing
    let offset = adjustedMin
    let adjustedMax = max - offset - maxEncodingOffset
    let adjustedRange = Math.floor(adjustedMax / spacing) + 1
    return Math.floor(Math.random() * adjustedRange) * spacing + offset
  }
  let minE = spendableEnergy * posToAggressionFactor[normalizedPos]
  let maxE = spendableEnergy * posToRiskAppetite[normalizedPos]
  let nextE = MIN_SPENDING + myRandom(minE, maxE, RESULT_ENCODING_OFFSET.length)
  let encodedNextE = encodeResult(nextE, prevResult)
  return encodedNextE
},

  // add your bot here
}

function game(p1, p2) {
  var ballPos = 0,
    p1moves = [],
    p2moves = [],
    p1e = 100,
    p2e = 100,
    outcome = '';
  var str = 'rem P1  3  2  1  0  1  2  3  P2 rem';

  function string(pos, e, e2) {
    var s = p1e + (p1e < 100 ? (p1e < 10 ? '   ' : '  ') : ' ') + e + (e < 10 ? ' ' : '');
    if (pos == -4) {
      s += '        P1 WINS        '
    } else if (pos == 4) {
      s += '        P2 WINS        '
    } else {
      s += ' '.repeat((pos + 4) * 3 - 1) + 'o' + ' '.repeat(23 - (pos + 4) * 3)
    }
    return s + (e2 < 10 ? ' ' : '') + e2 + (p2e < 100 ? (p2e < 10 ? '   ' : '  ') : ' ') + p2e;
  }
  while (Math.abs(ballPos) < 4) {
    var p1out = p1e ? Math.max(Math.min(p1e, bots[p1](p1e, p1moves, -ballPos)), 1) : 0;
    var p2out = p2e ? Math.max(Math.min(p2e, bots[p2](p2e, p2moves, ballPos)), 1) : 0;

    if (p1out > p2out) {
      ballPos--;
    } else if (p1out < p2out) {
      ballPos++;
    }
    p1e -= p1out;
    p2e -= p2out;
    str += '\n' + string(ballPos, p1out, p2out);
    if (p1e == 0 && p2e == 0 && Math.abs(ballPos) < 4) {
      str += '\n                DRAW               ';
      break
    }
    p1moves.push(p1out);
    p2moves.push(p2out)
  }
  return {
    log: str,
    res: (ballPos == -4 ? 1 : (ballPos == 4 ? 2 : 0))
  }
}

function init() {
  var f = document.getElementById('f'),
    f2 = document.getElementById('f2');
  for (var x in bots) {
    var option = document.createElement('option');
    option.innerText = x;
    option.value = x;
    f.appendChild(option);
    var option2 = document.createElement('option');
    option2.innerText = x;
    option2.value = x;
    f2.appendChild(option2)
  }
}
init();

function play() {
  var f = document.getElementById('f'),
    f2 = document.getElementById('f2');
  document.getElementById("g").innerText = game(f.value, f2.value).log
}

function tournament() {
  var leaderboard = {},
    names = [];
  for (var x in bots) {
    names.push(x);
    leaderboard[x] = 0
  }
  for (var t = 0; t < names.length; t++) {
    for (var y of names.slice(t + 1)) {
      for (var r = 0; r < 2000; r++) {
        var res = game(names[t], y);
        if (res.res == 1) {
          leaderboard[names[t]]++
        } else if (res.res == 2) {
          leaderboard[y]++
        }
      }
    }
  }
  var o = [];
  for (var x in leaderboard) {
    o.push({
      n: x,
      s: leaderboard[x]
    })
  }
  o = o.sort((x, y) => y.s - x.s);
  var t = document.getElementById('t');
  t.innerHTML = '';
  t.innerHTML += `<tr><td>Name</td><td>Score</td></tr>`
  for (var d of o) {
    t.innerHTML += `<tr><td>${d.n}</td><td>${d.s}</td></tr>`
  }
}
```

```
<select id='f'></select> vs
<select id='f2'></select><button onclick='play()'>Play</button>
<pre><code id='g'></code></pre>Or start tournament: <button onclick='tournament()'>Go!</button>
<table id='t'></table>
```

# Leaderboard so far:

| Ranking | Name | User |
| --- | --- | --- |
| 1st | Ball pulling | Command Master |
| 2nd | Fraction | qwatry |
| 3rd | Waiter | 79037662 |
| 4th | Chair | user1502040 |
| 5th | Indecisive Tracker | aff |
| 6th | Vague Memory | histocrat |
| 7th | Table | user1502040 |
| 8th | Pacemaker | Ethertyte |
| 9th | Memory | histocrat |
| 10th | Exhauster | Sheik Yerbouti |
| 11th | Decay | Redwolf Programs |
| 12th | just1 | Spitemaster |
| 13th | random | Me (demo) |
| 14th | 25er | Me (demo) |

Command Master's "Ball pulling" mantains its spot in first. qwatry's new "Fraction" has jumped into second. The apparent tie between "waiter" and "chair" has been resolved by a 1v1 - "waiter" beats "chair", but they both score the same amount of points. aff's "Indecisive Tracker" uses the most complicated algorithm yet, but makes it into 5th place.

# Answer
# Ball pulling

```
"Ball pulling": function(myE, myPrev, pos) {
    return Math.max(1,Math.floor(myE * [0.10808232641486629,0.30174603004818334,0.2358032944932353,0.10406266397506114,0.25013297998583794,0.4608205872385916,0.5635474208925423][3-pos] + [-25.20386503823533,-4.62324162626722,-7.69195538879287,-5.7156191657689925,-3.221187031407233,-16.758418842577605,-4.233010800850232][3-pos] + Math.random() * [23.13539398461274,-3.257894925941551,-0.09547522996644178,-0.09187251666187485,-1.1010525700900573,-9.874021194357677,2.831769191532314][3-pos]));
}

```

JSFiddle

Calculates a linear function of the energy and a random number, with the exact function depending on the ball location.
> 5 votes

# Answer
# The demo bots

## Random

Outputs a random integer between 1 and 36.

```
function(myE,myPrev,pos){
    return Math.floor(Math.random() * 36) + 1;
}

```

## 25er

Outputs 25 all the time.

```
function(myE,myPrev,pos){
    return 25;
}

```

Note: These two are built into the controller - no need to add them.

Why is this the most popular?
> 9 votes

# Answer
# Memory

```
    "Memory": function(myE, myPrev, pos) {
    if (myPrev.length == 0) return 2;
    prev_pos = 0;
    for(i=0;i<myPrev.length-1;i++) {
        if (myPrev[i] > myPrev[i+1]) {
            prev_pos += 1;
        } else if (myPrev[i] < myPrev[i+1]) {
            prev_pos -=1;
        }
    }
    move = myPrev[myPrev.length-1]
    if (pos==3) return move;
    if(prev_pos > pos) {
        move = Math.ceil(move * 2.75);
    } else if (prev_pos < pos) {
        move = Math.ceil(move * 0.8);
    }
    return Math.max(1,Math.min(move, myE - 8));
}

```

Infers whether it won or lost last round from how it adjusted in previous rounds, and then adjusts.
> 9 votes

# Answer
# Table

```

"table": (myE, myPrev, pos) => {
    if (myE == 0) {
        return 0;
    }
    let w = [
      [-5.6544223, 0.06557736, -0.2641703],
      [0.75869083, -0.011340193, 1.4130216, -1.2559392],
      [0.13409477, 2.9561214, 0.27817196, 0.0030480723, 0.3889832],
      [-2.6868086, -0.3014877, 4.818155, 3.9265578, 1.7512726, 0.097844936],
      [0.68415153, 0.72050923, 1.334225, -1.6574494, 2.4933205, -0.25133085, -1.4409807],
      [1.6410222, -74.064156, -7.7318263, -0.01627013, 2.0059361, -6.7933116, -0.14581795, -1.6378351],
    ];
    let b = [1.8160640001296997, 1.5627140998840332, 3.7942299842834473, -2.4042959213256836, 2.8334028720855713, 312.232177734375];
    let log_weights = [];
    let log_weight_max = -Infinity;
    for (let m = 0; m < myE; m++) {
      let f = [m / (myE - 1), (myE - 50) / 29.15475947, 0.5 * pos, 0, 0, 0, 0, 0, 0];
      for (let l = 0; l < w.length; l++) {
        f[l + 3] = b[l];
        for (let i = 0; i < w[l].length; i++) {
          f[l + 3] += w[l][i] * f[i];
        }
        if (b[l] <= 300) {
          f[l + 3] = Math.max(f[l + 3], 0);
        }
      }
      let log_weight = f[f.length - 1];
      log_weight_max = Math.max(log_weight_max, log_weight);
      log_weights.push(log_weight);
    }
    let Q = 0;
    let M = 0;
    for (let m = 0; m < log_weights.length; m++) {
      let q = Math.exp(log_weights[m] - log_weight_max);
      Q += q;
      if (Math.random() * Q <= q) {
        M = m;
      }
    }
    return M + 1;
  }

```

Closely approximates the Nash equilibrium. Not exploitative enough to top the leader board.

# Chair

```

'chair': function(myE, myPrev, pos) {
    let c = 0x69b82a691f395b79b7fb2bb83cb5f2a40ce32e4a4c4a055f7c50e68a3f81e123197280dfbec638e3b036a9b53677122f2fa83447501ece2a63d766e983ff858cda2da01ac621bb3084c1055a2fe83e6a7450c29fa99549d3cc6f1c556550b2397f417e915b65d47a9d6c1b267aaab5171d3e8a7fbad4788e9cb795cdc11759ba232730ad0a3635a8a9c5564afdf5b82c380687a8af1b1f1ca4d36ac668b32cafe39afdda16421be9d955ce70cfab6c987dc407e97792f647a43ecd0f191fecdbc60ef782519410655f3054395cc0e1c68f893f416806ad502b9b945166b61110f7d72c0d5437d32235007c26b64f787f1147e3ce1966a4ff6fb564d47db1b191801e811052dd5c31bee7fed77afae4799debec9349e224155780fbd65684d2503356b0c71805a41994fd48f043ee745d8bc8e12bb8105cb97edef8e08f2d5467649aceb5ee668168420ad4b4b0d9c33cf4577b19827220dec3377c1bdf627fa1b3015b59b0a5e4b456f4d18abbbc4d22bde46c7596a7cbabb4536fa325561e50e1bdffeee5fb17a6222ae7f5d894c824920227b4f45aa369e8d3956b68ad8ba2499c5b4f925b42983544c1c9cbff22bb3774c138c0b04b47be0a91c73164b0729d0fd4521be988e78584d5974fc0083452e6127507a59956104d84ad3bc481325d21295ebfc63ea8c4708251a1df30a3f7e906b9acba9eda44f60091c6765466a6f9dbc5a83862ad358d0a41f7d4d099670b2e6302d9a1d5dbfb54a1698e3f9d9956ad90e53n;
    return myE <= 1 ? myE : Number((c / (83n ** BigInt(myE * 7 + pos - 11))) % 83n + 1n);
},

```

Uses a magic constant as a lookup table. Optimized against the current playing field.
> 7 votes

# Answer
# Decay

```
{
    "Decay": (energy, previous, position) => {
        return energy == 100 ? 30 : Math.ceil(energy * 0.15);
    }
}

```

Starts with 30 energy, which is enough to give it an initial lead. It then uses 15% of its remaining energy each turn.
> 6 votes

# Answer
# Waiter

```
"waiter": (myE, myPrev, pos) => {
  if (pos == 3) {
    // If 1 space from winning, spend all energy to try and win
    return myE;
  } else if (pos == 1) {
        return Math.max(1, Math.floor(myE * .06));
    } else if (pos == -3) {
    // If opponent is 1 space from winning, spend 82% energy to try and prevent them from winning, or spend 9 to counter Memory
    return myPrev.length < 9 ? Math.ceil(myE * .82) : Math.min(9, Math.ceil(myE * .82));
  } else if (myPrev.length < 1) {
    // If fewer than 1 turn has been played, "wait" and only spend 1 energy
    return 1;
  } else {
    // Otherwise spend up to 12% of energy
    return Math.max(1, Math.floor(myE * .12));
  }
}

```

Update `2021-04-03T21:14:04Z` \- Changing 0.3 to 0.2 seems to improve performance against the current bots: https://jsfiddle.net/jwnsq917/

Update `2021-04-04T16:47:32Z` \- Changing 0.2 to 0.12 improves performance against the current bots, in particular BallPulling: https://jsfiddle.net/qd80eofc/1/

Update `2021-04-05T13:26:19Z` \- Changing 2 to 1 improves performance against the current bots: https://jsfiddle.net/3sqftja7/

The trend of "slightly adjust values to pull ahead" continues.

Update `2021-04-05T13:37:16Z` \- Add case for when opponent is 2 spaces from winning: https://jsfiddle.net/3sqftja7/5/

Update `2021-04-05T15:10:57Z` \- Add hard counter for Memory: https://jsfiddle.net/egnwLb3r/

Update `2021-04-07T14:06:56Z` \- More minor adjustments to once again take top spot: https://jsfiddle.net/ceL2as16/1/

I suspect that due to the fact that minor changes can make a bot win against other bots, the winner of this challenge will simply be the last person to make their bot hard-counter the other bots, possibly by updating their bot in secret.
> 5 votes

# Answer
# Exhauster

```
"Exhauster": (myE,myPrev,pos) => {
    return pos == -3 ? 28 - myPrev.length : 3;
}

```

It uses 3 units of energy in every turn, except when the opponent is at one step from the victory.
> 5 votes

# Answer
# Just1

```
"just1": (myE, myPrev, pos) => {
    return pos === -3 ? Math.ceil(myE / 4) : 1;
}

```

Waits out its opponent - it bids 1 unless it'd lose if it doesn't spend more - then it spends 25% of its current energy.
> 5 votes

# Answer
# Vague Memory

```
"Vague Memory": function(myE, myPrev, pos) {
    if (myPrev.length == 0) return 2;
    prev_pos = 0;
    for(i=0;i<myPrev.length-1;i++) {
        if (myPrev[i] > myPrev[i+1]) {
            prev_pos += 1;
        } else if (myPrev[i] < myPrev[i+1]) {
            prev_pos -=1;
        }
    }
    move = myPrev[myPrev.length-1]
    if (pos==3) return move;
    if(prev_pos > pos) {
        move = Math.ceil(move * 2.75 - 2.4*Math.random());
    } else if (prev_pos < pos) {
        move = Math.ceil(move*0.8);
    }
    min_move = Math.round(3.5 * Math.random());
    if(pos < -1) min_move += 2;
    return Math.max(min_move,Math.min(move, myE - 28));
}

```

Same as Memory, this tries to hone in the right value by adjusting up when it loses a round and down when it wins one. But to make it harder to tune against, this one randomly saves energy toward the beginning and randomly spends it toward the end.
> 4 votes

# Answer
# Pacemaker

```
"Pacemaker": (myE, myPrev, pos) => {
  if (myPrev.length === 0) return 4; // https://xkcd.com/221/
  if (pos === 3) return Math.round(myE * 0.99);
  if (pos === -3) return Math.max(1, Math.round(myE * 0.4));
  return Math.max(1, Math.min(myE, Math.round(myE / (7 - pos))));
}

```

Tries to pace itself based on how many more rounds it expects the game to last. Goes all in if it's one win away from victory, goes in heavy if it's one loss away from complete loss.

I also tried out similar ideas with nondeterminism, but the hardcoded logic one performed better in all my variations.

Update: Increasing the plan-ahead time from 4 to 7 rounds seems to fair better so I've updated the parameter. Previously, initial rounds were too greedy, spending a lot of energy early on.
> 2 votes

# Answer
# Indecisive Tracker

```
'Indecisive Tracker': (myE, myPrev, pos) => {
  const RESULT = { WIN: 0, DRAW: 1, LOSE: 2 }
  const RESULT_ENCODING_OFFSET = [0, 1, 2]
  const RESULT_WEIGHT = [1, 0, -1]
  const MIN_SPENDING = 1
  const posToAggressionFactor = [0, 0.3, 0.2, 0, 0, 0, 0.1, 0.8, 0]
  const posToRiskAppetite = [0, 1, 0.4, 0.1, 0.1, 0.1, 0.2, 0.3, 0]
  let encodeResult = (E, lastResult) => E + RESULT_ENCODING_OFFSET[lastResult]
  let decodeResult = (E) => RESULT_ENCODING_OFFSET.findIndex(e => e === (E - MIN_SPENDING) % RESULT_ENCODING_OFFSET.length)
  let getResultFromPos = (posBefore, posAfter) => {
    return posBefore < posAfter ? RESULT.WIN
         : posBefore > posAfter ? RESULT.LOSE
                                : RESULT.DRAW
  }
  let BallMove = (prevPos, currE, nextE, finalPos) => {
    let currResult = nextE == null ? getResultFromPos(prevPos, finalPos)
                                   : decodeResult(nextE)
    let nextPos = prevPos + RESULT_WEIGHT[currResult]
    let enemyE = currResult === RESULT.LOSE ? currE + 1
               : currResult === RESULT.DRAW ? currE
                                            : 1
    return {
      enemyE: enemyE,
      myE: currE,
      posBefore: prevPos,
      posAfter: nextPos,
      result: currResult
    }
  }
  const GOAL = 8
  let normalizedPos = pos + 4
  let goalDistance = GOAL - normalizedPos
  let minimumReservedEnergyPerTileDistance = 3
  let spendableEnergy = myE - ((goalDistance - 1) * minimumReservedEnergyPerTileDistance)
  let prevPos = 0
  let prevResult = RESULT.DRAW
  let gameMoves = new Array()
  for (i = 0; i < myPrev.length; i++) {
    let currMove = BallMove(prevPos, myPrev[i], myPrev[i+1], pos)
    prevPos = currMove.posAfter
    prevResult = currMove.result
    gameMoves.push(currMove)
  }
  let myRandom = (min, max, spacing) => {
    if ((spacing ?? 0) === 0) spacing = 1
    let maxEncodingOffset = Math.max.apply(null, RESULT_ENCODING_OFFSET)
    let adjustedMin = Math.floor((min + maxEncodingOffset) / spacing) * spacing
    let offset = adjustedMin
    let adjustedMax = max - offset - maxEncodingOffset
    let adjustedRange = Math.floor(adjustedMax / spacing) + 1
    return Math.floor(Math.random() * adjustedRange) * spacing + offset
  }
  let minE = spendableEnergy * posToAggressionFactor[normalizedPos]
  let maxE = spendableEnergy * posToRiskAppetite[normalizedPos]
  let nextE = MIN_SPENDING + myRandom(minE, maxE, RESULT_ENCODING_OFFSET.length)
  let encodedNextE = encodeResult(nextE, prevResult)
  return encodedNextE
}

```

Tries to encode last round's winning/losing information on the spent energy, then deduce (conservatively) the game rounds info. But it fails to decide what to do with the data...

Ultimately, the bot uses *lookup value based on the ball's position* to decide that round's minimum and maximum factors, which will be fed into a random function.

The lookup values themselves are initially based on intuition and then some test run until I got a good-enough result for me. So, you can say that they are partially based on the other bots' behavior.
> 2 votes

# Answer
# Fraction

```
 "Fraction": function(myE, myPrev, pos) {
   return ((myPrev.length===3)&&(pos===-3))? 25 : Math.floor(myE/(pos+4)*0.395)
 },

```

I was just messing around and I discovered this simple solution that surprisingly does fairly well!

¯\\\_(ツ)\_/¯
> 2 votes

---
Tags: king-of-the-hill, javascript
---


title: Repeating terms of a given sentence

text:
# Question
Title: Repeating terms of a given sentence
**Program**

Write a program to display repeating terms of a given sentence.

**Explanation**

The program must output the repeating terms of two or more letters from the given input (input is a sentence separated by spaces without any punctuation except the full-stop indicating the end.) Repeated terms may not span across or include a space. For example, if input is the sentence "I **am** **an** **am**eture **ma**the**ma**gici**an**" the output must be am, ma, an. (note that "em" is not a valid output as it is separated by space).

Repeated terms may overlap with each other. For example if the input is "ababa", the output should include "aba", even though the two instances of it overlap.

```
ababa
aba
  aba

```

**Example**

Input:

> International competitions are better than intercollege ones.

Output:

> Inter, ti, er, tion, io, on, ion, tio, co, on, .......etc (t, l must not be included as they are 1 letter.) (Upper lower Cases do not matter)

**Test cases**

```
aabcde cdec -> cde, cd, de

aab aacab -> aa, ab

aaa aabcaaa ababa -> aaa, aa, ab, aba, ba

abababa-> ab, aba, abab, ababa, ba, bab, baba

```

**Winning Criterion**

# Answer
> 2 votes
# JavaScript (ES10), 99 bytes

```
s=>new Set([...s].map((q,i,a,j=i)=>a.map(_=>s.lastIndexOf(q+=s[++i])>j&!/ /.test(q)?q:[])).flat(2))

```

Try it online!

# Answer
> 1 votes
# Python 3, 119 bytes

```
lambda s:{''.join(y) for x in range(2,len(s))for y in permutations(s,x)if s.count(''.join(y))>1}
from itertools import*

```

Try it online!

Extremely slow... Works by calculating permutations

# Answer
> 1 votes
# Japt `-g`, 14 bytes

```
ã køS fÅü lÉ y

```

Try it

* saved 4 thanks to @Shaggy

```
    ã       - substrings
    køS     - remove if contains space
    fÅ     - take longer than 1
    ü       - sort and group
    lÊ     - take groups longer than 1
    y      - transpose
    -g flag to return first element

```

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