title: Print the Greek national anthem

text:
# Question
Title: Print the Greek national anthem
In March 25, 1821, Greece fought its great war of independence. In order to honor this, your task is to print the Greek national anthem:

```
Σε γνωρίζω από την κόψη
του σπαθιού την τρομερή.
Σε γνωρίζω από την όψη
που με βιά μετράει τη γη.
Απ' τα κόκκαλα βγαλμένη,
των Ελλήνων τα ιερά!
Και σαν πρώτα ανδρειωμένη,
χαίρε ω χαίρε Λευτεριά!
Και σαν πρώτα ανδρειωμένη,
χαίρε ω χαίρε Λευτεριά!
Και σαν πρώτα ανδρειωμένη,
χαίρε ω χαίρε Λευτεριά!

```

This is my own version of the anthem (punctuation, capitalization), although the lyrics are the original.

* Any builtins printing or returning this text are forbidden, just in case.
* The printed text must be exactly as above, with an optional trailing newline.
* The output must be in UTF-8, unless it can't be supported at all, in which case the output must be encoded in the closest supported alternative.

# Answer
# Jelly, ~~180~~ ~~174~~ 163 bytes

```
60r26;“WSNME‘ȷ_Ọ;“ ¶.',!”“¢Iç÷ṀDė3H⁷'UBV“ñẸḣY]ṭżẸ-dƒjṭ{^ṣ8ḞkƊK“ẈḊbƝÑk?Æ.)Aɱ3ẎƬṠ⁵ʂ÷Gẏp⁴ṇ1ẸR ¬,F°0>ST$[?ṘȦŀẎcFẈṃijȯÆḋ“¦ḟw2ðƊhSẏ¥ẏ5ƒẉɦ⁺Ʋ⁴Ɓ¦ÞIzƥṙḊOḊ-÷~øWḤ0ṃ’ṃ€6676ḃ4¤ị

```

Try it online!
> 7 votes

# Answer
# Python 3, 263 bytes

```
s="BT R\h`NUh P_k cV\ %skgV\n"
print(''.join(i if 47>ord(i)else chr(ord(i)+865)for i in s%"Y"+"c^d b_PWX^l cV\ c`^[T`M.\n"+s%""+"_^d [T QXK [Tc`KTX cV RV.\n0_' cP YkYYPZP QRPZ[L\V,\nch\ 4ZZM\h\ cP XT`K!"+"\n9PX bP\ _`mcP P\S`TXh[L\V,\nfPN`T h fPN`T :TdcT`XK!"*3))

```

Try it online!
Use the same repetition technique that mbomb007 used, but I replaced all characters higher than 47 (all greek letters), u913~u974 with u48~u109 ,and then undo this before printing
> 4 votes

# Answer
# Java 7, ~~320~~ ~~319~~ ~~300~~ ~~294~~ 293 bytes

```
void Z(){String a="AS Q[g_MTg O^j bU[ ",b="8OW aO[ ^_lbO O[R_SWgZK[U,\neOM_S g eOM_S 9ScbS_WJ!\n";for(char C:(a+"XjfU\nb]c a^OVW]k bU[ b_]ZS_L.\n"+a+"jfU\n^]c ZS PWJ ZSb_JSW bU QU.\n/^' bO XjXXOYO PQOYZK[U,\nbg[ 3YYL[g[ bO WS_J!\n"+b+b+b).toCharArray())System.out.print((char)(C>46?C+866:C));}

```

Try it online!

This outputs the anthem with a trailing newline. I converted the function from returning a `String` to a `void` so that it would print the String instead of returning it and save bytes.

~~Will golf further in the morning~~ Golfers don't sleep :P

### Explanation (outdated)

```
String Z(){
  // X contains the value of the Greek Anthem
  String X="",
  // a and b contain some repeated parts of the anthem
         a="AS Q[g_MTg O^j bU[ ",
         b="8OW aO[ ^_lbO O[R_SWgZK[U,\neOM_S g eOM_S 9ScbS_WJ!\n";
  // Then we loop over every char in this string
  for(char C: (a+"XjfU\nb]c a^OVW]k bU[ b_]ZS_L.\n"+a+"jfU\n^]c ZS PWJ ZSb_JSW bU QU.\n/^' bO XjXXOYO PQOYZK[U,\nbg[ 3YYL[g[ bO WS_J!\n"+b+b+b).toCharArray())
    // Adding 866 to the char if it is greater than `.` 46
    // (we also want to preserve the punctuation)
    X+=(char)(C>46?C+866:C);
  return X;
}

```

To get to this reduced String, I manually checked subtracting which numbers from the code points would be the best. These values would have to lie between  and `~`. In order to make the detection of whether a char is punctuation (`.`, `'`, `!`, ) or not, it would be best if all the values lied above `.` (46). And there shouldn't be any `\`s in the String because otherwise Java thinks they are escape sequences, and so I have to escape them. Finally I came up with subtracting 866 from the Greek characters.
> 4 votes

# Answer
# Python 3, ~~350~~ 345 bytes

```
s="Σε γνωρίζω από την %sόψη\n"
print(s%'κ'+"του σπαθιού την τρομερή.\n"+s%''+"που με βιά μετράει τη γη.\nΑπ' τα κόκκαλα βγαλμένη,\nτων Ελλήνων τα ιερά!"+"\nΚαι σαν πρώτα ανδρειωμένη,\nχαίρε ω χαίρε Λευτεριά!"*3)

