title: Recycling for the New Year

text:
# Question
Title: Recycling for the New Year
A good resolution for 2015 is to live more sustainably. We'll start by recycling. Recycling code, that is!

Your task is to print the number `2015` to STDOUT, with or without trailing newline (and *only* that). However, you have to do so by *recycling* some old code from PPCG. Here is how that works:

* Pick any *answer* posted on CodeGolf.SE before 2014-12-16 00:00:00Z (the day I posted this in the sandbox). *Exception:* You may not use any answers from last year's New Year's challenge.
* Choose *one* code block from that answer (not an inline code snippet, it has to be a on its own paragraph). This block must be advertised as actual code, e.g. you cannot use test cases or example output which happen to use monospace formatting.
* Rearrange the *characters* in that code block to form your submission for this challenge. You may only change the order, not add or remove any characters. This includes newlines.
* You must be able to show that the original source block is syntactically valid in your language. In the best case you can do this by showing that it runs without compile-time or run-time errors. So while the original code may have been Java, you could use it for a Whitespace answer (as every file is valid in Whitespace), but probably can't use it for a Python answer (as the original won't be valid Python syntax).

Note that your answer must ignore all input and external state (including the actual current date). It *may* read from STDIN, say, as long as it doesn't crash if it's empty, and produces the same output for all possible contents of the stream.

Your resulting code has to be a full program (not a function, nor a snippet which assumes a REPL environment).

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

# Leaderboards

I'm sure this will play out very differently in different languages. So the following Stack Snippet generates both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

```
function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);i=i.replace("{{PLACE}}",t++ +".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=43048;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td></td><td>Author<td>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table>
```

# Answer
# GolfScript, 9 bytes

The original answer (dibs!) is also in GolfScript, which is how I know it is syntactically valid. I tested on http://golfscript.apphb.com/ .

```
2015}{.**

```

I despise the use of languages designed for golfing, but I had to win this challenge, so I betrayed my values by posting this answer. I don't know what most of the characters do in this language, but I once inadvertently learned, while skimming a GolfScript answer, that an unmatched `}` comments out the rest of the program. This allowed me to ignore the rest of the characters.
> 23 votes

# Answer
# Befunge-93, 2085 bytes

I thought I'd have fun and go meta by recycling the best of the recycled. Not going for any awards for brevity here.

```
+2012+1+1e1 or b+bbv+b+NN
"a"""""
p((('?'.ord-' '.ord )/(1.0/'A'.ord)).to_i)
<<id
                   1
                   !
                   _"  fabaaaca"-.-.-.-.+"O"2::++p

aa
AaAAaAAaAAaAAaA
eEe ddd OoOOoOOoOOoOOoOOoOOoOOoOOoOOoO ddD Ccc eEE
ccc LLl
SssSss LLl
SsS LLl
SsSSsSSsSSsS LLl
cccccc
mMm

+   +     a     pppp  pppp  y   y     n   n eeeee +     +    y   y eeeee     a     rrr    "
+   +    a a    p   p p   p  y y      nn  n e      + + +      y y  e        a a    r  r   "
+++++   aaaaa   pppp  pppp    y       n n n eee    + + +       y   eee     aaaaa   rrr    "
+   +  a     a  p     p       y       n  nn e       + +        y   e      a     a  r  r
+   + a       a p     p       y       n   n eeeee   + +        y   eeeee a       a r  r   "

Hope to see another round of awesome programming puzzles and code golf challenges

===============================
"" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" " ' ' ' ' '

Big char dump below (will clean up if there's more languages to squeeze in):

  $$$$$$$()++++++++++++++++++++++++++++--------------------------/////:::;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<>>>>>??AAACCDDEEEFHHLLMMMMM
NOOOOOOOOOOORRRRRRRRRSSSUUUUV[\]___aaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbbbbbbbcccccccccccccddddddddddddddddddddddddddddddddddddddd
ddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeffffffffffghhhhhhiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiilll
llllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnnnnnnnnnnnnnnn
nnnnnnnnnnnnnoooooooooooooooooooooooooooooooooooooooooooooooooppppppppppppp
ppppppppppppprrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrsssssss
ssssssssssssssssssssssssstttttttttttttttttttttttttttttttttttttttttttttttttt
ttttttttttttttttttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
uuuuuuuuuuuuvvvvvvvvwwxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
yyyyyyyyyyzz{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}

"""
one=1
print(int(ord('A')/(one/(ord(' ')-one))))
id
"mOO"

```

This is actually also a polyglot for 5 languages: Befunge-93, oOo Code, Pyth, Python 3 and Ruby. However, since the original code is only syntactically valid for Befunge-93, I'm only counting that.

Unfortunately the original code had only one pair of `[]` and too many `.`s, so I wasn't able to actually fit Brainfuck in (hence the oOo Code).

---

# Notes

This turned out to be surprisingly restrictive, because:

* The full set of digits available is `001111111222`, requiring the use of `ord` for Ruby and Python. In particular there's no `5`, which turned out to be a pain for Pyth.
* The lack of `@` meant that `p` needed to be used to place an `@` for Befunge.
* The lack of `*` meant that we had to multiply by dividing by the inverse of a number. Fun.

## Befunge-93

The Befunge program is

```
                   v
                   1
                   !
                   _"  fabaaaca"-.-.-.-.+"O"2::++p

```

where we've skipped the useless instructions. We encode each digit as the difference in ASCII values between chars, specifically `cabf` vs. `a`.

## oOo Code

The corresponding BF is

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

```

, of which the only relevant part is

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

```

## Pyth

Pyth only executes the first line, so

```
+2012+1+1e1 or b+bbv+b+NN

```

Note that Pyth uses an prefix notation, so the first part of the line is actually

```
2012 + (1 + (1 + (1 % 10)))

```

(*Note: `e` means `%10`*)

Due to the nature of Pyth, this is automatically printed. The rest of the line is valid Pyth, but the preceeding space before the `o` suppresses the automatic printing.

## Python 3

The majority of the Python code is commented out using strings, especially a large triple-quoted string in the middle. Ignoring a few stray strings, we have:

```
+2012+1+1e1 or b+bbv+b+NN
"""
...
"""
one=1
print(int(ord('A')/(one/(ord(' ')-one))))
id

```

The first and last lines are syntactically valid, but do nothing. The middle two lines print what we need.

## Ruby

The Ruby code is similar, but we're using a heredoc instead of a triple quoted string to comment out most of the program. Ignoring some stray strings, we have:

```
+2012+1+1e1 or b+bbv+b+NN
p((('?'.ord-' '.ord )/(1.0/'A'.ord)).to_i)
<<id
...
id

```

Once again, the first line is syntactically valid, but does nothing. The second line prints what we need.
> 17 votes

# Answer
# CJam, 12 bytes

```
T~mp[]!_1+oE^

```

The Unscramble the Code topic is a really good source for random number printing. This one was quite fun to piece together :)

```
T~     bitwise not of 0 is -1                     [-1]
mp     replace with 0 as -1 is not prime          [0]
[]!    not of an empty array (falsy) is 1         [0, 1]
_      copy that 1                                [0, 1, 1]
1+     add 1                                      [0, 1, 2]
o      output top of stack                        [0, 1]           2
E      push 14                                    [0, 1, 14]       2
^      bitwise xor                                [0, 15]          2
       (CJam implicitly prints stack afterwards)  []               2015

```

---

## Bonus answers

14 bytes:

```
36.e8 .79e2%15

```

19 bytes:

```
0_*1_)@@{_%\_)*\};5

```
> 11 votes

# Answer
# Ostrich, 198

I'm excited to get an Ostrich answer out; I don't care how long it is. :P (this is version 0.5.0, by the way)

```
{: rotate ( circ n -- )
    neg swap change-circular-start

IN: 1 9 [a,b] <circular> dup 6 rotate >array .
{ 4 5 6 7 8 9 1 2 3 }
IN: 1 9 [a,b] <circular> dup 3 rotate >array .
 7 8 9   3 4  6 };2 n15

```

Original:

```
: rotate ( circ n -- )
    neg swap change-circular-start ;

IN: 1 9 [a,b] <circular> dup 6 rotate >array .
{ 4 5 6 7 8 9 1 2 3 }
IN: 1 9 [a,b] <circular> dup 3 rotate >array .
{ 7 8 9 1 2 3 4 5 6 }

```

All I changed was the following:

* Wrapped everything other than `2 n15` in a block (`{}`) that is immediately popped (`;`).
* Stuck `2 n15` at the end. `2` pushes a `2`, `n` pushes a `0`, and `15` pushes `15`, which ultimately becomes `2015` when output.

This actually helped me find a bug: `2n15` doesn't work for some reason (it prints `215`), but both `2 n15` and `2n 15` work. I'll have to figure out why that is....

Here's the search query I used to find this perfect code sample:

> created:..2014-12-16 is:answer code:"2" code:"0" code:"1" code:"5" code:"\]" code:";"

This answer would work for 140, but I'm going to see if I can go smaller....
> 7 votes

# Answer
# JavaScript, 26 bytes

Original:

```
alert(998|(103>8>0&41>-0))

```

Recycled:

```
alert(4030>>(998>1|8&1-0))

```

It just shifts 4030 one bit to the right.
> 7 votes

# Answer
# CJam, 14 bytes

This one is a bit tricky, so I had to post it even though its a bit long. Original answer is also in CJam, so its valid.

Original answer:

```
92e8.17 5e6.3%

```

Recycled 2015:

```
9.68e3 .7e2%15

```

**How it works**

```
9.68e3 is 9680
.7e2 is 70
9680 70% is 9680%70 = 20
15 is 15

```

So the stack contains `20` and `15` which are printed one after another, printing 2015

Try it online here
> 5 votes

# Answer
# Marbelous, 54 bytes

### Boring answer (54 bytes)

```
32303135
:R
:Q
++003333333567QQRR}0

```

(followed by a ton of trailing newlines to equal 54 bytes)

Original Answer

The main board simply drops marbles representing each of character of `2015`. `R` and `Q` boards are defined, but never used.

### Alternative answer (92 bytes)

```
3W!!?0]]>W/\&0&1@1@0@0
      ]]>W/\&0&1@1@0@0
                @1  @0
03  02
\\  //
32+A
  Dp

```

Original Answer

Spaces as blank cells should be checked. This first prints `2` (0x32), then prints `0x03+0x02+0x0A=0x0F=15` as a three digit decimal (`015`). The first three lines do nothing.

Test answers here.
> 5 votes

# Answer
## Pyth, 25

https://github.com/isaacg1/pyth

```
J6ifqT++2010/JJ4U*2^TJ^TT

```

Here is the original answer (also written in pyth). I know that this is not a very competitive answer (there is python answer of length 26), but I really enjoyed coming up with this, and I think it comes out into a rather humourous answer.

Explanation:

```
J6                           : J=6
  i                   ^TT    : convert_to_base(..., 10 BILLION)
   fqT          U*2^TJ       : filter(lambda T: T==..., range(2*10^6)
      ++2010/JJ4             : 2010 + J/J + 4

```

Basically this is filtering a list of the first two million numbers for being equal to 2015. Then, it treats this list of numbers as the digits of a base 10 BILLION number. Thankfully, there is only one number equal to 2015 in the range, so you get 2015\*10000000000^0, which is just 2015. This takes a couple seconds to run.
> 4 votes

# Answer
# Perl, 48 bytes

```
\d>\fDg;print ord($:)*($_=$=+/~?/)+$_|//<<(\n>n)

```

Original Answer
> 4 votes

# Answer
# Python 2, 26 bytes

```
iiiceex=";;+=*";print 2015

```

Taken from the Smallest python script to print even numbers 0 to 100 thread. This is probably the solution @FryAmTheEggman was alluding to.
> 3 votes

# Answer
# \>\<\>, 57 bytes

**Original C++ code, from the RadioASCII challenge:**

```
#include <cstdio>
int main(){int x;printf("Lawrencium");}

```

**Recycled \>\<\> (Fish) code:**

```
eclne)nfn;
   ""#(();<>Laaccddiiiiiiimmnnnoprrsttttuuwx{}

```

Like Befunge, \>\<\> is a stack-based 2D language. Execution starts from the top left and is initially rightward. Only the first line of the program is executed, in the following manner:

```
e      Push 14                          [14]
c      Push 12                          [14, 12]
l      Push the length of the stack     [14, 12, 2]
n      Output as num                    [14, 12]          2
e      Push 14                          [14, 12, 14]      2
)      Push 1 if greater than else 0    [14, 0]           2
n      Output as num                    [14]              20
f      Push 15                          [14, 15]          20
n      Output as num                    [14]              2015
;      Terminate                        [14]              2015

```