```

**Try it online**
> 3 votes

# Answer
# PowerShell, ~~332~~ ~~270~~ 261 bytes

```
-join([char[]]"$(($a='=O MWc[IPc KZf ^QW')) TfbQ
^Y_ ]ZKRSYg ^QW ^[YVO[H.
$a fbQ
ZY_ VO LSF VO^[FOS ^Q MQ.
+Z' ^K TfTTKUK LMKUVGWQ,
^cW /UUHWcW ^K SO[F!
$('4KS ]KW Z[h^K KWN[OScVGWQ,
aKI[O c aKI[O 5O_^O[SF!
'*3)"|%{([char](870+$_),$_)[+$_-in10,32,33,39,44,46]})

```

Try it online!

This takes the munged string as a `char`-array, feeds it one at a time through a loop `|%{...}` each iteration either outputting the character straight `$_` or incrementing it by `870` before re-casting as a `char` (based on whether it's a punctuation or not). A few other tricks sets `$a` as a repeat phrase, and de-triplicates the last three stanzas. Those are all `-join`ed together into a full string and then output is implicit.

*Edit - Woo! This is the 1100th PowerShell answer on the site! :D*
> 3 votes

# Answer
## Windows 10 Batch, ~~424~~ 404 bytes

```
@chcp>nul 65001
@set s="Σε γνωρίζω από την κόψη"
@set t="Και σαν πρώτα ανδρειωμένη," "χαίρε ω χαίρε Λευτεριά!"
@for %%l in (%s% "του σπαθιού την τρομερή." %s:κ=% "που με βιά μετράει τη γη." "Απ' τα κόκκαλα βγαλμένη," "των Ελλήνων τα ιερά!" %t% %t% %t%) do @echo %%~l

```

Notes:

* Don't use Notepad to save this, it will add a BOM which will cause the script to fail.
* The `chcp` call fails if your Command Prompt is configured to use Raster Fonts. Change them to e.g. Lucida Console (does not require restart).
* The batch file seems to require a reasonably new version of Windows; Windows XP wasn't at all happy with `chcp 65001`.

Edit: Saved 20 bytes thanks to @ConorO'Brien.
> 3 votes

# Answer
# Bubblegum, 190 bytes

```
0000000: d5 8e b5 61 04 51 10 43 f3 ad 62 9c 98 ed 16 cd  ...a.Q.C..b.....
0000010: cc 4c a1 c3 e3 bb 65 ec 40 6a c9 9a 6f cc 1c df  .L....e.@j..o...
0000020: f2 8c a4 b7 c2 3b 12 c3 0c 0d 4f b8 83 11 52 9e  .....;....O...R.
0000030: 18 26 dc e6 b9 71 1f 19 1a 43 c9 73 1e 23 8b 34  .&...q...C.s.#.4
0000040: 77 3c 30 ee 71 1b 13 e4 28 34 5e 7c b9 f4 52 bc  w<0.q...(4^|..R.
0000050: 43 8d 44 ef e1 66 f4 3f f7 9b ba 1d a8 9e 34 4c  C.D..f.?......4L
0000060: 05 ed 87 ef c0 eb 23 41 11 fc 8e ca 44 bd e1 f6  ......#A....D...
0000070: 92 2f 26 a1 16 4a 9d 13 54 3e 4e e5 d0 a7 b2 03  ./&..J..T>N.....
0000080: 34 c8 d6 55 97 27 5e ff 01 95 ce 21 1a 1f bf b2  4..U.'^....!....
0000090: 45 a8 d9 5f 88 f0 8a 89 ff 62 4f 2f 89 db dc e1  E.._.....bO/....
00000a0: 65 b0 f8 8c 58 26 35 50 f0 97 7a 24 65 e4 7b e3  e...X&5P..z$e.{.
00000b0: 89 fd 99 f0 26 e6 81 b2 4e 2e e6 99 fd 01        ....&...N.....

```

Try it online!
> 3 votes

# Answer
# Japt, ~~197~~ ~~196~~ 195 bytes

```
`0fxtc
pkq ol]¸ky2ci2mk?mZ.
0xtc
lkq ? ^eX ?pmXae2c _c.
=l'2] fxff]g] ^_]g1pui AggZiui2] eamX!`+`
F]e o]i lmzp] ]i\`µeu1s][µ u s][µ Gaqpa´X!`³ d0`Oa _ium[¿ ]lx2ci `1`hYic,
`2" p""[=F-~]"_c +852 d

```

Test it online! Contains three 0x95 bytes which have been replaced with `?`.
> 2 votes

# Answer
# ///, ~~324~~ 323 bytes

```
/P/ρ//p/π//n/η//z/Σε γνωρίζω από τnν //k/Και σαν pPώτα ανδPειωμένn,
χαίPε ω χαίPε ΛευτεPιά!/zκόψn
του σπαθιού τnν τPομεPή.
zόψn
pου με βιά μετράει τn γn.
Αp' τα κόκκαλα βγαλμένn,
των Ελλήνων τα ιεPά!kkk

```

Try it online!

Maybe it could be golfed more, but I'm tired.

It works by replacing characters like `k` with longer text. I also made some character substitutions, because the Greek characters have more bytes than characters like `p`. Simple enough.

-1 byte thanks to @ErictheOutgolfer.
> 2 votes

# Answer
# Bubblegum, ~~194~~ 187 bytes

```
00000000: d58e 3542 0541 1005 f33d c590 e070 45dc  ..5B.A...=...pE.
00000010: dd2d 2444 d77d f706 f5ae c4f4 a019 f18f  .-$D.}..........
00000020: daab 8b47 7247 4aaf 3dad f146 a13d 47ac  ...GrGJ.=..F.=G.
00000030: 551d 3a6d 52d2 3b1a 1d6a 9732 f2f5 a82d  U.:mR.;..j.2...-
00000040: a70d ad12 5351 fbf2 e87b 4b9b 5a63 a423  ....SQ...{K.Zc.#
00000050: d71a afcb d1ff dc6f ea6a a0da a523 a1e6  .......o.j...#..
00000060: 39e4 81f7 4c4e 1df6 0d55 7aea 9956 67ac  9...LN...Uz..Vg.
00000070: 1107 2d1a 1a62 5a2b 13d2 9076 bcd0 532e  ..-..bZ+...v..S.
00000080: 7a5d ed99 fe15 2d2d aff4 567e ddd6 e486  z]....--..V~....
00000090: 9f8a b827 b617 1bc4 365c d59a 8ec3 8ad5  ...'....6\......
000000a0: 645a 3303 edfd a1ee 10f3 667d a73d f7a7  dZ3.......f}.=..
000000b0: e281 5c5b da0c e47a 92d9 1f              ..\[...z...

```

You can reverse this hexdump with `xxd -r`.

Thanks Dennis for redirecting me to Zopfli :)
> 1 votes

# Answer
# Python 2.7, 190 bytes

zlib abuse. Hexdump:

```
00000000: efbb bf70 7269 6e74 2278 9cbd 8cb1 0e82  ...print"x......
00000010: 4010 44fb fb8a b5b2 31fc 7f6b 61a3 252d  @.D.....1..ka.%-
00000020: 4216 5ccf e5b8 701b 96e8 2568 5ca5 b4b7  B.\...p...%h\...
00000030: 7ac9 cc9b 2909 ba98 a5b9 66c0 b480 fa08  z...).....f.....
00000040: fdf2 f04e c719 a684 371e 9fdf 5065 1c48  ...N....7...Pe.H
00000050: eac2 95bf 838f 9fcc 1f08 5aae 0c2a 15b1  ..........Z..*..
00000060: 55d0 f9c2 edd3 1614 edb5 ef31 20b4 1d86  U..........1 ...
00000070: e11c fdce 698e 7008 a18e 4613 98a4 dab8  ....i.p...F.....
00000080: 2332 4c18 21c9 cb32 8c17 21ce ab7f c746  #2L.!..2..!....F
00000090: 0832 ac3c d1ac 24fc afc9 1bcf bfdc ec22  .2.<..$........"
000000a0: 2e64 6563 6f64 6528 227a 6970 2229 2e64  .decode("zip").d
000000b0: 6563 6f64 6528 2267 7265 656b 2229       ecode("greek")

```

As @Dennis points out, this needs to be run in a terminal in order for it to correctly produce UTF-8 output.
> 1 votes

# Answer
# Bash + GNU iconv, 214

```
a="�� ������� ��� ��� "
l="
��� ��� ����� �����������,
����� � ����� ��������!"
iconv -f GREEK<<<"$a����
��� ������� ��� �������.
$a���
��� �� ��� ������� �� ��.
��' �� ������� ��������,
��� ������� �� ����!$l$l$l"

```

This just uses the `iconv` utility to convert from the GREEK encoding (byte per char) to utf-8, along with removing a bit of redundancy by storing repetitions in variables.

Don't try to copy directly from the above - lots of unprintables get munged when pasting. Instead, create the script as follows:

```
base64 -d << EOF > greek.sh
YT0i0+Ug4+358d/m+SDh8Pwg9OftICIKbD0iCsrh6SDz4e0g8PH+9OEg4e3k8eXp+ezd7ecsCvfh
3/HlIPkg9+Hf8eUgy+X19OXx6dwhIgppY29udiAtZiBHUkVFSzw8PCIkYer8+OcK9O/1IPPw4ejp
7/0g9OftIPTx7+zl8d4uCiRh/PjnCvDv9SDs5SDi6dwg7OX08dzl6SD05yDj5y4KwfAnIPThIOr8
6urh6+Eg4uPh6+zd7ecsCvT57SDF6+ve7fntIPThIOnl8dwhJGwkbCRsIg==
EOF

```
> 1 votes

# Answer
# PHP, 296 Bytes

```
<?=gzinflate(base64_decode("1Y+9DoJAEIR7Et7hrGyMz3gEiJKgiYWNlrYIAUXkL7zB7Cs5e0ZDZ22u2Nvdme/mcEFtcMMoiQQo8JDEoBQrqZEIDUaDTlLZovE9DiaJjYRiUeKJlu3uI5OI/gkDatZ87Xv4Sf5yreOq16AiNnN3R8xQo3UGZTXKPYhd6qR00dDxlOi1rSjR64ArRjQrjSyJ/uHIaY9cw7isqm5d1GxB5Ik2vhKycGslkP1bwx53qhiCzhl3w1WhC8NvzTqcSY1pVnb75/QX"));

```

## PHP, 349 Bytes

```
echo$y="Σε γνωρίζω από την"," κόψη\nτου σπαθιού την τρομερή.\n$y όψη\nπου με βιά μετράει τη γη.\nΑπ' τα κόκκαλα βγαλμένη,\nτων Ελλήνων τα ιερά!\n".$z="Και σαν πρώτα ανδρειωμένη,\nχαίρε ω χαίρε Λευτεριά!\n",$z.$z;

```
> 1 votes

# Answer
## Retina, 199 bytes

```

:pkq olWdeky=ci=mkhamT._:lkq ha XeR hapmRae=c Yc._0l'=W fxffWgW XYWghSic,_pui 4ggTiui=W eamR!###
:
Ia YiumUbu Wlx=ci fxtc_
#
_9We oWi lmzpW WiZmaeuhSic,_;u ;AaqpameR!
=
 p
;
sWUma
2=`f

T`w`¶Α-ώ

```

Try it online!

Woohoo, just under 200 bytes.

### Explanation

The main idea is to avoid the actual Unicode characters for the most part, because they just blow up the byte count if they are used everwhere. Instead, I represent each Greek letter by an ASCII letter or digit. It turns out that the relevant letters from `Α` (that's an alpha) to `ώ` span exactly 62 code points. That's 10 + 26 + 26, the number of ASCII digits and letters. The other Unicode character we've got is , which Retina uses to represent linefeeds. We can save a few more bytes by replacing that with `_`. Then the shorthand `w` in transliteration stages contains exactly the 63 characters we've used as substitutions, and we can represent the range this is mapped to using only 3 2-byte characters ( and the two ends of the Greek letter range).

Hence, the code is fairly illegible for the most part, since this substitution is done in the very last stage. Let's undo this to make a bit more sense of the code:

```

:του σπαθιού=ην=ρομερή.¶:που με βιά μετράει=η γη.¶Απ'=α κόκκαλα βγαλμένη,¶των Ελλήνων=α ιερά!###
:
Σε γνωρίζω από=ην κόψη¶
#
¶Και σαν πρώτα ανδρειωμένη,¶;ω ;Λευτεριά!
=
 τ
;
χαίρε
2=`κ

```

That looks a bit more like the stuff we want to output. The very first stage simply sets up the overall framework. It contains all the unique parts of the output as well as some more placeholders for repeated parts:

* `:` stands for the first and third line. They end up being *slightly* different, because the `κ` is missing from the third line, which is why the very last stage removes the second `κ` in the result.
* `#` stands for the last two lines, which are repeated three times.
* `;` stands for the repeated `χαίρε` in those lines.
* `=` stands for a word beginning with `τ` (and the space preceding it). There are *just* enough of those for this to save a single byte.
> 1 votes

# Answer
# Jolf, 187 bytes

Being encoded in the greek codepage helps.

```
ΆΆγ"Σε γνωρίζω από την κόψη
'του σπαθιού την τρομερή.
"-γ'κ«που με βιά μετράει τη γη.
Απ' τα κόκκαλα βγαλμένη,
των Ελλήνων τα ιερά!
»*3"Και σαν πρώτα ανδρειωμένη,
χαίρε ω χαίρε Λευτεριά!

```

Try it here! *It's all greek to me...*
> 0 votes

# Answer
# Python 3, 246 bytes

```
q=b'Qc akwo]dw _nz rek '
print(''.join(chr(b+b//63*850)for b in
q+b'hzve\nrms qn_fgm{ rek romjco\.\n'+q+b"zve\nnms jc `gZ jcroZcg re ae.\n?n' r_ hzhh_i_ `a_ij[ke,\nrwk Cii\kwk r_ gcoZ!"+b'\nH_g q_k no|r_ _kbocgwj[ke,\nu_]oc w u_]oc IcsrcogZ!'*3))

```

Try it online!

My take on Rod’s approach.
> 0 votes

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


# Question
Title: This is the sort of challenge that bytes
*I need to stop thinking of punny names*

Your task is to create as many snippets (programs that have input and output built-in), functions or full programs as possible that sorts whatever your language's version of integer arrays is in ascending order, but for each program, you're only allowed to use the characters in ASCII (or your language's code page, if it's directly specified as not ASCII) which haven't been used in the previous programs.

This is an example answer (separate programs separated by newlines):

```
Derp
ASdFGHJKLAAA
qwEEERtyRty

```

In this (fictional language), my first answer is `Derp`, which used up `D`, `e`, `r` and `p`. In the second program, I'm not allowed to use those character again, but I can reuse as many characters I want. Same with the third program, and so on.

Each program must take an array of integers, so something like this (see input/output examples for valid input/output styles):

```
[3 4 -2 5 7 196 -44 -2]

```

And it must output the items in the array as an array, in ascending order:

```
[-44 -2 -2 3 4 5 7 196]

```

**Your score will be the total amount of submissions. If there is a tie, the lowest bytecount (least amount of bytes in your code) wins!**

## Rules for programs:

* All submissions must run correctly in one language version (so `Python 2 != Python 3`).
* Your submissions can be snippets, functions, or full programs. You're even allowed to mix and match them - however, you must say which is which, and provide links to working submissions.
* Please provide online links to all solutions, if possible.
* All submissions must take an array (or a string delimited with any character) as input, and output the array sorted (in your language's array form or as a `{any character}`-delimited string.
* You are not allowed to use any characters outside of ASCII (or your language's code page).

For example, these are valid inputs/outputs:

```
[1 2 3 4]    (Clojure style arrays)
[1, 2, 3, 4] (Python style arrays)
1 2 3 4 5    (Space-delimited - separated by spaces)
1#2#3#4#5    ("#"-delimited - separated by "#" characters)
1\n2\n3\n4\n (newline-delimited)

```

## Specs for input:

* You are guaranteed that the array contains only integers. However, there may be negative numbers, and numbers may repeat indefinitely.

# Answer
> 15 votes
# Jelly, 10 programs, 65 bytes

```
Ṣ
¹Þ
Ụị
Œ!Ṃ
7778Ọv
Ẋ>2\S$¿
ĠFḣṪ¥@€
~Ṁ~rṀxLœ&
C»/ð+ÆNPÆfÆC_ḷ
<þḅ1‘WiþJḄ³ṫZḢ

```

There's some inevitable overlap with @Lynn's Jelly answer. Credits for the bogosort idea go to her.

Try it online! or verify uniqueness.

### How they work

```
Ṣ               Main link. Argument: A (array)

Ṣ               Sort A.

```

```
¹Þ              Main link. Argument: A (array)

¹Þ              Sort A, using the identity function as the key.

```

```
Ụị              Main link. Argument: A (array)

Ụ               Grade up; yield all indices of A, sorted by their corr. values.
 ị              Index into A.

```

```
Œ!Ṃ             Main link. Argument: A (array)

Œ!              Yield all permutations of A.
  Ṃ             Minimum; yield the lexicographically smallest permutation.

```

```
7778Ọv          Main link. Argument: A (array)

7778Ọ           Unordinal; yield chr(7778) = 'Ṣ'.
     v          Evaluate with argument A.

```

```
Ẋ>2\S$¿         Main link. Argument: A (array)

      ¿         While the condition it truthy, execute the body.
 >2\S$            Condition:
     $              Combine the two links to the left into a monadic chain.
 >2\                  Perform pairwise greater-than comparison.
    S                 Sum; add the results.
                    This returns 0 iff A contains an unsorted pair of integers.
Ẋ                 Body: Shuffle A.

```

```
ĠFḣṪ¥@€         Main link. Argument: A (array)

Ġ               Group the indices of A by their sorted values.
 F              Flatten the result.
      €         Apply the link to the left to each index in the previous result,
                calling it with the index as left argument and A as the right one.
    ¥@            Combine the two links to the left into a dyadic chain and swap
                  its arguments, so A is left one and the index i is the right one.
  ḣ               Head; take the first i elements of A.
   Ṫ              Tail; yield the last of the first i, i.e., the i-th element of A.

```

```
~Ṁ~rṀxLœ&       Main link. Argument: A (array)

~               Take the bitwise NOT of all integers in A.
 Ṁ              Take the maximum.
  ~             Take the bitwise NOT of the maximum, yielding the minimum of A.
    Ṁ           Yield the maximum of A.
   r            Range; yield [min(A), ... max(A)].
      L         Yield the length of A.
     x          Repeat each integer in the range len(A) times.
       œ&       Take the multiset-intersection of the result and A.

```

```
C»/ð+ÆNPÆfÆC_ḷ  Main link. Argument: A (array)

C               Complement; map (x -> 1-x) over A.
 »/             Reduce by dyadic maximum, yielding 1-min(A).
   ð            Begin a new, dyadic chain. Arguments: 1-min(A), A
    +           Add 1-min(A) to all elements of A, making them strictly positive.
     ÆN         For each element n of the result, yield the n-th prime number.
       P        Take the product.
        Æf      Factorize the product into prime numbers, with repetition.
          ÆC    Prime count; count the number of primes less than or equal to p,
                for each prime p in the resulting factorization.
             ḷ  Yield the left argument, 1-min(A).
            _   Subtract 1-min(A) from each prime count in the result to the left.

```

```
<þḅ1‘WiþJḄ³ṫZḢ  Main link. Argument: A (array)

<þ              Construct the less-than matrix of all pairs of elements in A.
  ḅ1            Convert each row from base 1 to integer (sum each).
    ‘           Increment. The integer at index i now counts how many elements
                of A are less than or equal to the i-th.
     W          Wrap the resulting 1D array into an array.
        J       Yield the indices of A, i.e., [1, ..., len(A)].
      iþ        Construct the index table; for each array T in the singleton array
                to the left and index j to the right, find the index of j in T.
                This yields an array of singleton arrays.
         Ḅ      Unbinary; convert each singleton from base 2 to integer, mapping
                ([x]-> x) over the array.
          ³     Yield A.
           ṫ    Tail; for each integer i in the result of `Ḅ`, create a copy of A
                without its first i-1 elements.
            Z   Zip/transpose. The first column becomes the first row.
             Ḣ  Head; yield the first row.

```

# Answer
> 15 votes
# Jelly, 8 programs

```
Ṣ                   Built-in sort.
¹Þ                  Sort-by the identity function.
Ụị                  Sort indices by values, then index into list.
Œ!Ṃ                 Smallest permutation.
7778Ọv              Eval Unicode 7778 (Ṣ).
ẊI>@-.S$$¿          Bogosort.
<;0œṡ0⁸ṁjµ/         Insertion sort.
AṀ‘¶+Ç©ṬT_©®³ċÐ€®x' A terrifying hack.

```

The last program is really annoying…

```
AṀ‘¶+Ç©               Add ® = abs(max(L)) + 1 to the entire list.
                      Now it’s offset to be entirely positive.
       Ṭ              Create a binary array with 1s at these indices.
        T             Find the indices of 1s in this array.
                      The result is sorted, but offset wrong, and lacks duplicates.
         _©®          Subtract the offset, saving this list to ®.
                      Now restore the duplicates:
            ³ċÐ€      Count occurences in the original list.
                ®x'   Repeat the elements of ® that many times.

```

If I can remove the `œṡ` from `<;0œṡ0⁸ṁjµ/`, there’s also this weird one: `²SNr²ZFœ&`. Help is appreciated.

# Answer
> 14 votes
# 05AB1E, score = 6

**05AB1E** uses CP-1252 encoding.

Thanks to *Kevin Cruijssen* for program 4.
Thanks to *Riley* for inspiration to program 6.

**Program 1**

```
{               # sort

```

Try it online!

**Program 2**

```
`[Ž.^]¯

`               # flatten input list to stack
 [Ž  ]          # loop until stack is empty
   .^           # add top of stack to global list in sorted order
      ¯         # push global list

```

Try it online!

**Program 3**

```
WrZŠŠŸvy†

Wr              # get minimum value in input list and reverse stack
  ZŠ            # get maximum value in input list and swap move it to bottom of stack
    Š           # move input down 2 levels of the stack
     Ÿ          # create a range from max to min
      v         # for each y in range
       y†       # move any occurrence of it in the input list to the front

```

Try it online!

**Program 4**

```
œß

œ               # get a list of all permutations of input
 ß              # pop the smallest

```

Try it online!

**Program 5**

```
êDgFDNè¹sUXQOFXs}}\)

ê                      # sort with duplicates removed
 Dg                    # duplicate and get length
   F                   # for N in [0 ... len-1] do
    DNè                # duplicate and get the Nth element in the unique list
       ¹s              # push input and move the Nth element to top of stack
         UX            # save it in X
           Q           # compare each element in the list against the Nth unique element
            O          # sum
             FXs}      # that many times, push X and swap it down 1 level on stack
                 }     # end outer loop
                  \    # remove the left over list of unique items
                   )   # wrap stack in a list

```

Try it online!

**Program 6**

```
©€Ýé€¤þ((®€Ýé€¤(þ(Rì

©                        # store a copy of input in register
 €Ý                      # map range[0 ... n] over list
   é                     # sort by length
    €¤                   # map get_last_element over list
      þ((                # keep only non-negative numbers
                         # now we have all positive numbers sorted
         ®€Ýé€¤(þ(       # do the same thing again on input
                         # except now we only keep negative numbers
                  R      # reverse sorting for negative numbers
                   ì     # prepend the sorted negative numbers to the positive ones

```

Try it online!

# Answer
> 11 votes
# Brachylog, score =  ~~4~~  5

### Program 1 - Shuffle sort

```
ṣ.↔:1≥₎∧|↰
```

We shuffle and check that the reverse of the list is non-increasing. If not we retry recursively.

### Program 2 - Permutation sort

```
p≤₁
```

Output the first permutation which is non-decreasing.

### Program 3 - Built-in

Order.

### Program 4 - Built-in

```
≜ᵒ
```

Order by labeling. Since the integers in the list are already fixed, this does the same as `o`.

### Program 5 - Min printing

```
g~kKt~lg~kK{⌋M&~cṪ↺Th[M]hẉTb↺c}ⁱ⁾
```

Here's an explanation for this monstrosity of Nature:

```
g~kK                                K = [Input list, a variable]
    t~lg~kK                         That variable is the length of the Input list
           {                  }ⁱ⁾   Iterate length-of-the-Input times on the Input:
            ⌋M                        M is the min of the input
              &~cṪ                    Ṫ is a triplet of lists which concatenate to the input
                 Ṫ↺Th[M]              T is Ṫ cyclically permuted once ccw; [M] is
                                        the first element of T
                        hẉ            Write M followed by a new line
                          Tb↺c        Remove the first element of T (i.e. [M]), cyclically
                                        pemute T once ccw and concatenate; this is
                                        the input for the next iteration

```

# Answer
> 7 votes
# JavaScript, score ~~1~~ 2

*Doubled the score thanks to @ETHproductions who reminded me of string escapes*

### Snippet 1 (21 bytes, characters `\ ,-.=>289`Facehilnorstux`)

```
Function`return this.sort\x28\x28t,h\x29=>t-h\x29`.call

```

### Snippet 2 (9117 bytes, characters `(+)[!]`)

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

```

You can test both versions in your browser's console. The first version is just a function, the second version is a snippet that needs the parentheses and argument added.

## Examples

```
< {function snippet here}([1, -44, 65, -105, 12])
> [-105, -44, 1, 12, 65]

```

## How?

The first snippet calls the sort method on the array you pass it. By default, the sort method sorts lexicographical, which is bad for integers (especially multi-digit negative numbers). As such, we have to pass it a callback in the form of an arrow function that takes two elements and subtracts the latter from the former. Depending on the resulting value, the two elements are rearranged: if it is smaller than 0, `a` will appear before `b`, if it is larger than 0, `a` will appear after `b`, and if it is 0, both elements will end up next to each other.

The second snippet is nothing more than an encoded version of the first snippet and it takes advantage of the fact that in JavaScript, `object.function()` equals `object["function"]()`. It also uses empty arrays, `!` operators and number casting to generate all kinds of strings, in which the needed characters for the function name can be found. Then the brackets are used once more to get the character at a certain index in the string, and all those characters are concatenated, resulting in the following JavaScript code:

```
[]["fill"]["constructor"]("return this.sort((a,b)=>a-b)")["call"]

```

`[]["fill"]` equals `[].fill`, whose `["constructor"]` is the `Function` object. We then call that with a string (which is to be evaluated when the function is called), which is the first function, but notice that the argument has been replaced by `this`. To set the value of `this` to the argument, we need to call a function on this function, namely `["call"]`. In conventional JavaScript, you would write this as:

```
function _() {
    return this.sort((a,b)=>a-b);
}
_.call(argument);

```

# Answer
> 7 votes
# , score ~~3~~, 4

This was a really fun challenge! Thankfully, vim has a builtin "sort" function, otherwise this would basically be impossible. Unfortunately, it since V/vim are string based it needs an argument to sort by numeric values. So I'm calling

* Sort by numerical value `n`,
* Sort by hexadecimal value `x`, and
* Sort by floating point value `f`

Little side-note: When I write something like `<esc>` or `<C-r>`, this is a actually a single-byte. It represents unprintable characters, and since V unfortunately relies heavily on unprintable characters, this method makes everything easier. The TIO links have the `-v` flag, which makes the V interpreter read these as if they were the characters they represent.

### Program 1, 2 bytes

```
ún

```

Try it online!

This calls the V specific *sort* function.

### Program 2, 10 bytes

```
Qsor x
vi

```

This just calls 'sort' directly. The only interesting thing about this is that we do it from `ex` mode, which is a weird mode that emulates the text editor 'ex', V's great-great-grandfather. `vi` is a shortcut for `visual`, the command used to leave ex mode. This requires a trailing newline.

Try it online!

### Program 3, 14 bytes

```
OSOR X<esc>V~DJ:<C-r>"

```

Try it online!

Alright, here is where the explanations start to get a *little* weird. If we can build up the text `sor x`, we can delete it and insert it into the current command with `<C-r><register-name>`. So we'll enter it uppercase.

```
O                       " Open a newline above the current line, and enter insert mode
 SOR X                  " From insert mode, enter 'SOR X'
      <esc>             " Leave insert mode
           V            " Select this whole line
            ~           " And toggle the case of every selected character ('u' would also work here)
             D          " Delete this line (into register '"')
              J         " Get rid of a newline
               :        " Enter command-line mode
                <C-r>"  " Insert register '"'
                        " Implicitly hit enter, running the 'sor x' command
                        " Implicitly print the buffer

```

### Program 4, 19 bytes

```
YPC<C-v>58fbe a<C-c>g?_dd@1

```

Try it online!

And here is where the explanations start to get *very* weird. Similar to last time, we'll build the command up in normal mode so that we can use different keys.

```
YP                          " Create a copy of this line up one line. This is mostly so that we have a line to work with without messing with the numbers.
  C                         " Delete this line and enter insert mode
   <C-v>58                  " Insert ASCII '58' (which is ':')
          fbe a             " Insert 'fbe a'
               <C-c>        " Pretty much equivalent to <esc>
                    g?_     " ROT13 this line. Now the line is ':sor n'
                       dd   " Delete this whole line
                         @1 " And run it as if typed

```

# Answer
> 6 votes
# CJam, score 4

### Program 1: Built-in

```
$

```

### Program 2: Eval'ed Built-in

```
36c~

```

36 is the ASCII value of `$`.

### Program 3: Permutation Sort

```
e!0=

e!     e# Find unique permutations of the input
  0=   e# Take the first one, which happens to be in sorted order

```

### Program 4: Min Values

```
[{__)\;\{_@_@<{\}&;}*^{1m<}{)\}?}h;]

```

Explanation of this unearthly monstrosity:

```
[             e# Begin working in an array
{             e# Do this block while the TOS is truthy (doesn't pop)
 __           e#  Duplicate TOS twice (the array)
 )\;          e#  Take the last element of the array
 \            e#  Swap top two elements, bringing the other array copy to the top
 {            e#  Reduce the array using this block
  _@_@<{\}&;  e#   The minimum of two values (e was already used, so can't use e<)
 }*           e#  (result is the minimum value from the array)
 ^            e#  Bitwise XOR of last element with minimum element;
              e#   if the numbers are the same, result is 0, otherwise non-zero
 {            e#  If non-zero (i.e. last element wasn't the minimum element)
  1m<         e#   Rotate the array 1 to the left
 }{           e#  Else
  )\          e#   Remove the last element and bring the array back to TOS
 }?           e#  (end if)
}h            e# (end do-while)
;             e# Remove the empty array left behind
]             e# End the array

```

# Answer
> 5 votes
# Japt, score = 4

**Program 1**

```
n

```

Try it online!

**Program 2**

```
ñ

```

Try it online!

**Program 3**

```
s)$.sort((a,b)=>a-b

```

Try it online!

**Program 4**

```
Ov85d +110d

```

Try it online!

# Answer
> 4 votes
# Octave, 2 points

It's hard to compete with esolangs, but here goes:

I'm impressed if someone beats this. `unique` can be used to sort values, but it will strip out the duplicates. In order to insert the duplicates you would need parentheses, and they are heavily used in the bubble-sort. You'd also need `@`, which is used too.

### Number 1:

This one is quite simple: Create an anonymous function, assigned to the variable `ans`.

```
@sort

```

Call it this way: `ans([-5, 3, 0, -2, 100])`. It doesn't work on tio, but it works on octave-online.

---

### Number 2:

This is simply an implementation of bubble sort, without using the characters `@sort`. We can't make this a function, because of `o`, and we can't use `input` because of the `t`. We're therefore stuck with `eval`.

```
eval(['a=inpu',116,'("");']);i=1;k=0;
while~k,k=1;i=1;while i<numel(a),if a(i)>a(i+1),a([i+1,i]) = a([i,i+1]);k=0;
end,i++;end,end,a

```

`eval(['a=inpu',116,'("");']);` evaluates to: `a=input("");`, that we can use to enter our input vector. The rest is bubble-sorting without using `for` or `mod`. Note that this must be saved in a script and called from the GUI/CLI. You can't copy-paste it, because of `input("")` (it will use the rest of the code as input, thus fail miserably).

# Answer
> 4 votes
## Haskell (lambdabot), 3 functions

```
sort

vv v|vvv:vvvv<-v=vv vvvv|v==v=v
vvvv==:vvv|vvvv==vv vvvv=vvv:vvvv|v:vv<-vvvv,vvv<v=vvv:v:vv|v:vv<-vvvv=v:vv==:vvv
vv=:vvvv|v:vvv<-vvvv=vv==:v=:vvv
vv=:v=vv
v vvv=vv vvv=:vvv

fix(ap(min).ap((++).flip(map)[1].(.(0*)).(+).minimum).(.ap(\\)(flip(map)[1].(.(0*)).(+).minimum)))

```

I'm using the lambdabot environment to avoid lots of `import` statements. Even `sort` needs `import Data.List`. lambdabot imports a bunch of modules by default. Besides the missing `imports`, it's standard Haskell code according to our rules.

Try it online!.

### Function 1

```
sort

```

The library function from `Data.List`. Nothing much to say here.

### Function 2

```
vv v|vvv:vvvv<-v=vv vvvv|v==v=v
vvvv==:vvv|vvvv==vv vvvv=vvv:vvvv|v:vv<-vvvv,vvv<v=vvv:v:vv|v:vv<-vvvv=v:vv==:vvv
vv=:vvvv|v:vvv<-vvvv=vv==:v=:vvv
vv=:v=vv
v vvv=vv vvv=:vvv

```

Function `v` implements an insert-sort.

I use pattern guards to avoid `()` for parameters. Compare `vv v|vvv:vvvv<-v=...` to `vv(vvv:vvvv)=...`.

The first line, function `vv` is a helper function to create the empty list. With it I don't have to use `[]` to write literal empty lists. More readable:

```
mkEmpty list | hd:tl <- list = mkEmpty tl | otherwise = list

```

`(==:)` is insert, which inserts an element into a sorted list, so that the resulting list is still sorted. More readable:

```
list `insert` el
  | list == []           = el:list
  | hd:tl <- list, el<hd = el:hd:tl
  | hd:tl <- list        = hd : tl `insert` el

```

`(=:)` is reduce. More readable:

```
acc `reduce` list
  | hd:tl <- list = (acc `insert` hd) `reduce` tl
acc `reduce` list = acc

```

And finally `v` which reduces the input list staring with `[]`:

```
sort list = [] `reduce` list

```

### Function 3

```
fix(ap(min).ap((++).flip(map)[1].(.(0*)).(+).minimum).(.ap(\\)(flip(map)[1].(.(0*)).(+).minimum)))

```

`sort` from Function 1 makes most of the list-walking functions (`fold`, `scan`, `until`) unavailable. Recursion needs `=` which is used in Function 2. The only option left is using the fixpoint combinator `fix`. I've started with

```
fix (\f x -> min x ([minimum x]++f(x\\[minimum x])))

```

which is a selection-sort. Turning it to point-free (I cannot use lambdas `\f x ->...`, because of the `-` which is used by the pattern gurads in Function 2) gives:

```
fix (ap min . ap ((++) . return . minimum) . (. ap (\\) (return . minimum)))

```

Making singleton lists out of a value with `return` is forbidden (same for `pure`), so I have to build my own function: `\x -> map (\y -> x+0*y) [1]` or point-free `flip map[1].(.(0*)).(+)`. Replacing `return` yields

```
fix(ap(min).ap((++).flip(map)[1].(.(0*)).(+).minimum).(.ap(\\)(flip(map)[1].(.(0*)).(+).minimum)))

```

# Answer
> 2 votes
# MATL, 3 programs

### Program 1

```
S

```

This just uses the builtin function, with implicit input and display.

Try it at MATL online.

### Program 2

```
`GGnZrd0<a}3M

```

This keeps generating random permutations of the inputs until all consecutive differences of the result are non-negative (this is bogosort, as noted by @c.z.). Running time is non-deterministic and its average increases very fast with input size (namely, (*n!*) for a size-*n* array with all entries different).

Try it at MATL Online.

### Program 3

```
t:"tt_X>_=&)]&h

```

This is a loop that computes the minimum of the array, removes all elements equal to that value, and proceds with the rest. This is done as many times as the input size. If not all entries in the input are different, some of the iterations will be useless (but harmless), because the array will have already been emptied.

Try it at MATL online.

# Answer
> 1 votes
# Pip, 4 programs

### Program 1 \- builtin

Snippet; assumes list in `x`.

```
SNx

```

(`SN` for Sort Numeric)

### Program 2 \- filter permutations

Snippet; assumes list in `y`. Very slow for inputs longer than about 7 items.

```
Y$<=_FIPMyPOy

       PMy     List of permutations of y
     FI        Filter on this lambda function:
 $<=_           Fold on less-than-or-equal
                (gives 1 if the permutation is sorted ascending, 0 otherwise)
Y              Yank that result back into y
               Filter returned a list of (one or more) permutations, so we need to
          POy  Pop the first one

```

### Program 3 \- eval

Snippet; assumes list in `z`.

```
V J C[83 78 122]

    C[83 78 122]  Apply chr to each number; yields ["S" "N" "z"]
  J               Join that list into a string
V                 Eval

```

### Program 4 \- MergeSort

Anonymous function; call with list as argument (like `({...} [1 2])` or `f:{...} (f [1 2])`.

```
{b:#a>o?(fa@(,#a/2))lc:#a>o?(fa@(#a/2,()))aa:lWb{Wb@0>c@0|b@0Qc@0{aAE:c@0c@>:o}t:bb:cc:t}aALc}

```

Ungolfed:

```
{
 ; If more than one element in a, b gets result of recursion with first half
 ; else b gets l (empty list)
 b: #a>o ? (f a@(,#a/2)) l
 ; If more than one element in a, c gets result of recursion with second half
 ; else c gets a
 c: #a>o ? (f a@(#a/2,())) a
 ; Now we merge b and c
 ; We'll put the results in a, which must be initialized to l (empty list)
 a:l
 ; Loop while b is nonempty
 W b {
  ; Loop while 0th element of c exists and is less than or equal to 0th element
  ; of b (note: Q is string equality)
  W b@0>c@0 | b@0Qc@0 {
   ; Append 0th element of c to a
   a AE: c@0
   ; Slice c from 1st element on and assign that back to c (removing 0th)
   c @>: o
  }
  ; Swap b and c
  t:b
  b:c
  c:t
 }
 ; When b is empty, we only need append the rest of c to a and return
 aALc
}

```

# Answer
> 1 votes
# PowerShell, 2

```
|sort

```

Try it online!

This is a snippet that runs in (e.g.) PowerShell's equivalent of a REPL. The TIO link shows usage. The `sort` is an alias for the `Sort-Object` cmdlet.

---

```
PARAM($A)[ARRAY]::SORT($A);$A

```

Try it online!

PowerShell commands are case-insensitive, so we can use `sort` for one and `SORT` for the other. This takes an input array, sorts it in-place, and then outputs it.

# Answer
> 1 votes
# Ruby, 2 programs

First - the straightforward:

```
->t{t.sort}

```

Second - the tricky part:

```
def w(g)
    eval ""<<103<<46<<115<<111<<114<<116
end

```

# Answer
> 0 votes
# J

**Program one: 3 bytes**

```
/:~

```

as in `/:~ 3,1,2,1` outputs `1 1 2 3`

Try it online!

NOTE in J, negative numbers are preceded by _ not - so you can try 4,\_10,56,\_333 etc.

**Program two: 5 bytes**

```
|.\:~

```

# Answer
> 0 votes
# PHP 7, 2 programs

Both programs can be golfed more.

### Program 1, 254 bytes, characters `! "$&+.01:;=>?[]adeginoprtv`

```
$a=$argv;0 .$a[1+1]?$i=$n=$d=0:print$a[1]and die;g:$r=0 .$a[++$i+1];$i=!$r?1:$i;$n=!$r?$n+1:$n;$v=$i+1;$d=$v>$d?$v:$d;$n>$d?print$a[$d]and die:0;$e=$d>$n&&$a[$i]>$a[$v];$t=$a[$i];$a[$i]=$e?$a[$v]:$a[$i];$a[$v]=$e?$t:$a[$v];$n==$d?print"$a[$i] ":0;goto g;

```

Bubble sort. Uses `goto` to create a loop as built-in loops require `()`.

### Program 2, 155 bytes, characters `#%'(),-67ACEFINORTUYZ^_{|}~`

```
IF(CREATE_FUNCTION('','NEFTIEZIENAECCERCTZIENA~N~UEEFECTZIENAUERTEF~CFACTY~YRZIENAUE'^')))6()~(7)7~6-677|~(7)7%~#|~6)77|~(7)7|~77-)^))(-|~^~~~(7)7|~')()){}

```

`IF(...){}` avoids usage of `;`. The main code is encoded with XOR, because `$` has been already used in the previous program. The code:

```
global$argv;unset($argv[0]);sort($argv);echo join(' ',$argv);

```

---
Tags: code-golf, code-challenge, restricted-source, sorting
---


# Question
Title: Shortest example of code that is compiled and increasing the optimization level makes it take longer
Just curious if someone can provide a short example of code that causes a compiler's optimizer to behave incorrectly:

* without optimization (or at lower optimization), code takes X seconds to run
* with optimization (or at higher optimization), code takes Y seconds to run where Y \> X

In other words, the optimizer's cost model causes it to make a poor decision with a specific case, even though (presumably) it makes good decisions in general.

This is meant for C (with gcc the comparisons should be between `-O0`, `-O1`, `-O2`, `-O3` in increasing order of optimization), but any compiled language should work.

# Answer
# C (gcc 6.2.0-5ubuntu12 x86\_64), 58 bytes

```
typedef struct{long a,b}s;s f(long*c){return(s){*c,c[1]};}

```

Compiled with -O1, we get the following assembly code (minus boilerplate):

```
f:
    movq    8(%rdi), %rdx
    movq    (%rdi), %rax
    ret

```

With -O3, it looks like this:

```
f:
    movdqu  (%rdi), %xmm0
    movaps  %xmm0, -24(%rsp)
    movq    -24(%rsp), %rax
    movq    -16(%rsp), %rdx
    ret

```

This is obviously worse (the first version copies from memory to registers directly, the second version copies from memory into the wrong register, back into scratch space in memory, and then from there into the correct registers, which is just doing more work for no gain).

This is a pretty longstanding example of a silly gcc miscompilation. In older versions of gcc, the -O3 code was even worse (containing a full function setup/teardown sequence, stack protection checks, and the like); it seems to have improved somewhat in the more recent versions.

Incidentally, clang produces code almost identical to gcc's -O1 at any positive optimization level (the only difference is that sometimes the two assignments are done in the other order).
> 9 votes

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


title: The Tenacious Thai Calendar

text:
# Question
Title: The Tenacious Thai Calendar
In the Thai calendar the year 2017 corresponds to 2560. The Thai calendar is always 543 years ahead of the Gregorian calendar.

Observant coders will note that 2560 is equal to \\$2^9 \times 5\\$, in other words it has 10 prime factors. This will not happen again for another 896 years! We call a year **tenacious** if it has exactly ten prime factors.

Write a program which outputs a truthy value if the current year using the Thai calendar, based on the system clock, is tenacious, and a falsey value otherwise.

Test cases:

* If the program is run during 2017, `true`
* If the program is run during any of the years 2018 to 2912, `false`
* If the program is run during 2913, `true` (\\$2913+543 = 2^7 \times 3^3\\$)

# Answer
> 6 votes
# Bash \+ coreutils, 35 bytes

```
factor $[`date +%Y`+543]|awk NF==11

```

Output is either a non-empty string (truthy) or an empty string (falsy).

Try it online!

### Alternate version: 37 bytes.

```
date -d 543year +%Y|factor|awk NF==11

```

Not as golfy, but I like this one.

Try it online!

### How it works

The arithmetic expansion

```
$[`date +%Y`+543]
```

executes `date +%Y` to get the current (full) year and adds **543** to the year.

Factor takes the sum as an argument and prints it prime factorization: first the number to be factored, then a list of individual prime factors.

Finally, awk filters the input, printing only lines with exactly 11 fields (the number plus 10 prime factors).

# Answer
> 5 votes
# 05AB1E, 10 bytes

```
žg543+ÒgTQ

```

Try it online! or as a Test suite

**Explanation**

```
      Òg     # the number of primefactors with duplicates of
žg           # the current year
  543+       # plus 543
        TQ   # equals 10

```

# Answer
> 4 votes
## CJam, 13 bytes

```
et0=543+mf,A=

```

Try it online!

### Explanation

```
et0=  e# Get current year.
543+  e# Add 543.
mf    e# Get prime factors with multiplicity.
,     e# Get length.
A=    e# Equals 10?

```

# Answer
> 4 votes
# Mathematica, ~~37~~ 31 bytes

*5 bytes saved due to lanlock4.*

```
PrimeOmega[#&@@Date[]+543]==10&

```

Anonymous function. Takes no input and returns `True` or `False` as output.

# Answer
> 3 votes
# Pyth, 11 bytes

```
qlP+543.d3T

```

Online interpreter available here.

## Explanation

```
       .d3   get current year
   +543      add 543
  P          get prime factors of result
 l           count number of prime factors
q         T  check if equal to 10 (result is implicitly printed)

```

# Answer
> 2 votes
# Japt, 18 14 13 bytes

```
543+Ki¹k l ¥A

```

Saved 4 bytes thanks to ETHproductions. Saved 1 byte thanks to obarakon.

Try it online!

# Answer
> 2 votes
# Python 2, ~~92~~ 89 bytes

-3 bytes thanks to Jonathan Allan

```
import time
y=time.gmtime()[0]+543
c=i=1
exec"i+=1\nwhile 1>y%i:y/=i;c-=1\n"*y
print-9==c

```

Try it online!
Iterate up to the year, extracting (and couting) the prime factors.
The exec line is equivalent to :

```
for i in range(2,y):
 while not(y%i):
  y=y/i
  c=c-1

```

# Answer
> 1 votes
# Octave, 31 bytes

```
nnz(factor(clock()(1)+543))==10

```

Try it online!

Two tricks used here:

* `clock()(1)` to index directly into the output of `clock` (`clock(1)` doesn't work)
* `nnz` instead of `numel`, as all entries are guaranteed to be nonzero.

---

### Alternate version, same byte count

```
nnz(factor(max(clock)+543))==10

```

This version can only be used for years exceeding `30`, but ~~obviously~~ disregarding time travel this includes all years in which the program can be executed. It works in Matlab as well.

# Answer
> 1 votes
# PHP, 111 68 66

```
$a=date(Y)+543;for($i=2;$i<$a;)$b+=$a%$i?!++$i:!!$a/=$i;echo$b==9;

```

directly counts the number of prime factors.

```
$a=date(Y)+543;             // current year
for($i=2;$i<$a;)            // while $i lower than the year
$b+=$a%$i?!++$i:!!$a/=$i;   // if $i divides $a: $a/=$i and ++$b | if not: ++$i
echo$b==9;                  // output if it has 10 prime factors

```

---

## Old idea: 111 90

```
for($i=1;++$i<1e3;)for($j=1;++$j<1e3;)${$i*$j}=($$i?:1)+($$j?:1);echo${date('Y')+543}==10;

```

This doesn't use a prime factortoring builtin but basically a *counting prime sieve* to get the number of prime factors of a number \< 10000. This maps to the 4 digit year that PHP provides using `date('Y')`:

```
for($i=1;++$i<1e3;)          // for each number smaller sqrt(1e4)
for($j=1;++$j<1e3;)          // do sqrt(1e4) times
${$i*$j}=($$i?:1)+($$j?:1);  // n_factors[i*j] = n_factors[i] + n_factors[j]
echo${date('Y')+543}==10;          // output 1 if the current year has 10 prime factors or nothing if it doesn't

```

# Answer
> 0 votes
# MATL, 14 bytes

```
1&Z'543+Yfn10=

```

Try it online!

```
1&Z'   % Current year
543+   % Add 543
Yf     % Prime factor decomposition
n      % Number of elements
10=    % Equal to 10? Implicitly display

```

# Answer
> 0 votes
## Batch, 123 bytes

```
@set/ay=%date:~-4%+543,n=d=2
:l
@set/ar=y%%d,d+=1
@if %r%==0 set/ay/=d-=1,n+=1
@if %y% gtr 1 goto l
@if %n%==12 echo 1

```

You can fake out the script by manually overriding the `date` variable before running it.

# Answer
> 0 votes
## JavaScript (ES6), ~~79~~ 75 bytes

```
f=(y=+Date().slice(11,15)+543,d=2,n=10)=>y>1?y%d?f(y,d+1,n):f(y/d,d,n-1):!n

```

Port of my Batch answer. Pass in the **Thai** calendar year if you want to perform a specific test. Edit: Saved 4 bytes thanks to @dandavis.

# Answer
> 0 votes
# , 18 bytes

Program body:

```
10=#q:543+{.6!:0''
```

Try it online!

`10=` is ten equal to

`#` the tally of

`q:` the prime factors of

`543+` this number added to

`{.` the head (first item, i.e. the year) of

`6!:0''` the date (as Y M D h m s)

---
Tags: code-golf, number-theory, primes, date
---


title: TiB, not TB, Seriously?

text:
# Question
Title: TiB, not TB, Seriously?
If you're like me (and/or use Windows), You should have found this issue quite disturbing.

You plug in a hard drive (2TB for my occasion), and realize it doesn't show as 2TB, but a bit smaller size which is clearly not 2TB.

Over some research, I found it was because of Microsoft's mistake. Mistyping Binary prefix as Decimal prefixes. (i.e. They typed 1TiB as 1TB)

So, I would like to see a Binary prefix to Decimal prefix program. Since this is a big problem (and some computers are literally toasters), You have to make your program as short as possible.

conversion chart I found

---

# I/O

You will be given the size (positive real number, will not exceed 2ˆ16 when converted), and the unit (4 of them, KiB, MiB, GiB and TiB, each corresponds to 1024ˆ1, 1024ˆ2, 1024ˆ3 and 1024ˆ4 bytes)

You have to output the (decimal representation of) the size (rounded half-up to integer value), and the corresponding unit.

---

# Examples

```
678 MiB => 711 MB
1.8 TiB => 2 TB

```

**Tip: Google has a unit converter**

# Answer
# Python 3.6, ~~78~~ 77 bytes

```
a,b=input().split()
print(f'{eval(a)*1.024**" KMGT".find(b[0]):.0f} {b[0]}B')

```
> 1 votes

# Answer
# Pyth, ~~27~~ ~~25~~ 35 Bytes

```
=H@z_3s[.E*v<4z^1.024x" KMGT"HdH\B

```

Adding the unit to the output costed me quite some bytes.

Try it!
> 1 votes

# Answer
# APL (Dyalog), 26 bytes

Prompts for unit and size, and outputs unit and size.

```
⌊.5+⎕×1.024*'KMGT'⍳⊃⎕←⍞∩⎕A

```

Try it online!

`∩⎕A` intersection with uppercase **A**lphabet of

character input (unit) from STDIN

`⎕←` output that to STDOUT

get the first character of the outputted value

`'KMGT'⍳` find the 1-based index of that in this string

`1.024*` raise this number that that power

`⎕×` multiply numeric input from STDIN with that

`.5+` add a half to that

round that down
> 1 votes

# Answer
# PHP, 63 bytes

```
<?=1.024**strpos(_KMGT,($m=$argv[2][0]))*$argv[1]+.5|0," $m",B;

```

takes input from command line arguments;
run with `echo '<code>' | php -n` or save to file and run with `php -n <filename>`.
> 1 votes

# Answer
# Mathematica, ~~44~~ 43 bytes

It has a built-in function for everything

```
Round@UnitConvert[#,StringPart[#,-3]<>"B"]&

```

(Input should be a string `"678 MiB"`.)
> 0 votes

# Answer
## JavaScript (ES6), 71 bytes

```
f=
(s,[n,[u]]=s.split` `)=>(n*1.024**` KMGT`.search(u)).toFixed()+` ${u}B`
```

```
<input oninput=o.textContent=/\s[KMGT]/.test(this.value)?f(this.value):``><span id=o>
```
> 0 votes

---
Tags: code-golf, conversion
---


title: Bowl a rectangular quine

text:
# Question
Title: Bowl a rectangular quine
# Code-Bowling Quine Challenge

You must bowl a quine following the rules of code bowling and quines but the source code must be in the shape of a **rectangle** (details specified below)

---

# Quine

Quines returned must be returned via the ways defined in the standard I/O rules.

---

# Rules

### Code-Bowling Rules

1. **Character : Byte Ratio** In Code-Bowling a character-count is preferred over a byte-count. The obvious reasoning for this is that multi-byte unicode characters (e.g. ) can be used in place of single-byte unicode characters to fluff up byte count and will make bowling more about who renames the most variables with high-byte unicode characters rather than who most strategically creates meaningful complex code. (See Useful tools section at end for character-counting widget)
2. **Variable/Function/Object Names** All variable names (or object pointers, function names, etc) should be 1 character long. The only acceptable time to use 2-character variables names is after all possible 1-character variables have been used. The only acceptable time to use 3-character variables names is after all possible 2-character variables have been used. Etc.
3. **Non-simplified Arithmetic** All arithmetic should be in simplified form unless there is a justifiable reason for doing otherwise (e.g. circumventing penalties defined in the scoring system of the challenge (In which case you still must use the smallest possible alternative form)). Finding the simplified form of any equation (as well as a list of small alternative forms) is easy to do using Wolfram|Alpha. (See Useful tools section at end)
4. **Un-used Code** All code must be used. Meaning the program must fail to always properly complete the task if any individual character (or varying set(s) of characters) is/are removed. Naturally, a subset of the program should not be able complete the task on its own without the rest of the program.
5. **Line-breaks and White-space** Unless necessary for code function or otherwise specified by the challenge, all line-breaks and white-space should be removed from code before scoring by counting characters.
6. **Comments** Comments are not permitted towards character-count, unless somehow utilized by your program/function.

### Rectangle Rules

Your code must be in the shape of a rectangle, i.e. every line has the same number of characters. Your code must have at least 2 lines, with at least 3 chars on each line.

Also, each line of code must be distinct to a certain threshold. Distinctness is calculated using the Levenshtein distance. The threshold is 85%, meaning the Levenshtein distance between any two lines must be greater than or equal to 0.85\*w, where w is the number of characters used in a line of your rectangle.

And for convenience, here is a Levenshtein distance calculator and a character length calculator.

---

# Scoring

This is a variant. The program with the highest number of characters wins!

# Answer
# Python 3, 89 bytes

```
a='a=%r;b=%r;p=\\';b='print;p(a%(a,b));';p=\
print;p(a%(a,b));c='c=%r;p(b+c%%c)';p(b+c%c)

```

**Try it online**

The Levenshtein distance is 38, which is 86.36% of 44.

**Explanation:**

This is similar to the standard quine `s='s=%r;print s%%s';print s%s`. I had to try a lot of combinations and modifications in order to find my program. Creating the function `p` was used to make the second line shorter. The `\` on the end of the first line is a line-continuation character.

### a

```
a='a=%r;b=%r;p=\\'
```
* A string template that results in the first line

### b

```
b='print;p(a%(a,b));'

```
* String that represents the first part of the 2nd line

### p

```
p=\
print

```
* Shorten stuff, change lengths

### line 1

```
p(a%(a,b))

```
* Print the first line

### c

```
c='c=%r;p(b+c%%c)'

```
* String representing itself plus the part after that prints `b`

### line 2

```
p(b+c%c)

```
* Outputs the second line
> 5 votes

---
Tags: restricted-source, quine, code-bowling
---


title: Queueing With Friends

text:
# Question
Title: Queueing With Friends
You're with your best bud, Jim, at the amusement park and as your favorite ride comes into view, you and Jim exchange glances. Naturally you race to get in line. Unfortunately he wins because you're a golfer and he plays a real sport (sorry friends). In fact, you're so far behind that you and Jim are separated by `x` people. Assuming the line is length `n` and you're at the back and the line zigs and zags every `j` people, at what positions in the line will you and Jim be in the same column allowing you to chat (only one row apart)?

# Input

3 Integers

* `n` \- The length of the line. This number will always be greater than or equal to `j` and will be in the form `y * j` where `y` is a positive integer (the number of rows in the queue).
* `j` \- The number of people in one row of the line (the number of columns in one row). This number will always be greater than 0.
* `x` \- The number of people between you and Jim such that `0 <= x < 2j - 1`. Hint: If this number is odd, then your output should be empty.

# Output

A list of integer positions in the line at which Jim is in the same column as you.
1 These integers can be 0 or 1-indexed as long as you specify in your answer.
2 These integers can assume you start at position 0 or position n-1 as long as you specify in your answer.

# Example

In this example, the input would be `n = 9, j = 3, x = 0`. The output should be `2, 5` because your position is 2 or 5 when you're in the same column as Jim

# Test Cases

```
[9, 3, 0] -> [2, 5]
[12, 3, 0] -> [2, 5, 8]
[9, 3, 1] -> []
[9, 3, 2] -> [1, 4]
[14, 7, 10] -> [1]
[24, 4, 6] -> [0, 4, 8, 12, 16]

```

# Scoring

This is , so the shortest answer (in bytes) wins.

# Answer
> 9 votes
# Python 2, ~~45~~ ~~41~~ ~~40~~ 37 bytes

```
lambda n,j,x:range(j-x/2,x%2or n-x,j)

```

Pretty much the trivial solution. I just quickly scanned for patterns and found a pattern. 1-indexed, 1 is at the back of the queue.

-4 bytes by avoiding ternaries and using an array for the values instead
-1 byte thanks to some inspiration from @DeadPossum, by using `and` instead of ternaries or array selectors
-3 bytes by switching to `or` in the opposite order. Only works because of 1-indexing

Also, crossed out 4 is still 4 on all of the 4s :(

Try it online!

# Answer
> 2 votes
# Pip, ~~22~~ 21 bytes

20 bytes of code, +1 for `-p` flag.

```
c%2?lv-c/2+b*\,a/b-1

```

Takes `n`, `j`, and `x` as command-line arguments. 0-indexed, starting at position 0. Try it online!

### Explanation

This is my original 22-byte version because it's a bit more understandable.

```
                       a, b, c are cmdline args; l is [] (implicit)
c%2?                   Test c mod 2
    l                  If it's 1 (truthy), return empty list; else:
                a/b-1  Number of rows in the queue minus 1
               ,       Range(^)
             b*        Multiply each element by b
     b-1-c/2+          Add (b-1)-c/2 to each element
                       Output in [1;2;3] format (implicit, -p flag)

```

The formula was obtained by observing the pattern for `n=9`, `j=3`:

```
x Output
0 [2;5]
2 [1;4]
4 [0;3]

```

If we take `x/2` (`0`,`1`,`2`), subtract it from `j-1` (`2`,`1`,`0`), and add that to `[0;3]`, we get the correct result in all cases.

# Answer
> 1 votes
# Java 8 lambda, 101 bytes

```
(n,j,x)->{int[]i=new int[n/j-1];int c=0,k=j-x/2;for(;k<n-x;k+=j)i[c++]=k;return x/2==0?i:new int[0];}

```

Almost-direct port of my Python answer. Range doesn't exist in Java though.

# Answer
> 0 votes
# Haskell, 43 bytes

```
(n#j)x|odd$round x=[]|m<-j-x/2=[m,m+j..n-x]

```

Pretty much directly ported from the Python answer from HyperNeutrino

More well-formatted code:

```
f n j x |odd$round x = []
        |otherwise   = let m=j-x/2 in [m,m+j..n-x]

```

EDIT: Forgot to mention it was one-indexed

# Answer
> 0 votes
# C# - 91 bytes

```
int[]r=new int[n/j-1];for(int i=1;i<n/j;i++){r[i-1]=i*j-x/2-1;}return(x%2==0)?r:new int[0];

```

---
Tags: code-golf
---


title: Chess Analysis with Limited Information

text:
# Question
Title: Chess Analysis with Limited Information
In this challenge, **you are given a limited amount of information about a particular game of chess, and you need to predict who won the game**.

You are given two sets of data:

1. Piece counts (What pieces are still alive)
2. Board colors (The color of pieces on the board)

More importantly, **you *don't* know where the pieces are located**. You need to determine who you think will win.

Games are selected from all events listed on PGNMentor from 2010 to now. I've selected 10% of all of the board positions from each game that ends in a win or a loss. Board positions will always be at least 30 moves into the game. The test cases can be found here. (White wins are listed first, followed by black wins)

## Input

The piece count will be a string consisting of a character for each piece: `k`ing, `q`ueen, `r`ook, k`n`ight, `b`ishop, or `p`awn. Lowercase means black, uppercase is white. The board will be a string of 64 characters (8 rows by 8 columns). `B` represents a black piece, `W` represents a white piece, and `.` represents an empty spot. Sample:

```
W..WB......W.BB....W..B..W.WWBBB..W...B....W..BBWWW...BB.W....B.,BBKPPPPPPPQRRbbkpppppppqrr

```

would represent the following board

```
...B.BB.
.BBBBBBB
.B.B....
B..W....
WWWW.W..
....W.W.
...W..WW
W.....W.

```

and where both colors have 2 Bishops, 1 King, 7 Pawns, 1 Queen, 2 Rooks

## Output

You need to return a floating-point number between 0 and 1 (inclusive) to determine how likely it is that white wins. Sample:

```
0.3     (30% chance that white wins)

```

More details:

* Each test case is worth 1 point. Your score will be `1 - (1-Output)^2` if white wins, or `1 - (Output)^2` if black wins.
* Your final score will be the sum across all test cases.
* If I feel that submissions are hardcoding the input, I reserve the right to change the test cases. (If I do change them, they will have the SHA-256 hash `893be4425529f40bb9a0a7632f7a268a087ea00b0eb68293d6c599c6c671cdee`)
* Your program must run test cases independently. No saving information from one test case to the next.
* **If you are using machine learning, I highly recommend training on the first 80% of the data, and testing using the remaining 20%**. (Or whatever percentages you use). I use the games multiple times in the data, but I put the same games together sequentially.
* **UPDATE:** I've added over a million test cases for testing and learning purposes. They are split into black and white parts because of github repo size limits.

Good luck and have fun!

# Answer
## GNU sed \+ bc, ~~4336~~ 5074.5 points, ~~64~~ 75 %

**Update:** the OP gave a new way to calculate the score of the prediction for an individual test case. Using Wolfram Alpha, I plotted both sets of formulas to see the differences.

The current way brings a strong incentive to output actual probabilities, and not just the extremes, 0 and 1, for which the new formulas give the same maximum score as before. This is why the unchanged algorithm below, has now a better prediction rate, in fact a great rate given its simplicity.

However, there's also a drawback associated with the new formulas, as explained in 'Edit 1'.

---

This is a simple estimation based only on the material advantage / disadvantage, ignoring the actual placement of the pieces. I was curious how this will perform. The reason I use sed, and not some language that can do this in one line, is because it is my favorite esoteric language.

```
/:/d                                             # delete the two headers
s:.*,::                                          # delete board positions
s:$:;Q9,R5,B3,N3,P1,K0,q-9,r-5,b-3,n-3,p-1,k-0:  # add relative piece value table
:r                                               # begin replacement loop
s:([a-Z])((.*)\1([^,]+)):\4+\2:                  # table lookup: letter-value repl.
tr                                               # repeat till last piece
s:;.*::                                          # delete value table
s:.*:echo '&0'|bc:e                              # get material difference: bc call
/^0$/c0.5                                        # print potential draw score
/-/c0                                            # print potential black win score
c1                                               # print potential white win score

```

Standard piece values used:

* 9 - Queen
* 5 - Rook
* 3 - Knight
* 3 - Bishop
* 1 - Pawn
* 0 - King

I calculate the material for both sides and subtract black's material from that of white. The output for each test case is based on that difference as follows:

* if difference \> 0, then output = 1 (potential white win)
* if difference = 0, then output = 0.5 (potential draw).

This is my only fractional output, hence the reason of the improvement as explained above.

* if difference \< 0, then output = 0 (potential black win)

The prediction rate for this method was 64 %. Now it is 75 % with the new formulas.

> I initially expected it to be higher, say 70 %, but as a chess player myself I can understand the result, since I've lost so many games when I was +1 / +2, and won that many when I was down in material. It's all about the actual position. (Well, now I got my wish!)

**Edit 1:** the drawback

The trivial solution is to output 0.5 for each test case, because this way you scored half a point regardless who won. For our test cases, this meant a total score of 3392.5 points (50 %).

But with the new formulas, 0.5 (which is an output you'd give if you're undecided who wins) is converted to 0.75 points. Remember that the maximum score you can receive for a test case is 1, for 100% confidence in the winner. As such, the new total score for a constant 0.5 output is 5088.75 points, or 75 %! In my opinion, the incentive is too strong for this case.

That score is better, though marginally, than my material advantage based algorithm. The reason for that is because the algorithm gives a probability of 1 or 0 (no incentive), assumed wins or losses, more times (3831) than it gives 0.5 (incentive), assumed draws (2954). The method is simple in the end, and as such it doesn't have a high percentage of correct answers. The boost from the new formula to constant 0.5, manages to reach that percentage, artificially.

**Edit 2:**

It is a known fact, mentioned in chess books, that it is usually better to have a bishop pair than a knight pair. This is especially true in the middle to end stage of the game, where the test cases are, since it's more likely to have an open position where a bishop's range is increased.

Therefore I did a second test, but this time I replaced the bishops's value from 3 to 3.5. The knight's value remained 3. This is a personal preference, so I didn't make it my default submission. The total score in this case was 4411 points (65 %). Only 1 percentage point increase was observed.

With the new formulas, the total score is 4835 points (71 %). Now the weighted bishop underperforms. But, the effect is explained because the weighted method now gives even more times assumed wins or losses (5089), than assumed draws (1696).
> 8 votes

# Answer
# Java 8 + Weka, 6413 points, 94.5%

This answer uses a machine learning approach. You need to retrieve the Weka library, notably `weka.jar` and `PackageManager.jar`.

Here, I use a multilayer perceptron as classifier; you can replace `mlp` with any `Classifier` class of Weka to compare results.

I have not tinkered much with the parameters of the MLP, and simply eyeballed them (one hidden layer of 50 neurons, 100 epochs, 0.2 learning rate, 0.1 momentum).

I threshold the output value of the MLP, so the output really is either 1 or 0 as defined in the challenge. That way the number of correctly classified instances as printed by Weka is directly our score.

### Feature vector construction

I turn each instance from a string to a vector of 76 elements, where:

* The first 64 elements represent the cells of the board, in the same order as in the string, where `1` is a white piece, `-1` is a black piece and `0` is an empty cell.
* The last 12 elements represent each type of piece (6 per player); the value of those elements is the number of pieces of that type on the board (`0` being "no piece of that type"). One could apply normalization to refit those values between -1 and 1 but this is probably not very helpful here.

### Number of training instances

If I use all test cases given to train my classifier, I have managed to get **6694 (i.e. 98.6588%) correctly classified instances**. This is obviously not surprising because testing a model on the same data you used to train it is way too easy (because in that case it is actually good that the model overfits).

Using a random subset of 80% of the instances as training data, we obtain the **6413 (i.e. 94.5173%) correctly classified instances** figure reported in the header (of course since the subset is random you might get slightly different results). I am confident that the model would work decently well on new data, because testing on the remaining 20% of the instances (that weren't used for training) gives **77.0818%** correct classification, which shows that the models generalizes decently well (assuming the instances we are given here are representative of the new test cases we would be given).

Using half the instances for training, and the other half for testing, we get **86.7502%** on both training and testing data, and **74.4988%** on only the test data.

### Implementation

As I've said, this code requires `weka.jar` and `PackageManager.jar` from Weka.

One can control the percentage of data used in the training set with `TRAIN_PERCENTAGE`.

The parameters of the MLP can be changed just below `TRAIN_PERCENTAGE`. One can try other classifiers of Weka (e.g. `SMO` for SVMs) by simply replacing `mlp` with another classifier.

This program prints to sets of results, the first one being on the entire set (including the data used for training) which is the score as defined in this challenge, and the second one being on only the data that was not used for training.

One inputs the data by passing the path of the file containing it as an argument to the program.

```
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.functions.MultilayerPerceptron;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

public class Test {

    public static void main(String[] arg) {

        final double TRAIN_PERCENTAGE = 0.5;

        final String HIDDEN_LAYERS = "50";
        final int NB_EPOCHS = 100;
        final double LEARNING_RATE = 0.2;
        final double MOMENTUM = 0.1;

        Instances instances = parseInstances(arg[0]);
        instances.randomize(new java.util.Random(0));
        Instances trainingSet = new Instances(instances, 0, (int) Math.floor(instances.size() * TRAIN_PERCENTAGE));
        Instances testingSet = new Instances(instances, (int) Math.ceil(instances.size() * TRAIN_PERCENTAGE), (instances.size() - (int) Math.ceil(instances.size() * TRAIN_PERCENTAGE)));

        Classifier mlp = new MultilayerPerceptron();
        ((MultilayerPerceptron) mlp).setHiddenLayers(HIDDEN_LAYERS);
        ((MultilayerPerceptron) mlp).setTrainingTime(NB_EPOCHS);
        ((MultilayerPerceptron) mlp).setLearningRate(LEARNING_RATE);
        ((MultilayerPerceptron) mlp).setMomentum(MOMENTUM);

        try {
            // Training phase
            mlp.buildClassifier(trainingSet);
            // Test phase
            System.out.println("### CHALLENGE SCORE ###");
            Evaluation test = new Evaluation(trainingSet);
            test.evaluateModel(mlp, instances);
            System.out.println(test.toSummaryString());
            System.out.println();
            System.out.println("### TEST SET SCORE ###");
            Evaluation test2 = new Evaluation(trainingSet);
            test2.evaluateModel(mlp, testingSet);
            System.out.println(test2.toSummaryString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Instances parseInstances(String filePath) {
        ArrayList<Attribute> attrs = new ArrayList<>(); // Instances constructor only accepts ArrayList
        for(int i = 0 ; i < 76 ; i++) {
            attrs.add(new Attribute("a" + String.valueOf(i)));
        }
        attrs.add(new Attribute("winner", new ArrayList<String>(){{this.add("white");this.add("black");}}));
        Instances instances = new Instances("Rel", attrs, 10);
        instances.setClassIndex(76);

        try {
            BufferedReader r = new BufferedReader(new FileReader(filePath));
            String line;
            String winner = "white";
            while((line = r.readLine()) != null) {
                if(line.equals("White:")) {
                    winner = "white";
                } else if(line.equals("Black:")) {
                    winner = "black";
                } else {
                    Instance instance = new DenseInstance(77);
                    instance.setValue(attrs.get(76), winner);
                    String[] values = line.split(",");
                    for(int i = 0 ; i < values[0].length() ; i++) {
                        if(values[0].charAt(i) == 'B') {
                            instance.setValue(attrs.get(i), -1);
                        } else if(values[0].charAt(i) == 'W') {
                            instance.setValue(attrs.get(i), 1);
                        } else {
                            instance.setValue(attrs.get(i), 0);
                        }
                    }
                    // Ugly as hell
                    instance.setValue(attrs.get(64), values[1].length() - values[1].replace("k", "").length());
                    instance.setValue(attrs.get(65), values[1].length() - values[1].replace("q", "").length());
                    instance.setValue(attrs.get(66), values[1].length() - values[1].replace("r", "").length());
                    instance.setValue(attrs.get(67), values[1].length() - values[1].replace("n", "").length());
                    instance.setValue(attrs.get(68), values[1].length() - values[1].replace("b", "").length());
                    instance.setValue(attrs.get(69), values[1].length() - values[1].replace("p", "").length());
                    instance.setValue(attrs.get(70), values[1].length() - values[1].replace("K", "").length());
                    instance.setValue(attrs.get(71), values[1].length() - values[1].replace("Q", "").length());
                    instance.setValue(attrs.get(72), values[1].length() - values[1].replace("R", "").length());
                    instance.setValue(attrs.get(73), values[1].length() - values[1].replace("N", "").length());
                    instance.setValue(attrs.get(74), values[1].length() - values[1].replace("B", "").length());
                    instance.setValue(attrs.get(75), values[1].length() - values[1].replace("P", "").length());

                    instances.add(instance);
                }
            }
        } catch (Exception e) { // who cares
            e.printStackTrace();
        }
        return instances;
    }
}

```
> 8 votes

# Answer
**Python 3 - 84.6%, 5275 points on a validation set**

If we cheat and use all the data, we can achieve **an accuracy of 99.3%, and a score of 6408**

Just a simple large MLP with dropout using Keras

```
import collections
import numpy as np
import random

import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.layers.noise import GaussianDropout
from keras.optimizers import Adam

np.random.seed(0)
random.seed(0)

def load_data():
    with open('test_cases.txt', 'r') as f:
        for line in f:
            yield line.split(',')

def parse_data(rows):
    black_pieces = "kpbkrq"
    white_pieces = black_pieces.upper()
    for i, row in enumerate(rows):
        if len(row) >= 2:
            board = row[0]
            board = np.array([1 if c == 'W' else -1 if c == 'B' else 0 for c in board], dtype=np.float32)
            pieces = row[1]
            counts = collections.Counter(pieces)
            white_counts = np.array([counts[c] for c in white_pieces], dtype=np.float32)
            black_counts = np.array([counts[c] for c in black_pieces], dtype=np.float32)
            yield (outcome, white_counts, black_counts, board)
        else:
            if 'White' in row[0]:
                outcome = 1
            else:
                outcome = 0

data = list(parse_data(load_data()))
random.shuffle(data)
data = list(zip(*data))
y = np.array(data[0])
x = list(zip(*data[1:]))
x = np.array([np.concatenate(xi) for xi in x])

i = len(y) // 10

x_test, x_train = x[:i], x[i:]
y_test, y_train = y[:i], y[i:]

model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(76,)))
model.add(GaussianDropout(0.5))
model.add(Dense(512, activation='relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(512, activation='relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='mean_squared_error', optimizer=Adam())

use_all_data = False

x_valid, y_valid = x_test, y_test

if use_all_data:
    x_train, y_train = x_test, y_test = x, y
    validation_data=None
else:
    validation_data=(x_test, y_test)

batch_size = 128

history = model.fit(x_train, y_train, batch_size=batch_size, epochs=50, verbose=1, validation_data=validation_data)

y_pred = model.predict_on_batch(x_test).flatten()
y_class = np.round(y_pred)
print("accuracy: ", np.sum(y_class == y_test) / len(y_test))

score = np.sum((y_pred - (1 - y_test)) ** 2) * (len(y) / len(y_test))
print("score: ", score)

```
> 4 votes

# Answer
**Python 3 - 94.3% accuracy, 6447 points on a validation set of 20% of the data**

Uses 3 neural networks, a nearest neighbours regressor, a random forest, and gradient boosting. These predictions are combined with a random forest which also has access to the data.

```
import collections
import numpy as np
import numpy.ma as ma
import random

import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, BatchNormalization, Activation, Conv2D, Flatten
from keras.layers.noise import GaussianDropout
from keras.callbacks import EarlyStopping
from keras.optimizers import Adam
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import GradientBoostingRegressor
import tensorflow

tensorflow.set_random_seed(1)
np.random.seed(1)
random.seed(1)

def load_data():
    with open('test_cases.txt', 'r') as f:
        for line in f:
            yield line.split(',')

def parse_data(rows):
    black_pieces = "kqrnbp"
    white_pieces = black_pieces.upper()
    for i, row in enumerate(rows):
        if len(row) >= 2:
            board = row[0]
            board = np.array([1 if c == 'W' else -1 if c == 'B' else 0 for c in board], dtype=np.float32)
            pieces = row[1]
            counts = collections.Counter(pieces)
            white_counts = np.array([counts[c] for c in white_pieces], dtype=np.float32)
            black_counts = np.array([counts[c] for c in black_pieces], dtype=np.float32)
            yield (outcome, white_counts, black_counts, board)
        else:
            if 'White' in row[0]:
                outcome = 1
            else:
                outcome = 0

data = list(parse_data(load_data()))
random.shuffle(data)
data = list(zip(*data))
y = np.array(data[0])
x = list(zip(*data[1:]))
conv_x = []
for white_counts, black_counts, board in x:
    board = board.reshape((1, 8, 8))
    white_board = board > 0
    black_board = board < 0
    counts = [white_counts, black_counts]
    for i, c in enumerate(counts):
        n = c.shape[0]
        counts[i] = np.tile(c, 64).reshape(n, 8, 8)
    features = np.concatenate([white_board, black_board] + counts, axis=0)
    conv_x.append(features)
conv_x = np.array(conv_x)
x = np.array([np.concatenate(xi) for xi in x])
s = x.std(axis=0)
u = x.mean(axis=0)
nz = s != 0
x = x[:,nz]
u = u[nz]
s = s[nz]
x = (x - u) / s

i = 2 * len(y) // 10

x_test, x_train = x[:i], x[i:]
conv_x_test, conv_x_train = conv_x[:i], conv_x[i:]
y_test, y_train = y[:i], y[i:]

model = Sequential()

def conv(n, w=3, shape=None):
    if shape is None:
        model.add(Conv2D(n, w, padding="same"))
    else:
        model.add(Conv2D(n, w, padding="same", input_shape=shape))
    model.add(BatchNormalization())
    model.add(Activation('relu'))

conv(128, shape=conv_x[0].shape)
conv(128)
conv(128)
conv(128)
conv(128)
conv(128)
conv(128)
conv(128)
conv(128)
conv(128)
conv(2, w=1)
model.add(Flatten())
model.add(GaussianDropout(0.5))
model.add(Dense(256))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(1))
model.add(BatchNormalization())
model.add(Activation('sigmoid'))

model.compile(loss='mse', optimizer=Adam())

model5 = model

model = Sequential()
model.add(Dense(50, input_shape=(x.shape[1],)))
model.add(Activation('sigmoid'))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='mse', optimizer=Adam())

model0 = model

model = Sequential()
model.add(Dense(1024, input_shape=(x.shape[1],)))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(1024))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(1024))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(GaussianDropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='mse', optimizer=Adam())

model4 = model

use_all_data = False

x_valid, y_valid = x_test, y_test

if use_all_data:
    x_train, y_train = x_test, y_test = x, y
    validation_data=None
else:
    validation_data=(x_test, y_test)

def subsample(x, y, p=0.9, keep_rest=False):
    m = np.random.binomial(1, p, size=len(y)).astype(np.bool)
    r = (x[m,:], y[m])
    if not keep_rest:
        return r
    m = ~m
    return r + (x[m,:], y[m])

epochs=100

x0, y0, x_valid, y_valid = subsample(conv_x_train, y_train, keep_rest=True)
model5.fit(x0, y0, epochs=epochs, verbose=1, validation_data=(x_valid, y_valid), callbacks=[EarlyStopping(patience=1)])

x0, y0, x_valid, y_valid = subsample(x_train, y_train, keep_rest=True)
model0.fit(x0, y0, epochs=epochs, verbose=1, validation_data=(x_valid, y_valid), callbacks=[EarlyStopping(patience=1)])

x0, y0, x_valid, y_valid = subsample(x_train, y_train, keep_rest=True)
model4.fit(x0, y0, epochs=epochs, verbose=1, validation_data=(x_valid, y_valid), callbacks=[EarlyStopping(patience=1)])

model1 = RandomForestRegressor(n_estimators=400, n_jobs=-1, verbose=1)
model1.fit(*subsample(x_train, y_train))

model2 = GradientBoostingRegressor(learning_rate=0.2, n_estimators=5000, verbose=1)
model2.fit(*subsample(x_train, y_train))

model3 = KNeighborsRegressor(n_neighbors=2, weights='distance', p=1)
model3.fit(*subsample(x_train, y_train))

models = (model0, model1, model2, model3, model4, model5)

model_names = [
    "shallow neural net",
    "random forest",
    "gradient boosting",
    "k-nearest neighbors",
    "deep neural net",
    "conv-net",
    "ensemble"
]

def combine(predictions):
    clip = lambda x: np.clip(x, 0, 1)
    return clip(np.array([y.flatten() for y in predictions]).T)

def augment(x, conv_x):
    p = combine([m.predict(x) for m in models[:-1]] + [models[-1].predict(conv_x)])
    return np.concatenate((x, p), axis=1)

model = RandomForestRegressor(n_estimators=200, n_jobs=-1, verbose=1)
model.fit(augment(x_train, conv_x_train), y_train)

def accuracy(prediction):
    class_prediction = np.where(prediction > 0.5, 1, 0)
    return np.sum(class_prediction == y_test) / len(y_test)

predictions = [m.predict(x_test).flatten() for m in models[:-1]] + [models[-1].predict(conv_x_test).flatten()]+ [model.predict(augment(x_test, conv_x_test))]

for s, p in zip(model_names, predictions):
    print(s + " accuracy: ", accuracy(p))

def evaluate(prediction):
    return np.sum(1 - (prediction - y_test) ** 2) * (len(y) / len(y_test))

for s, p in zip(model_names, predictions):
    print(s + " score: ", evaluate(p))

```
> 2 votes

# Answer
# Python 3 - 4353.25/6785 points - 64%

So I worked on this mostly yesterday. My first post golfing, and I've only been using python a week or so now, so forgive me if not everything is optimized.

```
def GetWhiteWinPercent(a):
finalWhiteWinPercent=0
i=a.index(',')

#position
board=a[:i]
blackBoardScore=0
whiteBoardScore=0
for r in range(i):
    if board[r] == 'B': blackBoardScore += abs(7 - (r % 8))
    if board[r] == 'W': whiteBoardScore += r % 8
if   whiteBoardScore > blackBoardScore: finalWhiteWinPercent += .5
elif whiteBoardScore < blackBoardScore: finalWhiteWinPercent += .0
else: finalWhiteWinPercent+=.25

#pieces
pieces=a[i:]
s = {'q':-9,'r':-5,'n':-3,'b':-3,'p':-1,'Q':9,'R':5,'N':3,'B':3,'P':1}
pieceScore = sum([s.get(z) for z in pieces if s.get(z) != None])
if   pieceScore < 0: finalWhiteWinPercent += 0
elif pieceScore > 0: finalWhiteWinPercent += .5
else: finalWhiteWinPercent += .25

return finalWhiteWinPercent

```

I ended up along the same path as seshoumara's answer to begin with. But the large number of test cases that had even counts of pieces left me dissatisfied.

So I googled traits that dictate who is winning in chess (I don't play the game myself) and noticed board position, specifically center control, is big. That's where this bit comes in.

```
for r in range(i):
    if board[r] == 'B': blackBoardScore += abs(7 - (r % 8))
    if board[r] == 'W': whiteBoardScore += r % 8
if   whiteBoardScore > blackBoardScore: finalWhiteWinPercent += .5
elif whiteBoardScore < blackBoardScore: finalWhiteWinPercent += .0
else: finalWhiteWinPercent+=.25

```

Both of those halves combined are used to find the score (0.0, 0.25, 0.50, 0.75, 1.0)

Very interesting that this board position extra doesn't seem to increase the chance at all of guessing the winner.

If you drop the test cases into some files, here's the testing.

```
whiteWins=0
blackWins=0
totalWins=0
for line in open('testcases2.txt','r'):
    totalWins += 1
    blackWins += 1 - GetWhiteWinPercent(line)
for line in open('testcases.txt','r'):
    totalWins += 1
    whiteWins += GetWhiteWinPercent(line)

print(str(whiteWins+blackWins) +'/'+str(totalWins))

```

I know this isn't a golf challenge, but any tips or advice in that regard is appreciated!
> 0 votes

---
Tags: code-challenge, chess, classification, test-battery
---