Now the big question is — why is the C++ code valid \>\<\>? In \>\<\> there are ways to change the direction of program flow (it's a 2D language, after all):

```
^>v<     Arrows which direct program flow a certain direction
_/|\     Mirrors which reflect the direction of program flow
#        Four-way mirror, reflect from all directions

```

When the C++ code is executed, the initial `#` reflects program flow leftward. But \>\<\> is toroidal, so the instruction pointer wraps around, appearing from the end of the line, meeting the `>` which directs program flow rightward again. The pointer then wraps back to the `#`, bounces back to the `>`... and thus an infinite loop occurs and an error is never thrown.
> 2 votes

# Answer
# Mathematica, 60 bytes

```
⌊DF@IM~RS~ad~ee~ee~ggggiiimmnnoorrrstt~.22346⌋Print@2015

```

Source

The part in the `Floor` brackets is just a series of function applications of non-existing functions (which Mathematica doesn't have a problem with, because of its symbolic computation model). Likewise, just writing the flooring and `Print@2015` is multiplication, which Mathematica also doesn't complain about. Without the syntactic sugar, it would be

```
Floor[ggggiiimmnnoorrrstt[ee[RS[DF[IM], ad], ee], 0.22346]] * Print[2015]

```

Since we're not assuming a REPL environment, the evaluated result of this is never printed (which would be `Null Floor[ggggiiimmnnoorrrstt[ee[RS[DF[IM], ad], ee], 0.22346]]`), but only the side effect of the `Print` actually goes to STDOUT.

Thanks to Sp3000 for turning up the source to this.
> 2 votes

# Answer
# Python 3, 1878 bytes

Very long, but wanted to share anyway:

```
import sys,re,zlib as z,base64
print(2015)#,PIL.Image as ire.search(str(z.adler3(i.open(sys.argv[1]).tobytes()[2::6])%203)+'(\\D+',z.decompress(base64.b8decode(b'c${Tc%XZ>86NyfdNqBH<%b?iLI_EpFkwO-GfQC$tcfjoB$+h*^;0s?o$g*?uzgjxs%~BKif!C3zALZEU!&?wJd#-mqgS@p<P&+)AsV|c*52*C>U&(_4w^urvvWJU8Bj;bvv4ia;eiJLu+bsXLru`DjH|W<`|;xLq++kv5k8VWZgQe*`_u+opEF8>A6qjM%k#skzbiuJ7dL_*><K@9l6!M*H(|w)PZJ2`RYy7K2VVrv+zc)&2Fc?wvh|^#ksyymE?D!Q$3!LbFX%h%vT%1#lr486Iybw?0!`H)ZlZ#XIao2uXTr}(IBl@wRWHa#})bgV);O3HoW7+T*!5M3=^mu6Ri$`7L;uUWj~gsqR6gQR9h7^nKdBIgy>ats36%|M|8p1x;32(ZfK9R5_xK5ts=Sz70c%SIK&g3N1E|sg{n3>JSbKwwhssGcb$8uMNw=Nv;f_;rj?}kz(3-&#FQw@O;q(8nGHjbrTC(NQv=ckXT|eHr|amahCq(7T6<LBTr5Gj>fHV~3DcYINN!Qr`6Dl?jT>!4u5~bb%Zi6VTax;%vg*m325J_$nEC%yqbbYeEp!K_K7k)W-XCP`6+}N7tktMVX+{@c2L&kLAc&IvspGrzZ$F`uOBg}fA3W2neAU}tg~<+iCN=<sR^Zke+9WNhnCyy6!8nfa>33&OWiPt2s=OMTrUgilSYQxrG!gziB!Aj83zX&6S|yjIQkA?iF0n%?<+B=%_D11aoCv?@Q&eei{sqNkr7RG`#*xyzSUE6BUNnZK)3|3Wls}K$qaKv;jOO#!{3Ms)4CQ?shafnAF^zVq(`K9o2xL5JoQoGea+W1$+xmw&8OMOtN1Pid6UAcd+*_bB6IY$KjrO=ac^tPv3(8O`&(agOBbT{Va6s}Rm9&`I#yivC;MhW8=n+^^&Reho;~!~W<xgH6bVq3^=H7)sUXV2nv~DP4`CY`f55i&qH)DvPMQy>)y*Z=|68w@v=#oo5^RSh5R2F%1-vt>h=|+1n0pE^Yq-72!)1+o{hD_3<Cyxpyr6r%cei-AFQ*h1seM$MP>ovLS2k#Ci$to#do$s3MXu2lZsw~9HkbjVWM@1!{w>}LWVj#j2qC(+*Okc>=<qcV}*}+U_QK+(ZZ(x>ZMdDDWtgHiBK+7p6aHHI`u-h6z7|Xm`>D1t4uEp271y7oCI^{1^H~O7QRxTA_U&92Q8z$J2O|5Lbeg_0umd^pSU<%-ki7LtDvo&AgIt0h~6(y@Hr+kyLJ$<B#07KdGob0EW$7@f{GszaUv#tkpSyk759Khmvq-aiyM-_&x_VCTx$Vy<;$<k{T$-@{Mhc<<%KD1AHK^MKkg%pYIW}SxhV?&a{o9=rs@*+hqyoioE=TF>9S<KxY+^69^OA0jkS#0!w@kw4}KTcP9#+PVW+qB|7B`Y?eRs+7}8RSAs?i?-Cz#Wp(Iihd`nI!Q_i%R^o_;fvDQ5|{Cr;yWeirL>_l#(wn)$QenJkK6Sgw)5NleBzvo&G#@>X`7Ib*aS4LHx9epI%BXXV&y7LJ&54g}D25-Q8>DZQ5hGKyIeJkQQu08%j|<x~)q(AOVw9P~Z*c0Z@VM6n#<}tBT6+T%4mZ9f*y76xlEFM~o$xr9*SZHd^6D-C!pkkp3m(-~W3&>KY@106L+;I><MJ^Dz`f{(I3i?u`2pWjUjlwZx`B1JB#h#u3xTH*b1K?TG40|4lxF1$_Pw+t?h2')).decode()).group(1))

```

Taken from KennyTM's answer.

I saw that 2, 0, 1 and 5 and # could be found in the code, so I moved some chars to make `print(2015)` and could comment out the rest. I also put the PIL import into the comment so it doesn't require that library.
> 1 votes

# Answer
# PHP, 21 bytes

```
<?=65*4*31*2/8;//7**9

```

Let's try this again. Taken from another PHP answer from Unscramble the Source Code. It's pretty basic, but so far it's the shortest program in a non-golfing language. You can verify it at http://codepad.org/15EjIYAU. The original code is as follows:

```
<?=9*8*7*6*5*4/3/2/1;

```
> 1 votes

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


# Question
Title: Convert RGB integer value into RGB values
For example, in traditional web hexadecimal, a certain base-16 number represents an RGB value. For example, 45A19C equals (69,161,156) in RGB.

You'll be converting from that number to RGB value, however, instead you'll be given that number in base-10 rather than base 16.

So in the example used above, 45A19C would equal 4563356 in base-10. Thus 4563356 converted to RGB would equal (69,161,156).

So assume the integer given is previously stored in variable n and is between 0 and 16777215. Take number n and convert it to RGB values between 0 and 255. Return or save in a variable the three values as a list \[r,g,b\].

An RGB to RGB int can be found here. This link converts the opposite of what your trying to do.

Shortest code wins.

If clarification is needed, please ask so I can fix my question to be more helpful.

# Answer
# AVR ABI, 0

Quantities larger than the registers in the AVR's registers are represented with multiple registers. So, when passing in a 32-bit 'n' to a function, it is passed as 4x8-bit registers. Effectively R(r24),G(r23), and B(r22) are directly addressable without any additional work by virtue of the CPU's register addressing.

Here's some 'C' code for the unpacking operation:

```
unsigned char r( unsigned long n ){return n>>16&255;}
unsigned char g( unsigned long n ){return n>>8&255;}
unsigned char b( unsigned long n ){return n>>0&255;}

```

disassembled examples from avr-gcc 4.8:

```
.global r
.type   r, @function
r:
ret
.size   r, .-r

.global g
.type   g, @function
g:
mov r24,r23
ret
.size   g, .-g

.global b
.type   b, @function
b:
mov r24,r22
ret
.size   b, .-b

```

For red, GCC just emits the return code since the red byte just happens to be in the return register already. For green and blue it copies the corresponding register into the return register and returns. The actual packing/unpacking is handled by the ABI - when done somewhere other than a function call boundary, it's handled purely by the register addressing. Both the copies and return opcode are overhead required to view this happening in the CPU - the compiler can use these registers directly if not required to place the result in the return register. Free RGB packing/unpacking is available when handing any 32-bit integer.

Another way to think about it is that the AVR's registers represent large numbers as a list of 8-bit registers, and that list happens to unpack RGB for us.
> 16 votes

# Answer
# Java ~~35~~ 31 bytes.

Yay!!! A java answer under 40 bytes.

```
new int[]{n>>16,n>>8&255,n&255}

```

Interestingly, java integers are always stored as Binary numbers.

Consequently this snippet returns \[69,161,156\] whether n = `0x45A19C`, `4563356`, or `0b10001011010000110011100`.
> 14 votes

# Answer
# CJam, 11 bytes

```
NG6#+256b1>

```

This assumes that the base-10 integer is stored in `N` (there are no lower-case variable names), and it leaves the required list on the stack. This simply gets the digits in base 256. To take care of leading zeroes, we first add 2563 = 166. This will always give us 4 digits, the first one being `1`, so at the end we slice off that extraneous digit with `1>`:

```
N           "Push N.";
 G6#        "16^6.";
    +       "Add.";
     256b   "Get base-256 digits.";
         1> "Slice off leading digit.";

```

Test it here. You can use the following framework to initialise `N` and view the stack afterwards:

```
4563356:N;
NG6#+256b1>
ed

```

Of course, if I'm allowed to just have the input on the stack, instead of storing it in `N`, the solution is only 10 bytes, `G6#+256b1>`.
> 7 votes

# Answer
# Ostrich 0.5.0, 13 bytes

```
n16 6?+256B1>

```

Might as well post this just to promote Ostrich, even though it's essentially the same as @MartinBüttner's. (The only thing I changed was `b` -\> `B`, since all built-in functions are either symbols or capital letters in Ostrich, and `G` -\> `16`  since Ostrich doesn't have that fancy built-in number (which it really should).)

Idential translation to Golfscript (18 bytes):

```
n 16 6?+256base 1>

```
> 6 votes

# Answer
# Mathematica, 22 bytes

```
IntegerDigits[n,256,3]

```

Basically the same as my CJam answer. But I don't know a lot of languages that handle base conversion with arbitrary bases, so I thought I'd post both versions.

This one handles leading zeroes by using `IntegerDigits`' third parameter which pads the result to specified number of digits.
> 3 votes

# Answer
# APL, 8 characters

`n⊤⍨3⍴256`

```
3⍴256  is 256 256 256
B⊤⍨A   is A⊤B
A⊤B    encodes B in a number system specified by A
         It doesn't have to use a uniform radix, e.g.:
         365 24 60 60 1000 ⊤ time

```
> 3 votes

# Answer
# C/C++, 31

```
int r=n>>16,g=n>>8&255,b=n&255;

```

Convergently evolved to TheBestOne's answer, with the same size.

# C/C++, 31

```
int c[]={n>>16,n>>8&255,n&255};

```

This one actually makes a list(array). I'm not sure if it would count without "int c\[\]=". If so, it would be 23 bytes

Also added Uri Zarfaty's optimization to not mask the red channel, as by this point blue and green are already shifted away.
> 1 votes

# Answer
# Ruby, 25

```
[16,8,0].map{|x|n>>x&255}

```

The javascript answer by @Oriol is valid ruby as well, but at least this uses ruby features... (and it's a byte shorter).
> 1 votes

# Answer
# Rebol - 43 40

```
x: to-tuple to-hex n reduce[x/6 x/7 x/8]

```

Example:

```
>> n: 4563356
== 4563356

>> x: to-tuple to-hex n reduce [x/6 x/7 x/8]
== [69 161 156]

```

Alternative 40 char solution:

```
map-each x[-16 -8 0][(shift n x)and 255]

```
> 1 votes

# Answer
# J (10)

```
(3#256)#:]

```

Demonstration:

```
    f=:(3#256)#:]
    f 4563356
69 161 156
    f 12
0 0 12

```
> 1 votes

# Answer
# JavaScript, ~~26~~ 22

```
[n>>16,n>>8&255,n&255]

```

Inspired by TheBestOne's answer. I don't know bitwise operators very much, but it seems to work.
> 0 votes

# Answer
# Python, 28 bytes

The final value is stored in `c`

```
c=[n>>16&255,n>>8&255,n&255]

```
> 0 votes

# Answer
# ARM Assembly, 45

```
UXTB r1, r0, 16
UXTB r2, r0, 8
UXTB r3, r0, 0

```

Assuming N is passed in to R0, R1 contains Red, R2 contains Blue, and R3 contains Green. The result list is stored in r1,r2,r3.

Assembles to 12B of ARM instructions or 6B of 16-bit Thumb instructions.
> 0 votes

# Answer
# Erlang, 25 Bytes

```
binary_to_list(<<N:24>>).

```

Using the bit syntax, extracts 24 bits from N, which results in a binary of size 3.
> 0 votes

# Answer
## Python 3, 23 bytes

```
*c,=n.to_bytes(3,'big')

```

If bare expressions are allowed then the following is one byte shorter:

```
[n>>16,n>>8&255,n&255]

```
> 0 votes

# Answer
# Ruby, 44

Not a winner, but this makes use of Ruby's (very useful) optional parameters to `String#to_i` and `Integer#to_s`. They both take a `base`.

```
f=->i{i.to_s(16).scan(/../){|x|p x.to_i 16}}

```
> 0 votes

# Answer
# C - 56 characters, but no calculations required

C doesn't really have lists, but would just like to point out that if you know the architecture (and there are macros to do this for you) you can retrieve RGB with no calculation, just defining types.

Something like this:

```
enum {B, G, R};
typedef union {int i; unsigned char u[3];}T;

```

Then you access like this:

```
#include <stdio.h>

int main(void)
{
    T t;

    // Set the color
    t.i = 0x45A19C;

    // Pull out the primaries
    printf("%u %u %u\n", t.u[R], t.u[G], t.u[B]);

    return 0;
}

```
> 0 votes

# Answer
# dc, 10

dc is a stack-based language so I'm assuming input and output on the stack is OK:

```
256~r256~r

```
> 0 votes

---
Tags: code-golf, number, base-conversion
---


title: Curator's Dilemma

text:
# Question
Title: Curator's Dilemma
# Introduction

You are a friend of a curator for an art museum, who has had the recent delight of getting modern art from four artists (*some of which may give the curator zero pieces of art, young scoundrels*). As this is modern art, all of any given artist's pieces look exactly the same. Your friend wants to use a computer to help decide which order to place these pieces in.

# Program Requirements

Your program must take five integers (passed to a function or inputted through stdin (or someway else)). The first four are the number of paintings supplied by each of the four artists. The last value is an permutation index `i` (counting from 1, not 0). The curator wishes to see the `i`th permutation by lexicographic order of the paintings.

Your program must output this permutation in any reasonable format: e.g. `abbccd` or `[0 1 1 2 2 3]`. The runtime for input totalling fewer than ten paintings must take less than an hour (this should hopefully be no problem).

**You are not allowed to use any in-built functions to work out permutations**

# Examples

Input: 0 1 2 0 2

Given that we have one painting by artist B and two by artist C (and they all look the same), the permutations in lexicographic order are:

> \['bcc', '**cbc**', 'ccb'\]

The highlighted permutation would be the correct output, because it is the second in lexicographic order.

Input: 1 2 0 1 5

> \['abbd', 'abdb', 'adbb', 'babd', '**badb**', 'bbad', 'bbda', 'bdab', 'bdba', 'dabb', 'dbab', 'dbba'\]

## Testing

Here are some tests that should be correct.

```
1 2 4 1 5    - ABBDCCCC
2 2 3 1 86   - ABBCACDC
4 1 2 0 24   - AACACBA
1 4 3 2 65   - ABBCBBDCDC

```

A short piece of code in Python3 that should randomly generate inputs and outputs is available here (not valid for entry, this uses the Python import of permutations):

```
from itertools import permutations
from random import randint
a,b,c,d,n = randint(1,2),randint(1,2),randint(1,3),randint(1,3),randint(1,15)
print(str(a) + " " + str(b) + " " + str(c) + " " + str(d) + " " + str(n) + " - " + str(sorted(set([''.join(p) for p in permutations(a * "a" + b * "b" + c * "c" + d * "d")]))[n-1]))

```

# Scoreboard

```
Optimizer - CJam       - 39  - Confirmed - Bruteforce
EDC65     - JavaScript - 120 - Confirmed - Bruteforce
Jakube    - Python2    - 175 - Confirmed - Algorithmic

```

# Answer
# Python 2: ~~175~~ 163 chars

This is not a serious golfing answer. With a different algorithm I reached 138 byte. Just wanted to post this here, because it doesn't use brute force. Complexity is Theta(#pictures).

```
f=lambda x:0**x or x*f(x-1)
def g(Q,n):
 while sum(Q):
  for j in 0,1,2,3:
   p=f(sum(Q)-1)*Q[j]
   for k in Q:p/=f(k)
   if p<n:n-=p
   else:print j;Q[j]-=1;break

```

## Usage:

```
g([1, 4, 3, 2], 65)

```

## edit:

Same algorithm, just some golfing: don't import the factorial method and little changes in the order of the calculations.

# Pyth translation: 61 characters

```
Lu*GhHUb1WsPQV4J*@QNytsPQFZPQ=J/JyZ)I<JeQ XQ4-eQJ)EN XQNt@QNB

```

Nothing special here, exact translation of my python code. Way too long though. I had too use a few ugly (long) things. The first 9 letter alone is the definition of the factorial.

```
Lu*GhHUb1    def y(b): G=1; for H in range(b): G*= H+1; return G

```

Also stuff like `Q[j]-=1` is way too long: `XQNt@QN` (1 character more than Python!!!)

## Usage:

Try it here: Pyth Compiler/Executor. Disable debug mode and use `[2, 2, 3, 1, 86]` as input.
> 5 votes

# Answer
# CJam, ~~50 43~~ 39 bytes

```
q~(])\{W):Wa*}%s:X{Xm*:s_&}X,(*{$X=},$=

```

This can be golfed a lot.

Takes input from STDIN in following format:

```
4 1 2 0 24

```

Outputs the painting. For example for above input:

```
0020210

```

Try it online here

Do note that the online compiler gives up for larger painting sizes. You will have to try larger inputs on the Java version
> 3 votes

# Answer
# JavaScript (ES6) 120  ~~138 147~~

As a function with the required five parameters, output via console.
Using symbols 0,1,2,3. I calc the total of symbols, then build and check every base 4 number having the required number of digits. Numbers with the wrong number of any digit are discarded.
Note: with JavaScript 32 bit integer this works for up to 15 paintings.

**Edit** Shorter (avoid .toString) and way faster (modified exit condition). Time for each test below 1 sec.

**Edit2** no algorithm change, golfed more (indentation added for readability)

```
F=(w,x,y,z,n)=>{
  for(a=0;n;n-=l=='0,0,0,0')
    for(l=[w,x,y,z],t=w+x+y+z,v='',b=a++;t--;b/=4)--l[d=b&3],v=d+v;
  console.log(v)
}

```

**Ungolfed** And no FireFox required

```
F=function(w,x,y,z,n) {
  for(a=0; n; a++) // exit when solution found (if wrong parameters, run forever)
  {
    l=[w,x,y,z]; // required number of each symbol
    t=w+x+y+z; // total of digits
    v=''; // init output string
    for(b=a;
      t--; // digit count down
      b >>= 2) // shift for next digit
    {
        d = b & 3; //get digit
        --l[d]; // decrement for the current digit
        v = d + v; // add to output string
    }
    l[0]|l[1]|l[2]|l[3] // if digits ok
    ||--n // decrement counter
  }
  console.log(v) // when found, exit for and print the answer
}

```

**Test** In FireBug/FireFox console

```
F(1, 2, 4, 1, 5)
F(2, 2, 3, 1, 86)
F(4, 1, 2, 0, 24)
F(1, 4, 3, 2, 65)

```

*Output*

```
01132222
01120232
0020210
0112113232

```
> 3 votes

# Answer
# Pyth, 20

```
@fqPQm/TdU4^U4sPQteQ

```

Try it here.

Input is in Python list form, e.g. `[1, 2, 4, 1, 5]`

Output is also in Python list form, e.g. `[0, 1, 1, 3, 2, 2, 2, 2]` for the above input.

The solution is brute force, and takes about 10 seconds, worst case, on my machine.

How it works:

```
@fqPQm/TdU4^U4sPQteQ
           ^U4sPQ         All permutations of [0, 1, 2, 3] with length equal to the number
                          of paintings.
     m/TdU4               Find the count (/) of paintings by painter in the input list.
 fqPQ                     Filter the permutations on the counts being the desired counts
                          in the input.
                          This gives all possible orderings of the paintings.
@                teQ      Index into this list at the given location - 1. (0-indexing)

```
> 2 votes

---
Tags: code-golf, combinatorics, permutations
---


title: Robot roadie needed to pack the truck

text:
# Question
Title: Robot roadie needed to pack the truck
As the band's roadie, you have to pack the truck. Your program will place the packages so that they fit in the smallest height.

## A badly packed truck

## Rules

Packages may be rotated through multiples of 90 degrees. Packages may touch but must not overlap.

The output is the repacked image (to file or stdout). Your program may use any input or output raster image format.

Your program must accept any number of packages of various shapes in images up to 4000x4000 pixels. It must not be hardcoded for this test image. If I suspect any submission to be tailored towards this specific image, I reserve the right to replace it by a new test image.

## Score

Your score is the smallest height of a rectangle that will contain your arrangement (the width is the input rectangle width). In the case of a tie, the earliest entry wins.

Standard loopholes are prohibited as usual.

# Answer
> 10 votes
# Language : Java

# Score : 555 533

I just went for trying to brute force a solution by iterating over the shapes in order of decreasing area (perimeter in case of tie) and trying out all packing possibilities until a valid packing is found for that shape at which point the shape's position is fixed and the algorithm goes on to the next shape. In order to hopefully improve the quality of the result when searching for a valid packing first all possible positions are tried with the shape rotated such that it is taller than it is wider.

Note: this assumes that the input image(s) have all of the shapes separated by white space. It takes the maximum width of the output as the first argument and a list of shape images as the other arguments (each shape image can have one or more shape separated by at least one line of white pixels)

```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import javax.imageio.ImageIO;

public class Packer {
    public static void main(String[] args) throws Exception {
        long t1 = System.currentTimeMillis();

        int width = Integer.valueOf(args[0]);
        List<Item> itemList = new ArrayList<Item>();
        for (int i = 1; i < args.length; i++) {
            itemList.addAll(getItems(ImageIO.read(new File(args[i]))));
        }

        File outputFile = new File("output.png");
        if (outputFile.exists()) {
            outputFile.delete();
        }
        outputFile.createNewFile();

        ImageIO.write(pack(itemList, width), "PNG", outputFile);
        long t2 = System.currentTimeMillis();
        System.out.println("Finished in " + (t2 - t1) + "ms");
    }

    private static BufferedImage pack(List<Item> itemList, int width) {
        System.out.println("Packing " + itemList.size() + " items");
        Collections.sort(itemList, new Comparator<Item>() {

            @Override
            public int compare(Item o1, Item o2) {
                return o1.area < o2.area ? 1 : (o1.area > o2.area ? -1
                        : (o1.perimiter < o2.perimiter ? 1
                                : (o1.perimiter > o2.perimiter ? -1 : 0)));
            }
        });
        Packing packing = new Packing(width);
        PackedItem.Rotation[] widthRots = { PackedItem.Rotation.ZERO,
                PackedItem.Rotation.ONE_EIGHTY };
        PackedItem.Rotation[] heightRots = { PackedItem.Rotation.NINETY,
                PackedItem.Rotation.TWO_SEVENTY };
        int count = 0;
        for (Item item : itemList) {
            count++;
            int minSize = Math.min(item.width, item.height);
            int maxSize = Math.max(item.width, item.height);
            int x = 0;
            int y = 0;
            int rot = 0;
            PackedItem.Rotation[] rots = widthRots;
            if (item.width > item.height) {
                rots = heightRots;
            }
            boolean rotsSwitched = false;

            PackedItem packedItem = new PackedItem(item, rots[rot], x, y);
            System.out.format("Packing item %d which is %d by %d\n", count,
                    item.width, item.height);
            while (!packing.isValidWith(packedItem)) {
                if (rot == 0) {
                    rot = 1;
                } else {
                    rot = 0;
                    if (x + minSize >= width) {
                        x = 0;
                        y++;
                        if (!rotsSwitched
                                && y + maxSize > packing.height) {
                            rotsSwitched = true;
                            if (item.width > item.height) {
                                rots = widthRots;
                            } else {
                                rots = heightRots;
                            }
                            y = 0;
                        }
                    } else {
                        x++;
                    }
                }
                packedItem.set(x, y, rots[rot]);
            }
            packing.addItem(packedItem);
            System.out.format("Packed item %d\n", count);
        }
        return packing.getDrawing();
    }

    private static List<Item> getItems(BufferedImage image) {
        List<Item> itemList = new ArrayList<Item>();
        boolean[][] pointsProcessed = new boolean[image.getWidth()][image
                .getHeight()];

        for (int i = 0; i < image.getWidth(); i++) {
            for (int j = 0; j < image.getHeight(); j++) {
                if (pointsProcessed[i][j]) {
                    continue;
                }
                ImagePoint point = ImagePoint.getPoint(i, j, image);
                if (point.getColor().equals(Color.WHITE)) {
                    pointsProcessed[point.x][point.y] = true;
                    continue;
                }
                Collection<ImagePoint> itemPoints = new ArrayList<ImagePoint>();
                Queue<ImagePoint> pointsToProcess = new LinkedList<ImagePoint>();
                pointsToProcess.add(point);
                while (!pointsToProcess.isEmpty()) {
                    point = pointsToProcess.poll();
                    if (pointsProcessed[point.x][point.y]) {
                        continue;
                    }
                    pointsProcessed[point.x][point.y] = true;
                    if (point.getColor().equals(Color.WHITE)) {
                        continue;
                    }
                    itemPoints.add(point);
                    pointsToProcess.addAll(point.getNeighbors());
                }
                itemList.add(new Item(itemPoints));
            }
        }

        return itemList;
    }

    private interface Point {
        int getX();

        int getY();

        Color getColor();
    }

    private static final class ImagePoint implements Point {
        private static final Map<BufferedImage, Map<Integer, Map<Integer, ImagePoint>>> POINT_CACHE = new HashMap<BufferedImage, Map<Integer, Map<Integer, ImagePoint>>>();
        private final int x;
        private final int y;
        private final Color color;
        private final BufferedImage image;
        private Collection<ImagePoint> neighbors;

        private ImagePoint(int x, int y, BufferedImage image) {
            this.x = x;
            this.y = y;
            this.image = image;
            this.color = new Color(image.getRGB(x, y));
        }

        static ImagePoint getPoint(int x, int y, BufferedImage image) {
            Map<Integer, Map<Integer, ImagePoint>> imageCache = POINT_CACHE
                    .get(image);
            if (imageCache == null) {
                imageCache = new HashMap<Integer, Map<Integer, ImagePoint>>();
                POINT_CACHE.put(image, imageCache);
            }
            Map<Integer, ImagePoint> xCache = imageCache.get(x);
            if (xCache == null) {
                xCache = new HashMap<Integer, Packer.ImagePoint>();
                imageCache.put(x, xCache);
            }
            ImagePoint point = xCache.get(y);
            if (point == null) {
                point = new ImagePoint(x, y, image);
                xCache.put(y, point);
            }
            return point;
        }

        Collection<ImagePoint> getNeighbors() {
            if (neighbors == null) {
                neighbors = new ArrayList<ImagePoint>();
                for (int i = -1; i <= 1; i++) {
                    if (x + i < 0 || x + i >= image.getWidth()) {
                        continue;
                    }
                    for (int j = -1; j <= 1; j++) {
                        if ((i == j && i == 0) || y + j < 0
                                || y + j >= image.getHeight()) {
                            continue;
                        }
                        neighbors.add(getPoint(x + i, y + j, image));
                    }
                }
            }
            return neighbors;
        }

        @Override
        public int getX() {
            return y;
        }

        @Override
        public int getY() {
            return x;
        }

        @Override
        public Color getColor() {
            return color;
        }
    }

    private static final class Item {
        private final Collection<ItemPoint> points;
        private final int width;
        private final int height;
        private final int perimiter;
        private final int area;

        Item(Collection<ImagePoint> points) {
            int maxX = Integer.MIN_VALUE;
            int minX = Integer.MAX_VALUE;
            int maxY = Integer.MIN_VALUE;
            int minY = Integer.MAX_VALUE;
            for (ImagePoint point : points) {
                maxX = Math.max(maxX, point.x);
                minX = Math.min(minX, point.x);
                maxY = Math.max(maxY, point.y);
                minY = Math.min(minY, point.y);
            }
            this.width = maxX - minX;
            this.height = maxY - minY;
            this.perimiter = this.width * 2 + this.height * 2;
            this.area = this.width * this.height;
            this.points = new ArrayList<ItemPoint>(points.size());
            for (ImagePoint point : points) {
                this.points.add(new ItemPoint(point.x - minX, point.y - minY,
                        point.getColor()));
            }
        }

        private static final class ItemPoint implements Point {
            private final int x;
            private final int y;
            private final Color color;

            public ItemPoint(int x, int y, Color color) {
                this.x = x;
                this.y = y;
                this.color = color;
            }

            @Override
            public int getX() {
                return x;
            }

            @Override
            public int getY() {
                return y;
            }

            @Override
            public Color getColor() {
                return color;
            }
        }
    }

    private static final class PackedItem {
        private final Collection<PackedPoint> points;
        private Rotation rotation;
        private int x;
        private int y;
        private AffineTransform transform;
        private int modCount;

        PackedItem(Item item, Rotation rotation, int x, int y) {
            this.set(x, y, rotation);
            this.points = new ArrayList<PackedPoint>();
            for (Point point : item.points) {
                this.points.add(new PackedPoint(point));
            }
        }

        void set(int newX, int newY, Rotation newRotation) {
            modCount++;
            x = newX;
            y = newY;
            rotation = newRotation;
            transform = new AffineTransform();
            transform.translate(x, y);
            transform.rotate(this.rotation.getDegrees());
        }

        void draw(Graphics g) {
            Color oldColor = g.getColor();
            for (Point point : points) {
                g.setColor(point.getColor());
                g.drawLine(point.getX(), point.getY(), point.getX(),
                        point.getY());
            }
            g.setColor(oldColor);
        }

        private enum Rotation {
            ZERO(0), NINETY(Math.PI / 2), ONE_EIGHTY(Math.PI), TWO_SEVENTY(
                    3 * Math.PI / 2);

            private final double degrees;

            Rotation(double degrees) {
                this.degrees = degrees;
            }

            double getDegrees() {
                return degrees;
            }
        }

        private final class PackedPoint implements Point {
            private final Point point;
            private final Point2D point2D;
            private int x;
            private int y;
            private int modCount;

            public PackedPoint(Point point) {
                this.point = point;
                this.point2D = new Point2D.Float(point.getX(), point.getY());
            }

            @Override
            public int getX() {
                update();
                return x;
            }

            @Override
            public int getY() {
                update();
                return y;
            }

            private void update() {
                if (this.modCount != PackedItem.this.modCount) {
                    this.modCount = PackedItem.this.modCount;
                    Point2D destPoint = new Point2D.Float();
                    transform.transform(point2D, destPoint);
                    x = (int) destPoint.getX();
                    y = (int) destPoint.getY();
                }
            }

            @Override
            public Color getColor() {
                return point.getColor();
            }
        }
    }

    private static final class Packing {
        private final Set<PackedItem> packedItems = new HashSet<PackedItem>();
        private final int maxWidth;
        private boolean[][] pointsFilled;
        private int height;

        Packing(int maxWidth) {
            this.maxWidth = maxWidth;
            this.pointsFilled = new boolean[maxWidth][0];
        }

        void addItem(PackedItem item) {
            packedItems.add(item);
            for (Point point : item.points) {
                height = Math.max(height, point.getY() + 1);
                if (pointsFilled[point.getX()].length < point.getY() + 1) {
                    pointsFilled[point.getX()] = Arrays.copyOf(
                            pointsFilled[point.getX()], point.getY() + 1);
                }
                pointsFilled[point.getX()][point.getY()] = true;
            }
        }

        BufferedImage getDrawing() {
            BufferedImage image = new BufferedImage(maxWidth, height,
                    BufferedImage.TYPE_INT_ARGB);
            Graphics g = image.getGraphics();
            g.setColor(Color.WHITE);
            g.drawRect(0, 0, maxWidth, height);
            for (PackedItem item : packedItems) {
                item.draw(g);
            }
            return image;
        }

        boolean isValidWith(PackedItem item) {
            for (Point point : item.points) {
                int x = point.getX();
                int y = point.getY();
                if (y < 0 || x < 0 || x >= maxWidth) {
                    return false;
                }
                boolean[] column = pointsFilled[x];
                if (y < column.length && column[y]) {
                    return false;
                }
            }
            return true;
        }
    }
}

```

The solution this produces (takes about 4 minutes 30 seconds on my machine) is:

Looking at this picture it seems like the result can be improved by iterating over all of the shapes post packing and trying to move them all up a bit. I might try doing that later.

---
Tags: code-challenge, combinatorics, image-processing, packing
---


title: Code a Code Slidey Puzzle!

text:
# Question
Title: Code a Code Slidey Puzzle!
The most recognizable sliding puzzle is the fifteen puzzle. It has a 4 by 4 grid, 15 tiles, and one empty grid space. The tiles can only move into the empty space and must always be in line with the grid.

Let's define a generalized sliding puzzle as a two-dimensional *W* wide by *H* high grid (*W*, *H* both positive integers) that contains some number of **identical unmarked** tiles (between 0 and *W*×*H* of them) snapped to the grid, arranged in any way (without overlapping), with empty grid spaces filling the rest of the area.

For example if *W* and *H* are 3 and a tile is `T` and an empty space is `E` one of many possible siding puzzle arrangements is

```
TTT
TET
EET

```

For these puzzles there are 4 possible moves: shove everything **up**, shove everything **down**, shove everything **left**, or shove everything **right**. 'Shoving' in some direction makes all the tiles travel in that direction as far as possible until they hit another tile or the grid boundary. Sometimes shoving will not change the layout of the grid,

If the example grid is shoved right the result is

```
TTT
ETT
EET

```

Shoved left the result is

```
TTT
TTE
TEE

```

Shoved down the result is

```
EET
TET
TTT

```

(notice that both the leftmost `T`'s moved)

Shoving up does not change the grid layout in this case.

Note that since the tiles are indistinguishable these puzzles do not have 'solved' states. Also note that a puzzle may start in a layout that is impossible to get back to once a shove has been made (e.g. one tile in the middle of a 3 by 3 grid).

# Challenge

Using only printable ASCII write two rectangular blocks of code, both *M* characters wide and *N* characters tall (for any positive integers *M*, *N*). One code block will represent a tile of a sliding puzzle, the other code block will represent an empty grid space.

Arranging these two code blocks into a *W* by *H* grid will create a code-represented sliding puzzle which can be saved as a text file and run as a normal program. When run, these kind of programs should prompt the user via stdin for a number from 1 to 4; **1 is for up, 2 down, 3 left, 4 right**. When the user types in their number and hits enter, the program calculates how to shove its source code tiles in that direction and saves the new puzzle layout in a file (either a new file or in the same file), then terminates.

This process can be repeated indefinitely with the new sliding puzzle code file generated after each shove.

# Example

Suppose my tile code block looks like this

```
//   my
// tile

```

and my empty grid space code block looks like this

```
//empty
//space

```

(*M* = 7, *N* = 2, this is of course not actual code)

Any valid sliding puzzle arrangement of these two blocks should create a program in the language I'm using that can be run to let the user shove in some direction.

The code representation of the example grid is:

```
//   my//   my//   my
// tile// tile// tile
//   my//empty//   my
// tile//space// tile
//empty//empty//   my
//space//space// tile

```

So running this and pressing 2 (for down) then Enter would write this to another file (or the same file):

```
//empty//empty//   my
//space//space// tile
//   my//empty//   my
// tile//space// tile
//   my//   my//   my
// tile// tile// tile

```

That file could then be run and shoved in the same exact way.

# Notes

* Any code-representation of a *W* by *H* sliding puzzle should be runnable and be able to shove itself properly. This includes all grid sizes from 1 by 1 to some reasonable maximum (216 by 216 or more).
* **A program *may* read its own source code.** There are no quine-based restrictions. Comments of any sort are also fine.
* The program must prompt for a direction to shove in even if there are no tiles to shove or no tiles can be shoved. The prompt is simply a place to type in a number, no message is required.
* You may assume the input is always valid (1, 2, 3, or 4).
* Padding your code blocks with spaces is fine. Remember that they can only be printable ASCII, this mean no tabs and no newlines (besides the newlines that help form the code blocks).
* If your language does not support stdin use whatever input method seems closest.
* You can require that a newline be at the end of your code-puzzle files. (Or require that it not be there.)
* How you name new files is not important. `f.txt` or just `f` is fine.
* The two code blocks may not be identical.

# Scoring

The goal is to do this with the smallest code size (which is why this is tagged code-golf). The submission with the smallest code block area (*M*×*N*) is the winner. Tie-breaker goes to the highest voted answer.

*Related: Code that runs the Game of Life on itself*

# Answer
> 6 votes
# TECO, 153

Empty block:

```
0T@^Ux#EBx#27@:^Ux##MxA1^QUq^T%d/51%w"G153UsZ/QqUlQq/153Un|Qq%s/153UlZ/QqUn'Qd&1UhQl<.UpQn<Qh-\"F%c'TRQs:C>QpJQn<D-%c"L%c1-Qh\|Qh\'RQs:C>Qw"GC|153%pJ'>EX

```

Tile block:

```
1T@^Ux#EBx#27@:^Ux##MxA1^QUq^T%d/51%w"G153UsZ/QqUlQq/153Un|Qq%s/153UlZ/QqUn'Qd&1UhQl<.UpQn<Qh-\"F%c'TRQs:C>QpJQn<D-%c"L%c1-Qh\|Qh\'RQs:C>Qw"GC|153%pJ'>EX

```

The program, which modifies itself in place, must be saved in a file named `x`. It can be run via the command `tecoc mung x.`. The dot is important; without it, TECO attempted to find a file named `x.tec`. The trailing newline must be present.

The printable ASCII restriction was a bit of a pain for this one, as the language utilizes many unprintable characters. Most of them can be replaced by a two-byte sequence beginning with a caret, but "Escape" (ASCII 27) is the one character that is 'inescapable', so to get it I had to put its ASCII value into a string and exec it. Thus, the 4-byte `EBx<Esc>` exploded into `@^Ux#EBx#27@:^UX##Mx`.

This could be reduced greatly, especially by splitting the program into two parts, storing them as strings and running only if both are present.

---
Tags: code-golf, quine, source-layout, printable-ascii, sliding-puzzle
---


title: Jump the Array!

text:
# Question
Title: Jump the Array!
Let's play a one-player game called *jump the array*. To play, you only need an array of integers, say `a`. You start at some position `i`, and on each turn, you jump to a new position. On turn `n`,

* if `n` is even, you jump to the absolute position `a[i] mod length(a)`,
* if `n` is odd, you jump to the relative position `(i + a[i]) mod length(a)`.

The array indexing starts at zero. You can count the first jump as turn `0` or turn `1`, which give a different game. Since the state space of the game is finite (your move is determined by your position and the parity of the turn number), you will of course eventually enter a loop of even length. Denote by `loop(a, i, b)` the length of this loop, when the first jump is counted as turn `b`.

# Input

A nonempty array `a` of integers to play the game with.

# Output

The maximum number `p` such that, when starting on some position `i` and counting the first turn as either `0` or `1`, you eventually enter a loop of length `2 * p`. In other words, your output is the number

```
max { loop(a, i, b)/2 : i in [0 .. length(a)-1], b in [0,1] }

```

# Rules

You can give a function or a full program. The smallest byte count wins, and standard loopholes are disallowed.

# Test cases

```
[0] -> 1
[-213] -> 1
[1,3,12,-1,7] -> 1
[2,3,5,7,9,11,13,17,19] -> 2
[-2,3,-5,7,-9,11,-13,17,-19,23,-27] -> 3
[0,2,5,4,-9,0,-1,1,-1,1,-6] -> 4

```

# Answer
> 6 votes
# Pyth: 28 character (Python 2: 116 character)

```
eSmhxtu+G%@Q+eG@QeGlQUQ]ddUQ

```

## Usage:

Try it here: Pyth Compiler/Executor

It expects a list of integers as input `[0,2,5,4,-9,0,-1,1,-1,1,-6]`

## Explanation:

I noticed one important property of the function `loop`: For each `i` there is a `j`, so that `loop(a,i,0) == loop(a,j,1)` and vice versa. Therefore we only need to compute the values `loop(a,i,b)` for `b=0`.

Proof: If the is a cycle `i -> j -> k -> ... -> z -> i` with `b = 0`, then there exists the cycle `j -> k -> ... -> z -> i -> j` with `b = 1`.

Therefore a simple script can work the following way. Iterate over all `i` and try to reach `i` by iteratively computing `i = a[(i + a[i]) mod len(a)] mod len(a)`. Since this computation may ran into a cycle without `i`, we cancel the computation after `len(a)` steps. Then we print the maximum cycle.

A **Python 2** implementation looks like this (**125 character**}:

```
a=input();A=len(a);m=[]
for i in range(A):
 j=i
 for c in range(A):
  j=a[(j+a[j])%A]%A
  if i==j:m+=[c+1];break
print max(m)

```

For the pyth implementation I used a little different approach. For each `i` I compute the list of positions, and look for `i` in this list.

```
eSmhxtu+G%@Q+eG@QeGlQUQ]ddUQ
  m                       UQ    for each d in [0, ..., len(input)-1] compute a
      u                ]d         list G (using reduce),
                                  which is first initialized with G = [d]
                     UQ           for each H in [0, ..., len(input)-1]:
       +G                            append to G the value
         %@Q+eG@QeGlQ                   input[G[-1] +input[G[-1]] % len(input)
                                        (notice that list lookups in pyth work with modular wrapping)
     t                            remove the first value (which is d)
    x                    d        and find the index of d in this shortend list
                                  (it's -1, if d is not in the list)
   h                              add 1
eS                              print the maximum (end of sorted list)

```

## edit: Python 2: 116 characters

@proud haskeller's solution was i few characters shorter than my Python solution, therefore I 'had' to shorten it a bit.

```
a=input();A=len(a);l=lambda j,i,c:c<=A and(c*(i==j)or l(a[(j+a[j])%A]%A,i,c+1));print max(l(i,i,0)for i in range(A))

```

The difference is, that I calculate the number recursively instead of iteratively.

# Answer
> 8 votes
# Python - 157

```
a=input()
z=len(a)
b=[]
for i in range(z):
    s,c,t=[],"",0
    while(c in s[:-1])-1:j=(i*t+a[i])%z;c=`t`+`i`;s+=[c];t^=1
    b+=[len(s)-s.index(c)-1]
print max(b)/2

```

# Answer
> 5 votes
# Haskell, ~~120~~ 105

```
f s|t<-l s=maximum[g$drop t$iterate(\i->s!!mod(i+s!!mod i t)t)i|i<-s]
g(x:s)=l$0:fst(span(/=x)o)
l=length

```

this generates an infinite list for each starting point (for golfing reasons we iterate over all values instead of all indexes, which are equivalent). then it calculates the cycle of each list (the cycle length of `xs` is `xs % []`).

it uses @jakubes's observations about cycles. because it steps 2 steps at a time, we don't need to divide by 2 at the end.

**Edit**: now using @MthViewMark's trick of dropping the first `n` elements to guarantee having a cycle with the first element. by the way, I managed to golf his algorithm to `112` characters:

```
l=length
o(x:y)=1+l(takeWhile(/=x)y)
j a|n<-l a=maximum$map(o.drop n.iterate(\i->mod(a!!mod(i+a!!i)n)n))[0..n-1]

```

# Answer
> 2 votes
# Python, 160

```
l=lambda a,b,c,d:(b,c)in d and len(d)-d.index((b,c))or l(a,(a[b]+[0,b][c])%len(a),~c,d+[(b,c)])
j=lambda a:max(l(a,b,c,[])for b in range(len(a))for c in(0,1))/2

```

Function for answer is `j`.
The recursive function `l` returns the loop length for a given array, start, and first turn, and the function `j` finds the max.

# Answer
> 2 votes
## Haskell - 139 characters

```
l=length
o(x:y)=1+l(takeWhile(/=x)y)
j a=maximum$map(o.drop n.iterate(b!!))[0..n-1]
 where b=zipWith(\x y->mod(a!!mod(x+y)n)n)a[0..];n=l a

```

Examples:

```
λ: j [0]
1

λ: j [-213]
1

λ: j [1,3,12,-1,7]
1

λ: j [2,3,5,7,9,11,13,17,19]
2

λ: j [-2,3,-5,7,-9,11,-13,17,-19,23,-27]
3

λ: j [0,2,5,4,-9,0,-1,1,-1,1,-6]
4

```

This makes use of @jakube's observation that you need only check half the starting values, while performing 2 step per iteration.

# Answer
> 1 votes
# Mathematica, ~~189 162~~ 161 bytes

If anonymous functions are allowed - 161 bytes:

```
Max[l=Length;Table[b={};n=p;i=s-1;e:={i,n~Mod~2};While[b~Count~e<2,b~AppendTo~e;h=#[[i+1]];i=If[EvenQ@n++,h,i+h]~Mod~l@#];l@b-b~Position~e+1,{s,l@#},{p,0,1}]/4]&

```

Otherwise - 163 bytes:

```
f=Max[l=Length;Table[b={};n=p;i=s-1;e:={i,n~Mod~2};While[b~Count~e<2,b~AppendTo~e;h=#[[i+1]];i=If[EvenQ@n++,h,i+h]~Mod~l@#];l@b-b~Position~e+1,{s,l@#},{p,0,1}]/4]&

```

Running this on all the test-cases:

```
f /@ {
  {0},
  {-213},
  {1, 3, 12, -1, 7},
  {2, 3, 5, 7, 9, 11, 13, 17, 19},
  {-2, 3, -5, 7, -9, 11, -13, 17, -19, 23, -27},
  {0, 2, 5, 4, -9, 0, -1, 1, -1, 1, -6}
}

```

Results in:

```
{1, 1, 1, 2, 3, 4}

```

# Python 2, 202 bytes

```
def l(a,n,i):
 b=[]
 while not[i,n]in b:b.append([i,n]);i=(a[i]if n<1 else i+a[i])%len(a);n+=1;n%=2
 return len(b)-b.index([i,n])
def f(a):print max([l(a,n,i) for n in[0,1]for i in range(len(a))])/2

```

**DEMO**

This is nearly a port of my Mathematica answer.

# Answer
> 1 votes
# Mathematica, ~~113~~ 112 chars

```
l=Length;m=MapIndexed;f=Max[l/@ConnectedComponents@Graph@m[Tr@#2->#&,Part@@Thread@Mod[#+{Tr@#2,1}&~m~#,l@#,1]]]&

```

Example:

```
f /@ {
  {0},
  {-213},
  {1, 3, 12, -1, 7},
  {2, 3, 5, 7, 9, 11, 13, 17, 19},
  {-2, 3, -5, 7, -9, 11, -13, 17, -19, 23, -27},
  {0, 2, 5, 4, -9, 0, -1, 1, -1, 1, -6}
}

```

> {1, 1, 1, 2, 3, 4}

# Answer
> 1 votes
# ised 82

```
ised '@1{0,2,5,4,-9,0,-1,1,-1,1,-6};@2{1};' '@{4 5}{(@3{:$1_x++x*@2{1-$2}:}2*#$1)::[#$1]};{1+?{:@5{$3::$5}=$4:}@::[2*#$1]_0}/2'

```

The first argument doesn't count into length (array initialization into `$1` and `b` initialization into `$2` \- select the "game").

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


# Question
Title: Build a program to analyze coin flip sequence choices
In a puzzle in an old book of mine, a game is defined in which two players choose sequences of coin flips that they believe will appear first when a coin is repeatedly flipped. (It was actually odd and even dice rolls, but this little detail doesn't matter in terms of problem equivalence.)

It is noted that if player 1 chooses `TTT` and player 2 chooses `HTT`, that player 2 has a 7/8 chance of winning the game, since the only way `TTT` can come before `HTT` is if the first three flips are all tails.

Your job is to create a program or function that will deduce the probability that one of two chosen sequences will comes first. Your program will take two lines of input (or two strings as arguments), each representing a sequence of length 10 or less:

```
HTT
TTT

```

And output the probability that the *first* player will win, in either fraction or decimal form:

```
7/8
0.875

```

The shortest code to do this in any language wins.

# Answer
> 4 votes
## Python 3 (~~139~~ ~~136~~ ~~134~~ ~~132~~ ~~126~~ ~~115~~ 143)

Uses Conway's Algorithm as described at here. Handles all sequence pairs as long as the first is not a terminating subsequence of the second (as per instructions).

```
def f(a,b):c=lambda x,y=a:sum((x[~i:]==y[:i+1])<<i for i in range(len(x)));return 0 if b in a else(1/(1+(c(a)-c(a,b))/(c(b,b)-c(b))),1)[a in b]

```

Thanks xnor for shaving 6 bytes off. Thanks Zgarb for spotting a bug with subsequences.

# Answer
> 3 votes
# CJam, ~~44 38~~ 36 bytes

Using the same Conway's Algorithm as in here.

```
ll]_m*{~1$,,@f>\f{\#!}2b}/\-:X--Xd\/

```

Input is the two distinct sequences in two lines. The output is the probability of first winning over second. The inputs need not be of same lengths

I am using the formula for winning odds (*`p`*) for first player A as

Then the probability is defined as

which, after simplifying becomes

and after some simplification, becomes

---

Example input:

```
HTT
TTT

```

Output:

```
0.875

```

Try it online here

# Answer
> 0 votes
# Lua 211 190 184

Also using Conway's Algorithm. Still new to Lua so this can be golfed more for sure.

```
z=io.read;e=function(s,t)r='';for d in s:gmatch"."do r=r..(d==t:sub(1,1)and 1 or 0);end;return tonumber(r,2);end;a=z();b=z();print((e(a,a)-e(a,b))/(e(b,b)-e(b,a))/(1/((1/2)^b:len())));

```

### Ungolfed

```
z=io.read;
e=function(s,t)
r='';
    for d in s:gmatch"."do
        r=r..(d==t:sub(1,1)and 1 or 0);
    end;
    return tonumber(r,2);
end;
a=z();
b=z();
print((e(a,a)-e(a,b))/(e(b,b)-e(b,a))/(1/((1/2)^b:len())));

```

### First version

```
z=io.read;
e=function(s,t)
    r=0;
    for d in s:gmatch"."do
        r=r*10;
        if d==t:sub(1,1)then r=r+1 end;
    end
    return tonumber(r,2);
end;
f=function(n,o)
    return ((e(n,n)-e(n,o))/(e(o,o)-e(o,n)))/(1/((1/2)^3));
end;
print(f(z(),z()));

```

---
Tags: code-golf, probability-theory
---


title: Print all odd numbers from 0 to 100000

text:
# Question
Title: Print all odd numbers from 0 to 100000
My teacher gave me a simple problem which I should solve with a code tiny as possible. I should print all odd numbers from 0 to 100000 into a HTML document using javascript.

```
for(var y = 0; y < 100000; y++){
if(!(y % 2 == 0)){
document.write(y + " ");
}
};

```

Is it possible to do that shorter?

# Answer
> 13 votes
# JavaScript, 38 bytes

Yet another way to do this, shortest of all.

This supposedly prints each number on a new line using `\n`. Now as the data is being written to an HTML document, `\n` is not of any use and the numbers appear to be separated by space only.

```
for(i=1;i<1e5;i+=2)document.writeln(i)
```

# Answer
> 7 votes
# Javascript, 36 bytes

If order doesn't matter:

```
for(i=1e5;i--;)document.writeln(i--)

```

Writes the numbers in reverse order.

# Answer
> 6 votes
another way to do it in 38 bytes:

```
for(i=0;i<5e4;)document.writeln(i+++i)

```

explanation:`i+++i` means the same as `(i++)+i`, with the second `i` resolving to its new value (as effected by the ++) so it goes like this for the results:

* 0+1=`1`
* 1+2=`3`
* 2+3=`5`

etc...

# Answer
> 5 votes
# JavaScript, 40 bytes

```
for(i=1;i<1e5;i+=2)document.write(i+" ")
```

The code is fairly straight forward.

* I iterate from `i=1` to `i=1e5`. `1e5` is nothing but `1` followed by 5 `0`, so `100000`.
* In each iteration step, I print the value of `i` and increment `i` by `2`. Thus printing only every other number starting from `1` and till `100000`.

This prints all the odd numbers from `1` to `100000`.

# Answer
> 4 votes
# JavaScript, 40 bytes

Another way to do it!

```
for(i=0;i<5e4;)document.writeln(2*++i-1)
```

The code is fairly straight forward.

* Iterate from `i = 0` to `i = 5e4`. `5e4` is nothing but `5` followed by 4 `0`, so `50000`.
* In each iteration step, print the value of `2*i - 1` after incrementing `i` by `1`. Thus printing only odd numbers from `1` to `99999`.

# Answer
> 0 votes
**Using while** 42

```
i=-1;while((i+=2)<10e5)document.writeln(i)

```

---
Tags: code-golf, number, tips, javascript
---


title: That's almost Lisp!

text:
# Question
Title: That's almost Lisp!
## Challenge

Your challenge is to design an interpreter for a lisp-like language, which will from hence forth be coined: *GLisp*. The program code for *GLisp* will consist of an arbitrary amount of nested expressions denoted by brackets, in the following form:

```
(func arg1 arg2 ...)

```

Note that the interpreter must allow for extraneous whitespace characters before and after brackets, functions, and arguments.

## Types

You will implement four types, Integer, List, Boolean, and Function. Integers and Boolean values can be explicitly inserted into source code with their own syntax. Your interpreter must assume that a run of numeric characters denotes an Integer (you do not have to implement a syntax to explicitly insert negative integers). Your interpreter must also assume that `true` and `false` are designated Boolean values. Functions can not be explicitly defined by the user, and will always return a single value (a List of any length counts as a single value).

## Functions

The following functions are required to be implemented, and are in the format ***Function****, Arity*. If an Arity `n` is proceeded by a plus sign, then that denotes `n` or more arguments. You may assume that all arguments given to a function are of the same type, unless specificed otherwise. You may also assume that if no behaviour is specified for a certian type, then you may assume that no argument of that function will ever be of that type. Arguments will be referred to as in the following diagram:

`(func argument1 argument2 ... argumentn)`

* **+**, 2+

+ If all arguments are of the type *Integer*, you must return the sum of the arguments
    + If all arguments are of the type *List*, you must return the concatenation of the arguments in ascending order (`arg1+arg2+ ...`)
    + If all arguments are of the type *Boolean*, you must return the logical All of the sequence of arguments
    + `(+ 1 2 3 4 5) -> 15`
    + `(+ (list 1 2) (list 3 4)) -> (list 1 2 3 4)`
    + `(+ true true true) -> true`
* **-**, 2+

+ If all arguments are of the type *Integer*, you must return the difference of the arguments (`arg1-arg2- ...`)
    + If all arguments are of the type *Boolean*, you must return the logical Any of the sequence of arguments
    + `(- 8 4 3) -> 1`
    + `(- 0 123) -> -123`
    + `(- true false false true false) -> true`
* *****, 2+

+ If all arguments are of type *Integer*, you must return the product of the arguments
    + If one argument is of type *List* and the other is of type *Integer* (you may assume that these will only be the only arguments given), you must return a new **List** with the items in `arg1` repeated `arg2` times.
    + `(* 1 2 3 4 5) -> 120`
    + `(* (list 1 2 3) 2) -> (list 1 2 3 1 2 3)`
* **/**, 2+

+ If all arguments are of the type *Integer*, you must return the quotient of the arguments (`arg/arg2/ ...`) (you may assume that division is done sequentially, and that the decimal portion at every step is truncated)
    + If one argument is of type *List* and the other is of type *Function*, then you must return the resulting *List* after `arg2` has been mapped over every value
    + `(/ 100 10 3) -> 3`
    + `(/ (list 1 2 3) inc) -> (list 2 3 4)`
* **%**, 2

+ If all arguments are of the type *Integer*, you must return the modulus of the arguments
    + `(% 4 2) -> 0`
* **=**, 2+

+ If **both** the type and value of all arguments is the same, you must return true. Otherwise, return false.
    + `(= 0 0 0) -> true`
    + `(= 0 false (list)) -> false`
* **list**, 0+

+ You must return a list of all arguments, regardless of type. If no arguments are given, then you must return an empty list
    + `(list 3 4 (list 5)) -> (list 3 4 (list 5))`
* **inc**, 1

+ If argument is of type *Integer*, you must return the *Integer* incremented by one
    + If argument is of type *List*, you must return the *List* rotated clockwise a single rotation
    + `(inc 1) -> 2`
    + `(inc (list 1 2 3)) -> (list 3 1 2)`
* **dec**, 1

+ If argument is of type *Integer*, you must return the *Integer* decremented by one
    + If argument is of type *List*, you must return the *List* rotated counter-clockwise a single rotation
    + `(dec 1) -> 0`
    + `(dec (list 1 2 3)) -> (list 2 3 1)`
* **if**, 3

+ If given **three** arguments of any type: If the truth value of `arg1` is true, return `arg2`, else return `arg3`
    + `(if (not (list 1)) 8 false) -> false`
* **not**, 1

+ If given an argument of any type, if the truth value of `arg1` is False, return `true`, else return `false`.
    + `(not (list)) -> true`
* **len**, 1

+ If given an argument of type *List*, return the length of `arg1`
    + `(len (list 4 2 true (list 3) (list))) -> 5`

Truth table: `0, (list), false -> false`, where `(list)` denotes an empty list. Everything else is `true`.

Your interpreter can either be a full program that reads the source input from stdin or a file, or a function which takes the source as a string and returns the output value.

If choosing the former, the output for *Integers* is simply numbers, for *Booleans* is `true` or `false`, and for lists is a space separated sequence of values enclosed in brackets (eg. `(1 2 3 4 (5 6 7))` denotes `(list 1 2 3 4 (list 5 6 7))`).

If choosing the latter, the value must be returned in the implementation language's corresponding type, or, if no similar type exists, a custom type. *Lists* can be returned as Arrays or Vectors if the language doesn't have a *List* type, *Booleans* should be returned as a Boolean type in the language, or a custom type if the language does not support them.

## Test cases

```
(list 1 2 3 (list 4 5 true))  -> (1 2 3 (4 5 true))
(/ 4000 (+ 1 2 3 4 (* 5 8)))  -> 80
(+ (not (- (len (list 5 6 7)) (/ 10 3))) true)  -> true
(if (           len (list )  ) 4 (if    (+ (= 8 8    8) (not (list 4))) 8 5))  -> 5

```

## Clarifications

* Your interpreter may deal with invalid input in any way you choose, but it **must not** throw an exception (though, it may print an error message and exit smoothly)
* Functions will always evaluate arguments left to right
* Invalid input is any input which is syntactically incorrect. This includes, but is not limited to, mismatched brackets, division by zero, and partially applied functions (unless going for the bonus)
* For `=`, if any of the values are different **or** any of the types are different, return `false`

## Bonuses

* **Score * 0.8** if you support partially applied functions. For example, `((+ 2) 3)` would be the same as `(+ 2 3)`, but allows for things such as `(/ (list 1 2 3) (+ 2))`. You may assume that a function is partially applied if it receives less than its minimum number of arguments
* **Score * 0.85** if you do not evaluate the arguments applied to `if` unless they are going to be returned

This is code-golf, so the interpreter with the lowest byte count wins!

# Answer
> 7 votes
## Haskell, 1370 1263 1179 1128 1163 1107 1084 bytes * 0.8 * 0.85 = 737.12

```
import Text.Parsec
data V=I Int|L[V]|T|F|P[V]|X|A|S|M|D|U|E|Q|J|K|C|N|W deriving Eq
m Q=0;m C=3;m f|f`elem`[J,K,N,W]=1;m _=2
l=length
x v=[n|I n<-v]
y v=[l|L l<-v]
z v=[0<1|T<-v]++[1<0|F<-v]
(&)f=l.f>>=(.l).(==)
b a|a=T|0<1=F
s(I n)=show n
s(L v)='(':tail(v>>=(' ':).s)++")"
s T=d!!0;s F=d!!1;s _="error"
i(L v)=e$i%v
i v=v
e(P v:a)=e$v++a
e(f:a)|m f>l a=P(f:a)
e(A:a)|x&a=I$sum$x a|y&a=L$concat$y a|z&a=b$and$z a
e(S:a)|x&a=I$f$x a|z&a=b$or$z a
e(M:a)|x&a=I$product$x a
e[M,v,I n]=e$A:replicate n v
e(D:a)|x&a=I$v$x a
e[D,L v,f]=L$map(\a->e[f,a])v
e[U,I a,I b]=I$a`mod`b
e(E:a:v)=b$all(==a)v
e(Q:a)=L a
e[J,I a]=I$a+1
e[J,L[]]=L[]
e[J,L v]=L$last v:init v
e[K,I a]=I$a-1
e[K,L v]=L$drop 1 v++take 1 v
e[C,a,b,c]|a`elem`[I 0,L[],F]=c|0<1=b
e[N,a]=e[C,a,F,T]
e[W,L v]=I$l v
e _=X
f(a:b)=a-sum b
v(a:b)=foldl div a b
(%)f=fmap f
p=k$choice$try%([(I .read)%many1 digit,L%between(w"(")(k$w")")(many$try p)]++zipWith((.return).(>>).w)d[T,F,A,S,M,D,U,E,Q,J,K,C,N,W])
k=(spaces>>)
w=string
d=words"true false + - * / % = list inc dec if not len"
g=either show(s.i).parse p""
main=interact g

```

Full program, reading `stdin` and writing to `stdout`. `g` is the function version, as well.

Implements both partial functions, and lazy evaluation of `if`.

Sample runs (of the function version):

```
λ: g "(list 1 2 3 (list 4 5 true))"
(1 2 3 (4 5 true))

λ: g "(/ 4000 (+ 1 2 3 4 (* 5 8)))"
80

λ: g "(+ (not (- (len (list 5 6 7)) (/ 10 3))) true)"
true

λ: g "(if (           len (list )  ) 4 (if    (+ (= 8 8    8) (not (list 4))) 8 5))"
5

λ: g "(if false (/ 1 0) 5)"
5

λ: g "((+ 2) 3)"
5

λ: g "(/ (list 1 2 3) (+ 2))"
(3 4 5)

```

Now has all unit tests from the description:

```
λ: runTests
passed: g "(+ 1 2 3 4 5)" ==> 15
passed: g "(+ (list 1 2) (list 3 4))" ==> (1 2 3 4)
passed: g "(+ true true true)" ==> true
passed: g "(- 8 4 3)" ==> 1
passed: g "(- 0 123)" ==> -123
passed: g "(- true false false true false)" ==> true
passed: g "(* 1 2 3 4 5)" ==> 120
passed: g "(* (list 1 2 3) 2)" ==> (1 2 3 1 2 3)
passed: g "(/ 100 10 3)" ==> 3
passed: g "(/ (list 1 2 3) inc)" ==> (2 3 4)
passed: g "(% 4 2)" ==> 0
passed: g "(= 0 0 0)" ==> true
passed: g "(= 0 false (list))" ==> false
passed: g "(list 3 4 (list 5))" ==> (3 4 (5))
passed: g "(inc 1)" ==> 2
passed: g "(inc (list 1 2 3))" ==> (3 1 2)
passed: g "(dec 1)" ==> 0
passed: g "(dec (list 1 2 3))" ==> (2 3 1)
passed: g "(if (not (list 1)) 8 9)" ==> 9
passed: g "(not (list))" ==> true
passed: g "(len (list 4 2 true (list 3) (list)))" ==> 5
passed: g "(list 1 2 3 (list 4 5 true))" ==> (1 2 3 (4 5 true))
passed: g "(/ 4000 (+ 1 2 3 4 (* 5 8)))" ==> 80
passed: g "(+ (not (- (len (list 5 6 7)) (/ 10 3))) true)" ==> true
passed: g "(if (           len (list )  ) 4 (if    (+ (= 8 8    8) (not (list 4))) 8 5))" ==> 5
passed: g "(if false (/ 1 0) 5)" ==> 5
passed: g "((+ 2) 3)" ==> 5
passed: g "(/ (list 1 2 3) (+ 2))" ==> (3 4 5)

```

# Answer
> 5 votes
# Python 2, 1417 * 0.8 * 0.85 = 963.56

```
from operator import*
A=type;K="list"
def E():print"E";exit()
def R(G):
 len(G)or E();T=G.pop(0);L=[]
 if"("==T:
  G or E()
  while")"!=G[0]:L+=[R(G)];G or E()
  G.pop(0);return L
 if")"==T:E()
 try:
  x=eval(T.title())
  if Q(x)<2:return x
  E()
 except:return T
H="+ - * / = % if inc dec not len"
Z=lambda y:lambda x:reduce(y,x)
D=dict(zip(H.split(),[[sum,any,0,lambda x:sum((y[1:]for y in x),[K])],[Z(sub)],[Z(mul),all,0,lambda x:x[0][:1]+x[0][1:]*x[1]],[Z(div),lambda x:[K]+map(lambda z:S([x[1],z]if Q(x[1])==2else x[1]+[z]),x[0][1:])],[lambda x:len(set(map(str,x)))<2]*6,[lambda x:x[0]%x[1]],[lambda x:S(x[2])if S(x[0])in[0,[K]]else S(x[1])]*6,[lambda x:x[0]+1,0,0,lambda x:x[0][:1]+x[0][-1:]+x[0][1:-1]],[lambda x:x[0]-1,0,0,lambda x:x[0][:1]+x[0][2:]+[x[0][1]]],[lambda x:x[0]in[0,[K]]]*6,[0]*3+[lambda x:len(x)-1]]))
H=H[:15]+H+" if"
def Q(x):
 t=A(x);w=int,bool,str
 if t in w:return w.index(t)
 if t==list and x:return 5-(2*(x[0]==K)+(str==A(x[0])and len(x)<H.count(x[0])+1))
 E()
def S(G):
 if Q(G)<2:return G
 G or E();c=G[0];r=G[1:];c==K or r or E()
 if c!="if":r=[x if Q(x)in{2,4}else S(x)for x in r]
 if c==K:return[c]+r
 k=map(Q,r);m=min(k);M=max(k);v=[m,[-1,3][{m,M}=={4,5}]][m!=M]
 try:return D[c][v](r)
 except:E()
def C(x):return"(%s)"%" ".join(map(C,x))if A(x)==list else str(x).lower()
def I(G):
 for c in"+-*/%=()":G=G.replace(c," %s "%c)
 return C(S(R(G.strip().split())))
print I(raw_input())

```

Complete overhaul. If you want to see the previous versions, check out the edit history.

There's a lot more to be golfed. I'm slowly working on it.

With zlib/base64 we get **1093 * 0.8 * 0.85 = 743.24**:

```
import base64,zlib
exec zlib.decompress(base64.b64decode("eJx9VE1P4zAQvedXGEuV7MbttgX2kOADAtSugANbTljWKqSuNku+5Lg0BfHfd8ZJCwjt9tLpdN6bmTczXtuqIFVtbOIqS7KirqwbBufS7WoTX0uaZ42jwcqsyRXjUW2z0tErGps2c4x7/08251FAclOCARwQF9/L+biuajbh8Y1UOiDZmjIq5T0EkjnposDc/s5yQzk9knM10dFNKBXS6fhDzIHJGrexJbnxbNyz+Qhnd0jbSvOc5Ox+7DKXG8YRm63JHWv52SzqwS04Pci0qand3n0fLCQNyYgMyTciyQCBWZmSlUlJWTlsjgYPMk+Kx1VCdlFvtIBfbVLDdqLlwaVcZaljL1nNFuOmzlEhoVSzKURS7sREHFDgYmynppFeQ5s7SEVaCL3WXAv1wJrNY2cUm5yLJM8/YlsQSkVTHXoDKIatmmofvsqe+Xsg0IVFUrPe8RItmcJQ8aI7WcDmUs5M3hiCP0L1ornY02IFBy4cbmMcQ77GWeiWg6h6+P1DDAIHfS0H5xLSzDSHhGhNwCrVBDvVPu2yq+IrUTiFnv/Z9Qjq2/c/+pwQvaP/gmeAVR1Yf4EeyvMlTfTwOPysQssxISzXQi6A81SHi5DiQvpbwGWDXXTyHIx4K+FaxGNV5QJEw7UlDme93a/ddpyVK9Myx7s/pcRzI0m58qvlY05HbDb02kl5zUOUXyI9iomBXVFni3FabUrX+cMpbv9Vf6DL7kD90OcfbmEeHE4xTv0Bxha+QFv4Ka/xL3s4Q0CnR5JCo5GVqt1fVla+zsTJ236YHPe5xR6t7jBA1OdTqQ5BhCeJS3QnLI8LWWQle+LxLfhaNJ6lKgSMVxxr9VqI2zcpX0/E6ZvWqjiSt7o79r7+S2BUz5rZ93Pet3yBc+jCKBs0nA4ooeM/FaTD7Be4wFAdTqnX3HcA2oJnnFdbY3umH5142FcKfdFwNPw2kIzTaA5vnDV1nsD9p4KSQUPoIIVa+vIu2JLBYzYGUngR+P5FgE/gn1Ggtsn2V1bWG3T/BUW+qRU="))

```

*Note: If you see my score going up, it's probably because I found a few bugs*

# Answer
> 5 votes
# Common Lisp, 868 bytes * 0.85 = 737.8

Is it cheating to implement Lisp with Lisp? Lots to optimize here, still.

```
(SETF (READTABLE-CASE *READTABLE*) :PRESERVE)(PRINC(LABELS((B(X)(FIND X'(true false)))(R(X)(IF X'true'false))(V(X)(MEMBER X'(0()false)))(A(&REST X)(R(NOTANY #'V X)))(O(&REST X)(R(NOTEVERY #'V X)))(E(X &KEY N)(IF(LISTP X)(ECASE(FIRST X)(+(APPLY(IF(EVERY'NUMBERP #1=(MAPCAR(IF N #'IDENTITY #'E)(CDR X)))'+(IF(EVERY'LISTP #1#)'APPEND #'A))#1#))(-(APPLY(IF(EVERY'NUMBERP #1#)'- #'O)#1#))(*(IF(LISTP #2=(CAR #1#))(LOOP FOR I TO(1-(CADR #1#))APPEND #2#)(APPLY'* #1#)))(/(IF(LISTP #2#)(LOOP FOR I IN #2#COLLECT(E `(,(CADR #1#),I):N T))(REDUCE'FLOOR #1#)))(%(APPLY'MOD #1#))(=(R(LOOP FOR I IN(CDR #1#)ALWAYS(EQUAL I #2#))))(list #1#)(inc(IF(LISTP #2#)(APPEND(LAST #2#)(BUTLAST #2#))(1+ #2#)))(dec(IF(LISTP #2#)(APPEND(CDR #2#)`(,(FIRST #2#)))(1- #2#)))(if(IF(V(E(CADR X)))(E(CADDDR X))(E(CADDR X))))(not(R(V #2#)))(len(LENGTH #2#)))X)))(OR(IGNORE-ERRORS(OR(E(READ))"()")):E))

```

Prints out an E in case of an error in input. Sample runs:

```
$ sbcl --script glisp.lisp
(list 1 2 3 (list 4 5 true))
(1 2 3 (4 5 true))

$ sbcl --script glisp.lisp
(/ 4000 (+ 1 2 3 4 (* 5 8)))
80

$ sbcl --script glisp.lisp
(+ (not (- (len (list 5 6 7)) (/ 10 3))) true)
true

$ sbcl --script glisp.lisp
(if (           len (list )  ) 4 (if    (+ (= 8 8    8) (not (list 4))) 8 5))
5

$ sbcl --script glisp.lisp
(this is an error)
E

$ sbcl --script glisp.lisp
(if (% 4 2) (this is an error) 42)
42

```

# Answer
> 2 votes
# Haskell, 972

```
r=fst.f
f('(':s)|(f:a,b)<-g s=(f%filter(/="")a,b)
f s=span(`notElem`" ()")s
j=dropWhile(==' ')
g""=([],"")
g s|')':l<-r=([x],l)|(y,t)<-g$j r=(x:y,t)where(x,r)=f$j s
"%"%c=show$foldr(mod.read)(maxBound::Int)c
"+"%c|t(c!!0)<1="(list "++tail(c>>=(' ':).drop 6.init)++")"|t(c!!0)<2=show$sum$map read c|0<1=i$all((=='t').head)c
"-"%c|t(c!!0)<2=show$foldl1(-)$map read c|0<1=i$any((=='t').head)c
"*"%c=fst$f$"(+ "++unwords([1..read$last c]>>init c)++")"
"="%c=i$all(==c!!0)c
"/"%c|t(c!!0)<1,[a,b]<-c="list"%map(\x->b%[x])(fst$g$drop 6 a)|0<1=show$foldl1 div$map read c
"if"%[p,a,b]|elem p["0","()","false"]=b|0<1=a
"list"%c="(list "++unwords c++")"
"len"%[c]=show$length(words c)-1
"inc"%[c]|t c>0=show$read c+1|([],_)<-g$drop 6 c="(list)"|(x,_)<-g$drop 6 c="list"%(last x:init x)
"dec"%[c]|t c<1,(x,_)<-g$drop 6 c="list"%(drop 1 x++take 1 x)|0<1=show$read c-1
"not"%[c]="if"%[c,"false","true"]
s%c="?"
i p|p="true"|0<1="false"
t('(':_)=0
t(c:s)|c<':',c>'/'=1|elem c"th"=2
t _=3

```

quite a hacky solution. this stores everything as strings in output-ready form - their types can be distinguished by their first letter - `0..9` for numbers, `(` for lists, `t` or `f` for booleans, and everything else for functions.

to run use the `r` function.

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