# Question
Title: Jumblers vs Rebuilders: Coding with Tetris Bricks
In traditional Tetris, there are 7 distinct tetromino bricks, each denoted by a letter similar to its shape.

```
#
#      #    #
#  ##  #    #  ###  ##    ##
#  ##  ##  ##   #    ##  ##
I  O   L   J    T    Z    S

```

Consider the arrangements of these bricks that can make a solid W×H rectangle, for some positive integers W and H. For example, using 2 I's, 1 L, 1 J, 2 T's, and 1 S, a 7×4 rectangle can be made:

```
IIIITTT
LIIIITJ
LTTTSSJ
LLTSSJJ

```

The same bricks can be rearranged (by moving and rotating but **not flipping**) into a different 7×4 pattern:

```
IJJTLLI
IJTTTLI
IJSSTLI
ISSTTTI

```

Now consider using a rectangular block of code in place of the first arrangement. For example this 7×4 bit of Python 3, which prints `Tetris` to stdout:

```
p=print
x='Tet'
y='ris'
p(x+y)#

```

According to the first Tetris arrangement its 7 "bricks" are...

```
           x          '
      int  y          '  ='r   is
p=pr   t   p(  ='Te  )#   x   +y

```

In the other arrangement (one of many possible) they are unintelligible as code:

```
r#)x(x=
p'r'=y'
='istpT
p+ytnie

```

But, given the bricks separately, it might be possible to piece them back together properly. This is the basis of the challenge.

# Challenge

This is a challenge. There are two competing roles, the *Jumblers* and the *Rebuilders*.

The Jumblers submit answers with blocks of code that have been broken down into Tetris bricks.

The Rebuilders attempt to rebuild these blocks **in the separate question dedicated for them: Jumblers vs Rebuilders: Coding with Tetris Bricks - Area for Rebuilder Answers.**

### Jumblers

Using only printable ASCII (hex codes 20 to 7E) write a W×H rectangular program. When run, it must output the **sole** word `Tetris` to stdout (or closest alternative). **Do not post this code in your answer; don't give W or H either.** Break it up into some arrangement of Tetris bricks like the example above and post these in your answer. (Your code may contain spaces but since they are hard to distinguish, it's best to use some other character in place of spaces and tell people what you used.)

The harder it is to rebuild your program the better. There may be many ways to rearrange your code-bricks into a rectangle, possibly with different dimensions. What the code does when run in these different arrangements doesn't matter as long as at least one arrangement prints `Tetris` to stdout.

The only other restriction is that W * H be less than 1025.

Jumblers should specify their programming language (and version).

### Rebuilders

Your goal is to take a Jumbler's code-bricks and put them back into their original order, so `Tetris` is printed when the code is run. If the working arrangement you find isn't the one the Jumbler had in mind that's too bad for them.

Remember that only translation and rotation are allowed in rearrangements, not mirroring.

# Scoring

Each time a submission is rebuilt it is considered "cracked" and is no longer in the running. The first Rebuilder to rebuild a submission gets the credit for it. If an answer goes uncracked for 72 hours the Jumbler should reveal the solution and will be henceforth immune from being cracked. A Jumbler must do this to win, since otherwise it will be unclear if there even was a solution.

The winning Jumbler is the uncracked answer with the smallest area (W * H = 4 * num of bricks). In case of ties the highest voted answer wins. The accepted answer for this question will be the winning Jumbler.

The winning Rebuilder is the user who cracks the most submissions. In case of ties it goes to whomever cracked the most cumulative area.

# Notes

* You may not rebuild your own submissions. (But otherwise you may take on both roles.)
* Rebuilders may not attempt to crack the same answer more than once.

# Scoreboard

Sorted from oldest submission to newest.

```
+--------------+-------------+------------------+---------+----------+----------------+-------------------------------------------+-------------------------------------------+
|   Jumbler    |  Language   |       Area       | Immune? | Rebuilt? |   Rebuilder    |                      Link                 |                  Solution Link            |
+--------------+-------------+------------------+---------+----------+----------------+-------------------------------------------+-------------------------------------------+
| xnor         | Python 3    | 212              | no      | yes      | foobar         | https://codegolf.stackexchange.com/a/40142 | https://codegolf.stackexchange.com/a/40203 |
| xnor         | Python 3    | 340              | no      | yes      | feersum        | https://codegolf.stackexchange.com/a/40146 | https://codegolf.stackexchange.com/a/40189 |
| es1024       | C           | 80               | no      | yes      | user23013      | https://codegolf.stackexchange.com/a/40155 | https://codegolf.stackexchange.com/a/40210 |
| Ethiraric    | Brainfuck   | 108              | yes     |          |                | https://codegolf.stackexchange.com/a/40156 |                                           |
| Qwertiy      | JavaScript  | 420              | yes     |          |                | https://codegolf.stackexchange.com/a/40161 |                                           |
| user23013    | Befunge     | 360              | yes     |          |                | https://codegolf.stackexchange.com/a/40163 |                                           |
| user23013    | CJam        | 80               | yes     |          |                | https://codegolf.stackexchange.com/a/40171 |                                           |
| Geobits      | Java        | 360              | yes     |          |                | https://codegolf.stackexchange.com/a/40180 |                                           |
| Dennis       | CJam        | 60               | yes     |          |                | https://codegolf.stackexchange.com/a/40184 |                                           |
| xnor         | Python 3    | 160              | yes     |          |                | https://codegolf.stackexchange.com/a/40192 |                                           |
| COTO         | C           | 72               | yes     |          |                | https://codegolf.stackexchange.com/a/40198 |                                           |
| es1024       | C           | 780              | yes     |          |                | https://codegolf.stackexchange.com/a/40202 |                                           |
| Gerli        | Mathematica | 72               | no      | yes      | Martin Büttner | https://codegolf.stackexchange.com/a/40230 | https://codegolf.stackexchange.com/a/40242 |
| Hydrothermal | JavaScript  | 80               | yes     |          |                | https://codegolf.stackexchange.com/a/40235 |                                           |
| Sam Yonnou   | GolfScript  | 48 (frontrunner) | yes     |          |                | https://codegolf.stackexchange.com/a/40239 |                                           |
| feersum      | Matlab      | 48               |         |          |                | https://codegolf.stackexchange.com/a/40310 |                                           |
| Beta Decay   | Python 3    | 484              |         |          |                | https://codegolf.stackexchange.com/a/40312 |                                           |
| potato       | Python 3    | 176              |         |          |                | https://codegolf.stackexchange.com/a/40341 |                                           |
+--------------+-------------+------------------+---------+----------+----------------+-------------------------------------------+-------------------------------------------+

```

<sup>(Thanks to http://www.sensefulsolutions.com/2010/10/format-text-as-table.html for table formatting.)</sup>

User COTO made an excellent tool for playing with code-bricks. I've turned it into a convenient snippet:

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>function parseSpec(s){function first(){var e,t;t=S.findIndex(function(t){return(e=t.findIndex(function(e){return/\S/.test(e)}))!=-1});return t==-1?null:[e,t]}function at(e){var t=e[0],n=e[1];return n>=0&&n<S.length&&t>=0&&t<S[n].length?S[n][t]:" "}function wipe(e){var t=e[0],n=e[1];if(n>=0&&n<S.length&&t>=0&&t<S[n].length)S[n][t]=" "}var P,S=s.split("\n").map(function(e){return e.split("")});var oPats=$(".proto-tet [pat]").get().map(function(e){return{sPat:eval("["+$(e).attr("pat")+"]"),e:e,block:function(e){return[at(e)].concat(this.sPat.map(function(t){return at([e[0]+t[0],e[1]+t[1]])}))},wipe:function(e){this.sPat.forEach(function(e){return wipe([P[0]+e[0],P[1]+e[1]])})},match:function(e){return!/\s/.test(this.block(e).join(""))}}});window.oPats=oPats;while(P=first()){var oPat=oPats.find(function(e){return e.match(P)});if(!oPat){orphan(at(P));wipe(P);continue}createPiece(oPat.e,oPat.block(P));wipe(P);oPat.wipe(P)}}function createPiece(e,t){function r(e){var t=$(this).position();G.isIgnoreClick=false;G.eDrag=this;G.iOffsets=[e.clientX-t.left,e.clientY-t.top]}function i(){if(G.isIgnoreClick)return;var e=$(this);s($(".proto-tet ."+e.attr("rr")),function(e,t){return n[t-1]},e.css("left"),e.css("top"));e.remove()}function s(e,t,n,s){e.clone().html(e.html().replace(/@(\d)(\d)/g,t)).appendTo("body").on("mousedown",r).click(i).css({left:n,top:s})}var n=[];s($(e),function(e,r,i){return n[r-1]=t[i-1]},18+G.iSpawn%8*18*4+"px",18+~~(G.iSpawn/8)*18*4+"px");G.iSpawn++}function init(){$(document).on("mouseup",function(){return G.eDrag=null}).on("mousemove",function(e){if(G.eDrag){var t=$(G.eDrag),n=Math.round((e.clientX-G.iOffsets[0])/18)*18,r=Math.round((e.clientY-G.iOffsets[1])/18)*18,i=t.position();if(n!=i.left||r!=i.top)G.isIgnoreClick=true;t.css({left:n+"px",top:r+"px"})}})}function orphan(e){error("Spec character not a part of any block: '"+e+"'")}function error(e){$(".error").css("display","block").append("<div>"+e+"</div>")}function go(){$(init);$(function(){parseSpec($("#spec").val())});$("#spec").remove();$("#info").remove();$("#go").remove()}var G={eDrag:null,isIgnoreClick:true,iSpawn:0};Array.prototype.findIndex=function(e){for(var t=0;t<this.length;t++){if(e(this[t]))return t}return-1};Array.prototype.find=function(e){var t=this.findIndex(e);if(t==-1)return;else return this[t]}</script><style>.proto-tet, .spec{display: none;}.tet-I{color: darkgreen;}.tet-J{color: orangered;}.tet-L{color: navy;}.tet-T{color: darkred;}.tet-O{color: darkcyan;}.tet-S{color: darkviolet;}.tet-Z{color: darkorange;}body > .tet{position: absolute;cursor: move;-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;border-collapse: collapse;}.tet td{width: 18px;height: 18px;font: bold 14px "Courier New",monospace;text-align: center;vertical-align: middle;padding: 0;}.error{z-index: 1024;position: absolute;display: none;color: red;font-weight: bold;background-color: white;}textarea{font-family: "Courier New", Courier, monospace;}</style><div id='info'>Put code-bricks here and hit OK. Re-run the snippet to restart.<br>(You may need to replace spaces in code-bricks with some other character first.)</div><textarea id='spec' rows='16' cols='80'>ABCD  a
      b   Oo
      c   oo
      d

 E    h
 F  efg   hg   GFE
 GH        f   H
           e

 I           IJK
 J   l         L
LK   kji  kl
          j
          i
                   t
 OP   p     QR    rs
MN    on     ST   q
       m
 W             z
 XY    zxw    yx     Y
 Z      y      w    WXZ</textarea><br><button id='go' type='button' onclick='go()'>OK</button><div class="proto-tet"><table class="tet tet-I tet-I0" rr="tet-I1" pat="[1,0],[2,0],[3,0]"><tr><td>@11</td><td>@22</td><td>@33</td><td>@44</td></tr></table><table class="tet tet-I tet-I1" rr="tet-I2" pat="[0,1],[0,2],[0,3]"><tr><td>@11</td></tr><tr><td>@22</td></tr><tr><td>@33</td></tr><tr><td>@44</td></tr></table><table class="tet tet-I tet-I2" rr="tet-I3" ><tr><td>@40</td><td>@30</td><td>@20</td><td>@10</td></tr></table><table class="tet tet-I tet-I3" rr="tet-I0"><tr><td>@40</td></tr><tr><td>@30</td></tr><tr><td>@20</td></tr><tr><td>@10</td></tr></table><table class="tet tet-J tet-J0" rr="tet-J1" pat="[0,1],[-1,2],[0,2]"><tr><td></td><td>@11</td></tr><tr><td></td><td>@22</td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-J tet-J1" rr="tet-J2" pat="[0,1],[1,1],[2,1]"><tr><td>@31</td><td></td><td></td></tr><tr><td>@42</td><td>@23</td><td>@14</td></tr></table><table class="tet tet-J tet-J2" rr="tet-J3" pat="[1,0],[0,1],[0,2]"><tr><td>@41</td><td>@32</td></tr><tr><td>@23</td><td></td></tr><tr><td>@14</td><td></td></tr></table><table class="tet tet-J tet-J3" rr="tet-J0" pat="[1,0],[2,0],[2,1]"><tr><td>@11</td><td>@22</td><td>@43</td></tr><tr><td></td><td></td><td>@34</td></tr></table><table class="tet tet-O tet-O0" rr="tet-O1" pat="[1,0],[0,1],[1,1]"><tr><td>@11</td><td>@22</td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-O tet-O1" rr="tet-O2"><tr><td>@30</td><td>@10</td></tr><tr><td>@40</td><td>@20</td></tr></table><table class="tet tet-O tet-O2" rr="tet-O3"><tr><td>@40</td><td>@30</td></tr><tr><td>@20</td><td>@10</td></tr></table><table class="tet tet-O tet-O3" rr="tet-O0"><tr><td>@20</td><td>@40</td></tr><tr><td>@10</td><td>@30</td></tr></table><table class="tet tet-L tet-L0" rr="tet-L1" pat="[0,1],[0,2],[1,2]"><tr><td>@11</td><td></td></tr><tr><td>@22</td><td></td></tr><tr><td>@33</td><td>@44</td></tr></table><table class="tet tet-L tet-L1" rr="tet-L2" pat="[1,0],[2,0],[0,1]"><tr><td>@31</td><td>@22</td><td>@13</td></tr><tr><td>@44</td><td></td><td></td></tr></table><table class="tet tet-L tet-L2" rr="tet-L3" pat="[1,0],[1,1],[1,2]"><tr><td>@41</td><td>@32</td></tr><tr><td></td><td>@23</td></tr><tr><td></td><td>@14</td></tr></table><table class="tet tet-L tet-L3" rr="tet-L0" pat="[-2,1],[-1,1],[0,1]"><tr><td></td><td></td><td>@41</td></tr><tr><td>@12</td><td>@23</td><td>@34</td></tr></table><table class="tet tet-S tet-S0" rr="tet-S1" pat="[1,0],[-1,1],[0,1]"><tr><td></td><td>@21</td><td>@12</td></tr><tr><td>@43</td><td>@34</td><td></td></tr></table><table class="tet tet-S tet-S1" rr="tet-S2" pat="[0,1],[1,1],[1,2]"><tr><td>@41</td><td></td></tr><tr><td>@32</td><td>@23</td></tr><tr><td></td><td>@14</td></tr></table><table class="tet tet-S tet-S2" rr="tet-S3"><tr><td></td><td>@30</td><td>@40</td></tr><tr><td>@10</td><td>@20</td><td></td></tr></table><table class="tet tet-S tet-S3" rr="tet-S0"><tr><td>@10</td><td></td></tr><tr><td>@20</td><td>@30</td></tr><tr><td></td><td>@40</td></tr></table><table class="tet tet-Z tet-Z0" rr="tet-Z1" pat="[1,0],[1,1],[2,1]"><tr><td>@11</td><td>@22</td><td></td></tr><tr><td></td><td>@33</td><td>@44</td></tr></table><table class="tet tet-Z tet-Z1" rr="tet-Z2" pat="[-1,1],[0,1],[-1,2]"><tr><td></td><td>@11</td></tr><tr><td>@32</td><td>@23</td></tr><tr><td>@44</td><td></td></tr></table><table class="tet tet-Z tet-Z2" rr="tet-Z3"><tr><td>@40</td><td>@30</td><td></td></tr><tr><td></td><td>@20</td><td>@10</td></tr></table><table class="tet tet-Z tet-Z3" rr="tet-Z0"><tr><td></td><td>@40</td></tr><tr><td>@20</td><td>@30</td></tr><tr><td>@10</td><td></td></tr></table><table class="tet tet-T tet-T0" rr="tet-T1" pat="[1,0],[2,0],[1,1]"><tr><td>@11</td><td>@22</td><td>@33</td></tr><tr><td></td><td>@44</td><td></td></tr></table><table class="tet tet-T tet-T1" rr="tet-T2" pat="[-1,1],[0,1],[0,2]"><tr><td></td><td>@11</td></tr><tr><td>@42</td><td>@23</td></tr><tr><td></td><td>@34</td></tr></table><table class="tet tet-T tet-T2" rr="tet-T3" pat="[-1,1],[0,1],[1,1]"><tr><td></td><td>@41</td><td></td></tr><tr><td>@32</td><td>@23</td><td>@14</td></tr></table><table class="tet tet-T tet-T3" rr="tet-T0" pat="[0,1],[1,1],[0,2]"><tr><td>@31</td><td></td></tr><tr><td>@22</td><td>@43</td></tr><tr><td>@14</td><td></td></tr></table></div><div class="error"></div>
```

# Answer
> 3 votes
# GolfScript 48

`I` pieces:

```
!;..  )+?;

```

`O` pieces:

```
.[  ;*  .(
):  ++  -\

```

`T` pieces:

```
+]\  +++  ;).  );.
 .    *    ,    )

```

`J` pieces:

```
.    )    *
(@@  :?,  .,:

```

### Solution

> `.[!)):,.`
> `):;+:?,*`
> `;*.?;).+`
> `++.;),*+`
> `.(..;).+`
> `-\(@@\]+`

# Answer
> 23 votes
# Java : 360 area

> # Bounty: 500
>
> Reconstructing these things is hard! That's probably why there aren't too many robbers participating in this challenge. However, I *want* to see mine cracked. So, instead of giving the solution after 72 hours, **I'm putting up 500 rep to the first successful cracker.** To clarify, I will add a +500 bounty to the answer post and award it to your crack if you reassemble these pieces into any working, rectangular Java program that outputs "Tetris". I am not preemptively activating the bounty, because I don't feel like wasting rep if nobody answers.
>
> There is no end date to this offer. It's valid as long as I'm a member here. To ensure I see your answer, ping me with a comment below.
>
> I've triple-checked to make sure the pieces (and code) are valid, but if a trusted user wants to confirm this, I can email/something the solution to them. Obviously, that would exempt them from posting it and collecting the bounty.

Made of a mix of all seven piece types. To make things easier(?) I've made sure that all pieces of the same type are rotated to the same orientation. Since Java has parts that can't be changed much, I've left the *really* obvious parts as simple I-blocks to get it started.

**Note:** Since Java has a few mandatory spaces, I've replaced them with underscores (`_`)below for layout purposes. There are 11 of them total, and they should all be converted to spaces to run the code. No other whitespace is present in the code, any below is just for positioning.

There are:

* 41 I
* 15 O
* 11 J
* 8 L
* 6 T
* 6 S
* 3 Z

**Have fun!**

```
------------- I

clas    s_X{    publ    ic_s

tati    c_vo    id_m    ain(

Stri    ng[]    2;c*    p(b-

(b-c    _voi    nt_a    Syst

em.o    ut.p    rint    1,c=

d=1,    e=3,    new_    int[

;b++    for(    1008    ?1:2

)a);    ccc+    ==++    pf}(

for(    (b);    p(b+    --b-

or(d    1?1:    +1;e    for(

=1);

------------- O

a)
*2

b=
r(

12
<3

36
[c

*1
++

b<
6]

64
64

7]
]-

<1
1;

89
0;

;p
c)

=0
ic

st
ch

at
ar

d/
1;

-------------- T

{in
 ]

+b(
 5

d/2
 ;

d<<
 )

;;;
 1

=1)
 (

------------- L

2=[
+

]b*
8

=1)
]

<<b
<

}_}
d

3=b
)

+[[
=

=c,
=

-------------- J

o
;b=

,
2;)

f
2;c

*
=][

c
f=d

+
e1+

e
=;;

d
_p(

i
<++

=
){_

[
f+e

---------------- S

 t_
;f

 c+
1)

 +<
;p

 64
<6

 b=
;p

 ))
(;

--------------- Z

4,
 -1

;=
 ff

;f
 0;

```

# Answer
> 12 votes
# Brainfuck, 108 area

This code was made of 27 I pieces.

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

```

I don't know if there is any way other than bruteforce to find the answer. If there is, i'd really like to know how.

# Answer
> 9 votes
## Python 3: 212 area \[Rebuilt\]

My code is broken up into the following 53 `I`-pieces, which I've written one per line alphabetically.

```
(358
0048
0396
0796
0824
0981
1013
1314
1330
1438
1502
2285
2317
2479
2585
2955
3116
3738
3818
4169
4356
4360
4632
4800
5016
5153
5256
5394
5598
5631
5758
5840
6312
6425
6539
7045
7156
7163
7329
7624
7674
8164
8250
8903
9%38
9009
94))
9413
9748
etri
prin
s'*
t('T

```

Have fun!

# Answer
> 5 votes
## Javascript, area 420

Only I-blocks.

```
!!!(
!!!+
!!!+
!!![
!!!]
!!!]
!!!]
!!!]
!!!]
!!'!
!![]
!!]]
!(!+
!(![
!+!]
!+!]
!+"+
!++)
!++[
!++[
!++[
!++[
!++]
![+[
!](+
(!!'
(!!+
(!(]
(++!
(['[
)!'!
)[)[
)]]!
+++"
+++)
++++
+++[
+++]
++])
+[+[
+[[[
+]'+
+]']
+]+[
+]+[
+]]!
+]]!
+]]!
+]]!
+]]'
+]][
+]]]
[!!+
[!!+
[!!+
[!!+
[!!+
[!!]
[!+!
[![[
[![[
[((!
[))!
[){!
[+'+
[++)
[++]
[[)+
[[+[
[[[!
[[['
[[[+
[][]
[]]]
[{[[
]!(!
]!]+
]['[
][[!
][[!
][[!
][[!
][[(
][[+
][[+
][[[
][[[
][]]
][}!
]]T]
]][(
]]]!
]]]!
]]]'
]]])
]]]]
]}]]
a['!
e]'(
l++[
v).!
{[[[
{]g]
})')
}]]]
```

No any standard obfuscators were used. All code including obfuscation and making this sorted list of blocks is made by less then 16 lines of my own code.

---

It's time to show how it was made:

```
x="+[],+!![],+!![]+!![],+!![]+!![]+!![],+!![]+!![]+!![]+!![],+!![]+!![]+!![]+!![]+!![],+!![]+!![]+!![]+!![]+!![]+!![],+!![]+!![]+!![]+!![]+!![]+!![]+!![],+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![],+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]+!![]".split(/,/g)
res={}
for(q=0; q<x.length; ++q) res[eval(x[q])]=x[q]
function add(str) { for(q=0;q<Math.min(str.length,10);++q) res[eval(x=str+"["+res[q]+"]")]=x }
add("({}+[])")
add("(![]+[])")
add("(!![]+[])")
add("([][[]]+[])")
code = 'eval('+Array.prototype.map.call('console.log("Tetris")',function(x){return res[x]||"'"+x+"'"}).join("+")+')'
res=[]
console.log(code)
code.replace(/(.)(?=.{104}(.).{104}(.).{104}(.))/g,function(m,a,b,c,d){res.push(a+b+c+d)})
eval(res.map(function(x){return x[0]}).join("")+res.map(function(x){return x[1]}).join("")+res.map(function(x){return x[2]}).join("")+res.map(function(x){return x[3]}).join(""))
console.log(res.sort().join("\n"))

```

So, it's just call to `eval` with obfuscated `'console.log("Tetris")'` argument, which is 420 symbols in length. It is splitted into 4 lines of 105 symbols and read by columns and alphabetical sorted.

Obfuscation for 10 digits is hardcoded, for other symbols used first 10 symbols from 4 combinations passed to `add` function. If there is no obfuscation for some symbol it is passed as is.

# Answer
> 5 votes
# JavaScript - Area 80

Seems like a lot of these answers are just using lots of I pieces and maybe an O piece or two, so I threw this together with some of the more interesting shapes.

* 7 I pieces
* 1 L piece
* 1 J piece
* 4 O pieces
* 6 T pieces
* 1 S piece

Each piece is separated by two spaces. The two hash signs are actually spaces in the code.

```
l  n  \  /  ;  +  r
o  -  x  c  v  (  i
g  (  5  o  a  ;  s    )  o    //  #c  ns  ->   )    "    d    l    e    l    wi
(  "  4  n  r  ;  "  x65  log  ;/  ")  ].  "c  "(#  o+\  ave  ow"  t"o  "Te  ["

```

Have fun!

# Answer
> 4 votes
# C, 80 area

Made of 12 `I` pieces and 8 `O` pieces. C syntax is always fun.

`I` pieces in no particular order:

```
 c[] // starts with a space
','n
',;}
(q){
,',  // ends in a space
u>6/
T2sr
char
main
q/**
t#1'
ts(c

```

`O` pieces:

```
q<
pu

't
i'

Ir
$'

/}
);

'?
re

',
`:

"e
i>

={
,0

```

# Answer
> 4 votes
# Befunge, 360 area

90 `O`-pieces.

```
 "
#6

 "
#^

 #
#

 #
4

 +
$

 +
0>

 +
v_

 0
>

 3
#

 >
\

 ^
/1

 _
v8

 v
$,

 ~
*=

!!
00

!<
v>

"!
<

"<
#^

">
^<

"v
#

"v
w\

#
 #

#
|_

#*
_*

#0
.@

#3
~#

#?
t@

#^
RI

#v
~>

#~
~#

$
!4

&v
v#

*#
"#

**
>^

+1
>^

+5
 ,

+^
S"

-
#"

-#
2\

-~
 #

0
|>

00
00

0<
v\

2,
+#

2v
^v

3#
<

3#
>2

3~
^-

47
31

6
6#

70
"T

8#
:\

:#
 #

:$
$*

:0
3<

<
#$

<*
<|

<<
>>

<>
<>

<@
 >

<~
2,

>
7<

>$
^6

>>
<<

>v
|g

\
^

\_
 !

^
<s

_!
>9

_$
ET

kr
 >

m~
#3

q~
~+

r^
c

t~
,

v
 ?

v/
_$

v4
>>

v7
>#

v<
>#

v<
>#

v>
:^

v~
1/

zr
 $

~#
#~

~#
\#

~$
7>

~3
$_

~v
\$

~~
~#

```

You can try it here.

> ```
> 3#~#~vm~00-~q~\_:$:#r^&v_!!<v<
> >2\#\$#300 #~+ !$* #c v#>9v>>#
> "v0< 36 v < ~~ ^<~^ <<<@\ -##v
> w\v\# 6# ?#$~#/12,<s>> >^ 2\~>
> "> +>$ +:0 _ #2,v/$ >>v4v7- 3~
> ^<0>^6v_3<v84 +#_$!4<<>>>##"^-
> <*8#> #0 v ~v~2v#~~#kr"v "zr"<
> <|:\7<.@$,*=1/^v~##~ ># #6 $#^
> #*+1# 3# 0470 >vv< ## ~$t~ "<>
> _*>^|_< > 31|>|g>##  #7>, #^<>
> 70_$#^+^~3 +** >v>!!+5#3*#"!#?
> "TETRIS"$_$ >^\ :^00 ,~#"#< t@
> ```
>
> There are probably other solutions. I didn't rotate the bricks.

# Answer
> 4 votes
# CJam, 60 (15 O's)

```
71 05 37 23 36 04 27 69 32 :i 12 93 bi i] 43
69 44 71 71 -# 70 10 25 44 cb 93 20 *G 9B 62

```

### Solution

> `27`
> `10`
> `96`
> `17`
> `54`
> `04`
> `52`
> `96`
> `71`
> `37`
> `12`
> `93`
> `43`
> `62`
> `29`
> `03`
> `07`
> `40`
> `44`
> `23`
> `72`
> `13`
> `]B`
> `i9`
> `*b`
> `Gi`
> `6#`
> `3-`
> `ib`
> `:c`

# Answer
> 3 votes
## Python 3: 340 area \[Rebuilt\]

Made of 85 `I`-pieces, given here alphabetized one per line.

```
    #Four spaces
    #Four spaces
    #Four spaces
    #Four spaces
    #Four spaces
    #Four spaces
    #Four spaces
    #Four spaces
    #Four spaces
))  #Two spaces
0290
0398
0866
0887
0892
0992
1108
1268
1297
1339
1555
1722
1817
1848
1930
2328
2521
2611
2747
3179
3192
3245
3284
3334
3613
3862
4086
4629
4639
4674
4695
4781
4968
5723
5742
5791
5938
6011
6069
6180
6231
6265
6269
6444
6564
6776
6884
7116
7253
7348
7440
7527
7743
7873
8064
8291
8808
8843
9305
9324
9458
9460
9586
9869
====
a,b,
abcd
c)-d
etri
pow(
prin
s'*(
t('T

```

As a Python list:

```
['    ', '    ', '    ', '    ', '    ', '    ', '    ', '    ', '    ', '    ', '    ', '))  ', '0290', '0398', '0866', '0887', '0892', '0992', '1108', '1268', '1297', '1339', '1555', '1722', '1817', '1848', '1930', '2328', '2521', '2611', '2747', '3179', '3192', '3245', '3284', '3334', '3613', '3862', '4086', '4629', '4639', '4674', '4695', '4781', '4968', '5723', '5742', '5791', '5938', '6011', '6069', '6180', '6231', '6265', '6269', '6444', '6564', '6776', '6884', '7116', '7253', '7348', '7440', '7527', '7743', '7873', '8064', '8291', '8808', '8843', '9305', '9324', '9458', '9460', '9586', '9869', '====', 'a,b,', 'abcd', 'c)-d', 'etri', 'pow(', 'prin', "s'*(", "t('T"]

```

# Answer
> 3 votes
## Python 3: 160 area

After feersum's crack, I tried to tighten up my code to make it harder to avoid cryptographic mumbo-jumbo. It's made of 40 `I` pieces, listed one per row:

```
')    #Two spaces
)-d)
*'Te
,b,c
0484
0824
2448
2562
3094
3762
3896
4052
4233
4562
5266
5277
5400
5885
5927
5965
6080
6720
6808
6884
7568
7856
7963
8609
8639
8665
8732
8892
9206
9893
====
abcd
ow(a
prin
t((p
tris

```

As a Python list:

```
["')  ", ')-d)', "*'Te", ',b,c', '0484', '0824', '2448', '2562', '3094', '3762', '3896', '4052', '4233', '4562', '5266', '5277', '5400', '5885', '5927', '5965', '6080', '6720', '6808', '6884', '7568', '7856', '7963', '8609', '8639', '8665', '8732', '8892', '9206', '9893', '====', 'abcd', 'ow(a', 'prin', 't((p', 'tris']

```

Changed:

* Reordered string multiplication to try to force `pow` to be used
* Fewer spaces (though shorter numbers)
* No `1`'s

I am worried about the many factors of the area though.

# Answer
> 2 votes
# CJam, 80 area

20 `O`-pieces.

```
 I
`7

&d
'X

+5
7m

-2
`-

-6
#b

-O
U[

3Z
Pi

4"
2X

43
P"

?<
5b

D:
.=

FH
uL

K`
~C

QT
:c

[^
+9

aj
^F

hD
dP

tn
6

uq
KG

x6
CF

```

> `-24"hD&d ID:uqx6tn-OajFH43[^+5?<3ZK`-6QT`
> ``-2XdP'X`7.=KGCF6 U[^FuLP"+97m5bPi~C#b:c`
> I didn't rotate the bricks.

# Answer
> 2 votes
# C - Area 72

**Blocks:**

```
I    J     _______ L ______       O      __ Z _     _______ T ______
          /                \   /    \   /      \   /                \
"    e    m   "   T   )   6    };  ii   3"   (.    \nn  {6"  ]"0  i%s
i    t    p   ,   &   m   1    -]  ar    "\   f(    t    8    e    T
s   )"    .[  0x  ,f  ai  0r
"

 ""   (t   ["
)"   61   4+
\____   ____/
      S

```

Since the only other C submission was cracked. ;)

A neat 72 characters. Pure obfuscation. No NP-hard problems to solve or huge integers to factor. Borrows some tricks from one of the greats. **Spaces are represented using `.`s. No actual `.`s appear in the solution.**

I've triple-checked the solution to ensure validity of the pieces.

# Answer
> 2 votes
# C - Area 780

There are 195 pieces in total. No comments were used. Nothing particularly complicated.

Note: all backslashes (`\`) are to be replaced with spaces.

95 `I` Pieces:

```
____ x12
incl
\edu
\\\\
\\\\
\\\\
dts<
h.oi
*_*>
_,_(
int\
__;\
,_(_
_*_,
=__,
__"*
+|_;
r__+
ahct
)=pu
_\ra
f\ch
edep
#t_,
y___
*_;_
(_;-
){__
,<_\
9"=_
+__*
___;
_+>_
_??<
+__*
*__,
__*_
*=+_
__:-
___-
_+__
,___
,__,
_,*&
*\&*
_,*_
_++,
+,__
++++
+__=
_++,
,,,_
___+
=+__
?++_
___+
=__+
,<_*
__+*
&+;*
+*__
__*_
__+,
++?~
__-9
_?__
__*_
(_+_
[**(
_<&_
};__
_@A:
(nia
@@@@
AAAA
AAAA
~~~~
_++;
_&,)
A__+
~~__
g_""
_;}_
+*__

```

35 `O` Pieces:

```
__
__
 (x18)
)_
__

_*
_\

_;
,-

_*
__

~)
"{

+_
+_

*_
,_

__
_)

~~
a~

_,
__

__
,)

_:
__

+*
__

__
+,

*+
_+

AA
AA

__
,+

```

18 `L` Pieces:

```
___
_
 (x2)
_;*
_
_=_
+
__*
_
+__
_
**_
&
+*_
_
&*&
,
++,
_
_*_
_
;;_
"
__+
_
AAA
~
"*)
;
___
(
,_-
_
_~^
_

```

25 `J` Pieces:

```
_+=
  +
+,_
  _
*__
  ;
;;_
  \
_,_
  )
~~~
  _
___
  A
~;(
  _
;__
  i
_;m
  A
=__
  _
a;a
  A
="A
  a
~_\
  o
o_a
  a
~~~
  _
99-
  _
*9_
  _
__)
  _
__*
  <
+_,
  _
_++
  =
_+_
  _
++_
  _
_+:
  _

```

10 `T` Pieces:

```
 _
,__
 +
*?_
 =
**=
 _
__+
 _
:_+
 _
_+_
 _
(_-
 +
++,
 +
___
 *
__:

```

4 `Z` Pieces:

```
=*
 ++
*+
 __
t_
 -~
__
 f(

```

8 `S` Pieces:

```
 _,
_,
 __
__
 (x2)
 -_
__
 (x2)
 _9
~_
 99
__
 __
],

```

### Solution

> `#include <stdio.h>
> typedef char _________; int (*
> _____)()=putchar;____(_,___,__
> ,______) _________*__,* *___,*
> ______;{__="9>?_|";______=*___
> ;--_;--_<*__++?++*______,_+=_+
> _:___,__,___;_<*__++?*______+=
> *______,++______,__,*______+=*
> ______,__,++______,*&*______+=
> *______,++______,* &*______+=*
> ______,++______,*&*&*______+=*
> ______,++______,_,*______+=*&*
> ______,_+=_+_:__,_;_<*__++?++*
> ______++,++*______++,++*______
> ++,++*______++,++*&*______++,_
> ,++*______,_+=_+_+_+_:______;_
> <*__++?~_____(_-_+_-_)^~_____(
> *______),++*___,_____,_,_+=*&*
> ______,_+_:_____(_+_-_-_);;_<*
> __?--*______:___;}_________ _[
> 999-99-99],*__=_;main(______){
> _________*___="AAA@@@@@~~~~~~"
> "~~~~~~aAAAAAaAAAAAAAAAAAAA;;"
> "aa~~~~~~~~~a;a";_____:____((*
> ___-______),&__);if(__,*++___)
> goto _____;++______;++______;}`

# Answer
> 1 votes
# Wolfram, area 72

Everywhere you see a dash (-), replace it with a space

## i

```
h01-

r*1/

```

## j

```
6
115

```

## l

```
  m
+1C

  t
*0e

  e
,,[

```

## o

```
r4
a+

```

## s

```
 10
-1

 +1
Pr

```

## z

```
ro
 8*

ac
 -1

od
 +1

```

## t

```
--F
 {

,50
 0

/]}  -- fixed bracket directions
 0

1-,
 ,

01C
 0

tni
 4

```

# Answer
> 0 votes
# MATLAB, area 48

Unfortunately, it does not seem to work in Octave.

```
-
^-1

'
'u"

v'+
e

[['
;

'.i
]

lmi
a

 kv
hW

 .x
).

3)
t;

b(
'p

('l;

.]'e

```

# Answer
> 0 votes
# Python 3

## Area - 484

Spaces replaced by `%`. There are some comments used as padding. Quite a bit of repetition of code. May be quite complicated.

### 121 Os

```
41
)+

%r
1-

:#
1#

%r
1-

01
,+

a1
n+

))
0+

h1
r-

#0
##

--
ge

11
1-

hr
1-

--
-1

ap
0+

+1
+'

h0
r+

:1
##

11
1-

))
0+

a0
p+

n0
d+

f%
oz

-1
0+

hr
1-

n0
d+

a0
p+

a1
n+

+0
1+

hf
.=

i1
%-

f%
oa

a1
n+

(c
0+

(0
1+

0,
1+

i1
n+

in
1+

r+
%=

-0
1+

fo
%l

n'
d'

--
=1

p1
%-

-;
-a

-;
-h

a1
n+

pe
0+

pe
0+

-1
0+

n0
d+

11
0-

a0
p+

i1
n+

hz
.=

n0
d+

##
)#

5)
1+

g(
1-

%1
r-

(c
.j

(0
c+

11
0-

(z
n(

g(
1-

41
)+

)s
)'

in
1+

r+
%=

ap
in

g(
1-

01
,+

-a
-n

(l
1+

pt
e(

%1
r-

-#
]#

(1
f+

g1
(-

h.
l=

01
,+

h.
pr

:1
##

:#
1#

(1
z+

r+
%=

+1
0+

p0
e+

r%
+=

(a
0+

hz
.=

+0
1+

(0
c+

))
0+

#0
##

q%
1-

g1
e-

-0
1+

#0
##

pe
0+

-1
h)

61
)+

an
1+

--
ng

fo
%f

)0
)+

f%
oz

-=
-[

11
)+

q1
%-

:#
1#

+0
1+

--
=r

j1
%-

ho
ri

#-
ra

(0
c+

i1
n+

,1
8-

r+
%=

%1
r-

##
0#

```

# Answer
> 0 votes
# Python 3 176 Area

I don't use underscores in this program, so I decided to replace all spaces with underscores for added readablity. Make sure to replace them back to spaces when failing to put it back together.

## I Blocks:

```
1456

"jtr

\)\~

tris

],i)

t=""

2697

t(t[

_r+2

_r_i

```

## O Blocks:

```
i_
s_

_;
32

6#
an

".
+-

t)
in

n(
_[

""
(c

ap
ri

```

## L Blocks:

```
  =
#14

  .
\n"

  ;
"(t

  i
T%"

  o
:=i

  r
ioj

  6
mp#

```

## J Blocks:

```
6
2(h

5
574

#
"=t

7
spl

f
o__

s
(s_

n
];#

0
t=_

*
#)(

```

## T Blocks:

```
=_1
 _

295
 r

21,
 r

,2)
 .

```

## Z Blocks:

```
46
 ""

"5
 3"

#t
 )n

1t
 ),

```

## S Blocks:

```
 ge
34

 nt
68

```

---
Tags: printable-ascii, source-layout, cops-and-robbers, tetris
---


# Question
Title: Smallest number you can get by adding up numbers in sequence
You a sequence of numbers like this one given to you as a string:

"**1 2 3 4 8 11 19 33 59 154 196 260**"

Create a program (any language) that calculates the smallest outcome you **can't** get by adding two of those numbers together.

The numbers given must be integers, and are always positive.

You can only use each number once.

The answer must be \> 0 and a whole number. The given string must contain at least a 1.

Examples of invalid outcomes:

"**1 2 3 4 8 11 19 33 59 154 196 260**"

* 3 *(1 + 2)*
* 54 *(19 + 33 + 8 + 2)*

Example of valid outcome:

"**1 2 7 34 34 78**"

* 4 *(1 + 2 = 3, can't get 4 by adding any numbers.)*

The shortest answer wins, answers can be submitted until october 30th, 18:00 CET.

# Answer
# Python - ~~104~~ 99

My interpretation:

```
L=map(int,input().split())
k=1
while k in map(sum,[[i,j]for i in L for j in L if i<j]):k+=1
print k

```

I tested it with the input string `0 1 2 3 4 8 11 19 33 59 154 196 260` containing a 0 to avoid the trivial solution 0.

Result:

```
16

```
> 2 votes

---
Tags: code-golf
---


title: Reassuring parables

text:
# Question
Title: Reassuring parables
Quite a few people here are probably avid XKCD readers. So, I figure I'd challenge you guys to do something that Megan can do easily: make a script that generates thousands of reassuring parables about what computers can never do.

Your script

* Can be written in any language
* Must be code-golfed
* Must take an input (on `stdin` or your language equivalent) on the number of parables it will spit out (you can assume this will not exceed `MAX_INT` or equivalent).
* Will output a number of **randomly** generated parables.

The parables are as follows

* Starts with `'Computers will never '`
* Next, one of 16 unique English verbs which you can choose freely to optimize your program, but *must* include `code-golf` and `understand`.
* Next, one of 16 unique English nouns which again, you can choose freely to optimize your program, but *must* include `a salad` and `an octopus`.
* Next, one of 16 unique English clauses which you can choose freely to optimize your program, but *must* include `for fun` and `after lunch`.
* Ends with a newline (`\n` or equivalent) character

So, for example, if the input is `2`, a valid output would be

```
Computers will never code-golf a salad for lunch
Computers will never hug a tree in vain

```

Program size is counted in bytes, not characters (so no unicode gibberish). Standard loopholes are not allowed.

This is my first challenge, so if I should make some obvious changes, please comment.

**Edit:** I am contemplating to substract the dictionary size from the byte count, to encourage dictionary 'compression'. I will see from future answers if this is remotely feasible ; if it is, you can count on a bonus.

# Answer
## CJam, ~~238~~ 232 (or 209) bytes

```
ri{'C"!fmQ$h/q6fW*LC*hBd11(kA>.TfqJ0++#<>A]XThJkY b~os;vMg_D-}zYX%_,PozNxe5_8`}$H;2IUZ]&$c+m~HJ*|!n\A^:W-*O\"V-/8Kg ,_b(N#M/1Zh6*%\#t22'#|\"BJN=Za2_.R"32f-96b28b" -"'{,W%+f=)/(\[G/~["for ""after "]\m*\(a\"a "f{\+}+\]{mr0=}%S*N}*

```

This uses many verbs/nouns/clauses from already posted answers but some are new too. I have base converted the characters to shave off some extra bytes.

The base converted string can be golfed 24 more bytes (to get a 209 byte solution; Note that you have to consider the character count instead of byte count as all characters have an ASCII code of less than 255 but the site still consider some has unicode) but I wanted the string to consist only printable ASCII characters.

Just for reference, here is the 209 bytes version:

```
ri{'C"9óßÂ/ÃC eG?dcÅoø£gaC#Yä©Ï¡áq¶hm)ðaâ%ØNo=óÏrbÁz´¾;q·u¬&ñ*±äô©@6W±U¹¥¢)Â·«Åx¶óV¬¬dhja¼ ª\"r[çË74ÄãÐ³î,ó3gÈ$AïL"32f-222b28b" -"'{,W%+f=)/(\[G/~["for ""after "]\m*\(a\"a "f{\+}+\]{mr0=}%S*N}*

```

Takes the number of lines to print from STDIN like:

```
12

```

Output:

```
Computers will never code-golf an octopus for fun
Computers will never code-golf a bag after za
Computers will never eat a hem after tip
Computers will never eat an octopus for tip
Computers will never get a fax for you
Computers will never dry a gym for za
Computers will never get a guy for tip
Computers will never do a pen for fun
Computers will never see a bar after you
Computers will never tax a pen for ex
Computers will never get a hem for lunch
Computers will never win a pen for ex

```

Try it online here
> 6 votes

# Answer
Here's a slightly different approach:

# Python, 368 308 297 bytes

EDIT, I actually golfed it this time. Shaved off 60 characters.

```
from random import*
from en import*
C=choice
v=["code-golf","understand","go","do"]
n=["salad","octopus","fun","lunch"]
for f,l in("verbs",v),("nouns",n):exec"l.append(str(C(wordnet.all_"+f+"()))[:-4]);"*12
exec'print"Computers will never",C(v),noun.article(C(n)),C(("for","after")),C(n);'*input()

```

Here is the golf-trick that I'm most proud of:

```
for f,l in("all_verbs",v),("all_nouns",n):

```

I didn't even know python could do that! Here's a simpler explanation:

```
for (a, b) in ((0, 1), (1, 2), (2, 3)):

```

assigns a and b to 0 and 1, and then to 1 and 2, and then to 2 and 3.

---

This uses NodeBox's linguistics library to generate a list of verbs/nouns/clauses, and then randomly selects from them.

This library is not that great for generating random words (hence the 368 bytes), but the nice thing about this approach is you get some pretty random reassuring parables with it. Here is what I mean.

```
Computers will never attempt a syria for synchronization.
Computers will never understand a salad for change of mind.
Computers will never brim an electric company for synchronization.
Computers will never pivot a dusk for fun.
Computers will never bedaze an electric company for genus osmerus.
Computers will never brim a salad for vital principle.
Computers will never attempt an erythroxylum after lunch.
Computers will never understand an uuq for water birch.
Computers will never brim an ictiobus for change of mind.
Computers will never brim an ictiobus for 17.
Computers will never lie in an octopus for change of mind.
Computers will never happen upon a toothpowder for water birch.
Computers will never typeset an electric company for change of mind.
Computers will never brim a french oceania after lunch.
Computers will never bring out an ictiobus for glossodia.
Computers will never bedazzle an animal fancier for ash cake.
Computers will never attempt a dusk for genus osmerus.
Computers will never understand an animal fancier for genus osmerus.
Computers will never accredit a prickly pear cactus for 17.
Computers will never typeset an erythroxylum for water birch.

```

But hey, I don't think anybody else's program will generate the saying: "Computers will never bedazzle an animal fancier for ash cake."

Here's an ungolfed version (574 bytes):

```
import random
import en

v = ["code-golf", "understand"]#list of verbs
n = ["a salad", "an octopus"]#list of nouns
c = ["for fun", "after lunch"]#list of clauses
for i in range(14):
    v.append(str(random.choice(en.wordnet.all_verbs()))[:-4])
    n.append(en.noun.article(str(random.choice(en.wordnet.all_nouns()))[:-4]))
    c.append("for "+str(random.choice(en.wordnet.all_verbs()))[:-4])

N=input("Enter the number of reassuring phrases you want: ")
for i in range(N):
    print "Computers will never"+' '+random.choice(v)+' '+random.choice(n)+' '+random.choice(c )+'.'

```

And lastly but definitely not leastly, here are some of my favorite reassuring parables, that I predict will become really popular catch-phrases in the next 10-15 years.

```
Computers will never move around a methenamine for godwin austen.
Computers will never conk an adzuki bean for bitterwood tree.
Computers will never jaywalk a cross-dresser for fun.
Computers will never hyperbolize an accessory after the fact for norfolk island pine.
Computers will never dissolve a salad for earth wax.
Computers will never acetylise an incontrovertibility for dictatorship.
Computers will never reciprocate a strizostedion vitreum glaucum for commelinaceae.
Computers will never goose an action replay for star chamber.
Computers will never veto a bottom lurkers for jackboot.
Computers will never reciprocate a visual cortex for oleaginousness.
Computers will never baptise a special relativity after lunch.
Computers will never understand a gipsywort for citrus tangelo.
Computers will never get it a brand-name drug for electronic computer.
Computers will never deforest a paperboy after lunch.
Computers will never bundle up a nazi for repurchase.
Computers will never elapse a bernhard riemann for counterproposal.

```

and my personal favorite:

```
Computers will never romanticise a cockatoo parrot for cross-fertilization.

```
> 19 votes

# Answer
# JavaScript ES6, 331 336 bytes

```
n=prompt(a='')
r=s=>s+Math.random()*16>>0
p=q=>'OctopusSaladCutCueBatJamKidPenDogFanHemDotTaxSowDyeDigCode-golfUnderstandLunchFunMeYouUsItAdsPaZaMenTwoIceJamWarRumWax'.match(/[A-Z][^A-Z]+/g)[q].toLowerCase()
while(n-->0)y=r(0),z=r(18),a+=`Computers will never ${p(r(2))} a${y?'':'n'} ${p(y)} ${z<18?'afte':'fo'}r ${p(z)}
`
alert(a)

```

```
n=prompt()
a=''
function r(s){return s+Math.random()*16>>0}
function p(q){return' '+'OctopusSaladCutCueBatJamKidPenDogFanHemDotTaxSowDyeDigCode-golf\
UnderstandLunchFunMeYouUsItAds\
PaZaMenTwoIceJamWarRumWax'.match(/[A-Z][^A-Z]+/g)[q].toLowerCase()}
while(n-->0)
  y=r(0),z=r(18),
  a+='Computers will never'+p(r(2))+(y?' a':' an')+p(y)+(z<18?' after':' for')+p(z)+'\n'
alert(a)
```

I picked words that work as both verbs and nouns to shorten the list, but let me know if that is not allowed. Try it out above using Stack Snippets (The code there has been formatted to use ES5) or at http://jsfiddle.net/5eq4knp3/2/. Here is an example output:

```
Computers will never hem a cut for ads
Computers will never dot a pen after lunch
Computers will never code-golf a bat for free
Computers will never sow a dog for me
Computers will never cut an octopus for fun

```
> 6 votes

# Answer
# Python - ~~390 385~~ 383

```
from pylab import*
S=str.split
n=input()
while n:n-=1;i,j,k=randint(0,16,3);print"Computers will never",S("buy cut dry eat fax get pay rob see sue tax tow wax win code-golf understand")[i],"a"+"n"*(j<1),S("octopus salad bag bar bee bow boy bra dad fax gym guy hat man mom pet")[j],"for "*(k>2)+S("after lunch,naked,ever,fun,me,you,us,tip,gas,cash,air,oil,beer,love,food,dope",",")[k]

```

Random example output:

```
Computers will never pay an octopus for oil
Computers will never cut a bra for beer
Computers will never eat a bee for us
Computers will never rob a pet for you
Computers will never tax a pet for tip
Computers will never buy a salad for cash
Computers will never sue a boy naked
Computers will never see a bar for you
Computers will never wax a bra for beer
Computers will never sue an octopus for us

```
> 5 votes

# Answer
# Perl - 366

```
@w="Code-golfUnderstandBeDoTieSeeSawEatCutCapSitSetHateZapSipLoveSaladOctopusSeaBeeCatDogHatBatJobManLapCapRapMapDotAnt0fun1that1noon1work0good0sure0reason0nothing0you1you1lunch1all0me0nowToday1me"=~s/\d/("For ","After ")[$&]/reg=~/([A-Z][^A-Z]+)/g;print"Computers will never ".lc"$w[rand 16] a".$w[16+rand 16]=~s/^[AO]?/(n)[!$&]." $&"/re." $w[32+rand 16]
"for 1..<>

```

Here is a test:

```
$ perl ./parables.pl <<<3
Computers will never do an ant after noon
Computers will never do a lap after all
Computers will never love an octopus for sure

```
> 2 votes

# Answer
## CJam, ~~353~~ ~~317~~ 301 bytes

I'm using Falko's word list, for fairness, so that the only difference in golfing is due to the languages and not the content (I might change the word list if people start golfing the content as well).

```
"Computers will never ""buy
cut
dry
eat
fax
get
pay
rob
see
sue
tax
tow
wax
win
code-golf
understand"N/[" an octopus"" a ""salad
bag
bar
bee
bow
boy
bra
dad
fax
gym
guy
hat
man
mom
pet"{N/\f{\+}~]}:F~S["after lunch""naked""ever""for ""fun
me
you
us
tip
gas
cash
air
oil
beer
love
food
dope"Fm*m*m*mr0=

```
> 1 votes

# Answer
## NetLogo, 396

I also used Falko's word list, with two exceptions (which don't change the length of program).

```
to f let a["after lunch""ever""alone"]type(word"Computers will never "one-of["buy""cut""dry""eat""fax""get""pay""rob""see""sue""tax""tow""wax""win""code-golf""understand"]" a"one-of["n ocotpus"" salad"" bag"" bar"" bee"" bow"" boy"" bun"" dad"" fax"" gym"" guy"" hat"" man"" mom"" pet"]" "one-of fput word"for "one-of["fun""me""you""us""tip""gas""cash""air""oil""beer""love""food""dope"]a"\n")end

```

Depending on how you define "program", you can remove the first five and last three characters, thus a score of 388.
> 0 votes

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


title: Code Crosswords - Solutions

text:
# Question
Title: Code Crosswords - Solutions
This is the companion question for Code Crosswords. Robber answers go here.

See Where should we put robbers? for meta-info.

# Answer
# Solution to es1024's C puzzle

I had to fudge a bit on 7-Down by invoking undefined behavior. *es1024 has indicated that this use of UB was the intended solution.* It will work on most people's computers though. I came up with various expressions achieving the desired result such as `-1 << 30`, `3 << 30`, `6 << 29`, and `~(~0U/4)` but all of them made it impossible for me to get 5-Across. So I used the Intel architecture-specific property that only the least significant 5 bits are used to determine the size of a left shift. Note that it needs to be `~_` and not `~1` so that the amount to shift by is not a compile-time constant. I tested the expressions with the following code:

```
#define T(X) _ = c; _ = X; printf("%d\n", _);
z[4] = {9};
int main(c)
{
    int _;

    T("01"[0])
    T(-8)
    T(-2)
    T(11<-328111)
    T(+2+71)
    T(9+0)
    T(0**z)
    T(5;)
    T(0<-000)
    T(2+~3)
    T(!91)
    T(!_)
    T(2**z)
    T('_T;')

    T("11"?5*9:2)
    T(15<<9)
    T(0+22)
    T(-211*0-97;)
    T(-17*0)
    T(3+0<<~_)
    T(8+000)
    T(+0)
    T(42)
    T(+!z)
    T(~_)
}

```
> 8 votes

# Answer
## professorfish, CJam, 41 darks

*(This solution actually requires several spaces, so it's not the one professorfish was looking for.)*

```
#K###I#'32
#HDJ*s\ ##
2##2#`#`#-
4Zm*`##L#3
m##6##]`'
f####e#`#'
`#0#'d1+eu
## #!####9
## '{;'"'m
C5(#}####q

```

That was great fun. Note that the `#` beneath the `6` is actually code and not a dark cell. Let's go through this:

### Across

Hint 2: `[[4 3]]`. This was one of the trickier ones, because I really got stuck on trying `4Z]]`` or similar. Turns out you can use the Cartesian product `m*` on stuff that isn't an array, and it will make an array for you. So here it is:

```
4Zm*`

```

Hint 4: `24717`. By the time I got to this, the `H`, `J`, `s` and trailing space were already in place. The `H` gave away that I could probably just reuse the `17` and do `\` at the end. The `J` pushes a `19` and `247 == 13 * 19`, so:

```
HDJ*s\

```

Hint 7: `32`. There are a bunch of ways to do this: `Y5#`, `3 2`, `ZY`, `YZ\`, `4(2`, `2)2`, `'32`. I went with the last one, because starting with a character seemed promising for 7-down, and that turned out to be right.

Hint 8: `E`. I already had the `'d` when I got there, so it was between choosing `'d1+eu`, `'deu1+` or a variant where I used `)` and a space instead of `1+` (for the non-CJam people, this taking the `d` character and increment and upper-casing it, in either order). However, the `u` in the final column looked useful for A-down. So I picked the first of those. In the end, `'d) eu` would have worked, too.

Hint 9: `""`. Well, this had to be "empty string, get string representation, push a space". But also needed the \` for string representation in 7-down, and a space in A-down seemed useful, too, so I chose

```
]`'

```

Note that `]` might also have been one of `LMOQR`.

Hint B: `"m`. I just really had to fit this one in with the rest, but there were few characters that mattered. I already had the `{` and the `m`. So instead of using a block, I turned `{` into a character, discarded it, and then pushed the two required characters:

```
 '{;'"'m

```

Hint D: `124`. I solved this one together with C-down, which was easiest with a decrement at the end. So I push a 12, a 5, and decrement the latter:

```
C5(

```

### Down

Hint 1: `[2 2 2 3]`. That looked too suspiciously like a prime factorisation for it not to be one. :)

```
24mf`

```

Hint 3: `3010936384`. Factoring this showed that it's actually 386. The only question was how to get the `38` in compliance with 2-across. In the end I needed a `*` in the third place, so doubling `19` it was:

```
J2*6#

```

Hint 5: `2017`. Two characters for such a large number? Just use built-in two-digit variables:

```
KH

```

Hint 6: `"18"`. I think there's only a single way to do this in 3 characters. Use the built-in 18, convert it to a string, and then to its string representation.

```
Is`

```

Hint 7: `' "\"\""`. Probably the hardest part of the puzzle. In particular, I needed to get the `"\"\""` in only three characters. The trick was to get the string representation of the empty string twice. That led to:

```
' `L``+

```

THe `+` isn't necessary, but was needed by 8-across.

Hint 8: `!{}`. The block needed to go in the code, so that left only two characters for `!`, which meant using another literal:

```
'!{}

```

Hint A: `-3u3`. With the `u` in place from 8-across, I started to put `-3` and `3` in the corners where no other hint cared about them. But then I needed an `m` at the bottom. I think there are multiple ways to get a `3` with `_m_`, but the simplest was taking the square root of 9:

```
-3 'u9mq

```

Hint C: `-1`. I already had the decrement there, so I just put a `0` where no one else cared about:

```
0  (

```

Hint E: `Stack: ""`. Well that was the simplest one. Just call the debugger:

```
ed

```
> 8 votes

# Answer
COTO, Javascript ES4, 37 Darks

```
 __________
|{}=51###6#|
|a##.#I-9<4|
|:##-##"#<#|
|5+Math.PI#|
|}##+##.#+#|
|["9"+0][0]|
|'##p##"###|
|a+-a#a=-10|
|'##c##=###|
|]##"\x48I"|
 ¯¯¯¯¯¯¯¯¯¯

```
* 6 across is `5+Math.PI` or `Math.PI+5`; but the latter would leave 'M' and 'h' crossing over into other expressions, seemed unlikely.
* A across had to be a string; with 4 in the middle it looked like an escape, the only way you have room for that is with `"\x48I"`.
* 2 down now ends in a string, so probably is "pac" appended to a number; we'll come back to that.
* 8 ac is now `xxxa`, evaluating to zero, so -a+a? a+-a? 3+-a? `a+-a` looked best since it gave me what looked like a char in a string in 1dn.
* 1 down contained :5, which could only be legal grammar in `{x:5}xxa'x`. Since the value returned is 5, it must be pulling it out of the object, so `{x:5}['a']`, which means the final missing character is also a: `{a:5}['a']`
* 1 across now has { at the start. I guessed this was a red herring assignment, tried `t={}=51`, and it worked. Did not know that!
* 2 down now has `5xxax"pac"`=\>"2pac". This has to be `5-a+"pac"`, somehow, so the second char has to be '.' for the floating point literal.
* 7 ac is now `[xx"xxxx]`, returning "90". So this has to be an array literal with the value pulled out; there's only room for one value so we have `[xx"xx][0]`. There's not room for two strings in there, but either `"9"+0` or `9+"0"` fit.
* 3 dn; 3072 is 3\*1024; the power of 2 is suspicious, and I already had 'I' in there blocking other ways of getting large numbers (like 1eX). So, guessed bitshift; `6<<I` turned out to be the answer, leaving +0 to add on to the end.
* 4 ac now contained a comparison operator; and the second char had to be a valid unary operator (to fit in after both 't=' and 'I'). I guessed '-', and there's several possible solutions left (`I-I<4`, `I-6<4`, etc)
* 5 dn now contained `-x..]xxx4`. The ".." threw me - there's only a couple of ways that can be legal syntax and is why I asked if ES4 is what was intended - was this some odd feature of that abandoned spec? But then I saw that this was a red herring; `-""` is NaN, so `-"..]"xx4` must be what's there - a comparison to NaN, returning false; '==' will do, but need to look at the last answer for confirmation...
* 9ac had several possible solutions, but the restriction on characters that would be allowed for 5dn made me think this was yet another red herring assignment; something `=-10`. To be honest I also looked at the earlier version of 9dn, and realised that must be something `=top` (to get a Window back). The variable assigned to could be a or I, it doesn't matter.

Tricky puzzle!
> 7 votes

# Answer
# grc's Python puzzle

For all the lengthy floating-point expressions, I made a C++ program to generate Python mathematical expressions by force and evaluates them. It assumes all numbers are floating-point and only supports operators +, -, \*, /, //, \**, and ~. I used it to get every clue longer than 5 characters except `a**9*27%b` and the hash. With 6 or less blanks it finishes within a couple of seconds, while there is a bit of a wait for 7.
> 4 votes

# Answer
# Solution to COTO's MATLAB puzzle

I guess I golfed this one pretty well, as there are 14 spaces.

This test script:

```
g=4;
o=magic(3);
D=@disp;

D(max([  2]));
D( i^3);
D(o^0);
D(6 -7+eye  );
D((i));
D(.1  ^5* g );
D(~2);
D(diag(~o)  );

D(asin (1)*i);
D((93+7) +~g);
D(  10e15);
D(2*ones (2));
D(02 ^  9 );
D(-i );
D(~o);

```

produces the following output:

```
     2

        0 - 1.0000i

     1     0     0
     0     1     0
     0     0     1

     0

        0 + 1.0000i

   4.0000e-05

     0

     0
     0
     0

        0 + 1.5708i

   100

   1.0000e+16

     2     2
     2     2

   512

        0 - 1.0000i

     0     0     0
     0     0     0
     0     0     0

```
> 3 votes

---
Tags: printable-ascii, source-layout, cops-and-robbers, crossword
---


title: Find imperfect anagrams

text:
# Question
Title: Find imperfect anagrams
The goal of this challenge is to write a program which takes a string (of any length) as input and displays anagrams (see these examples of anagrams) of this string, made by taking words in a dictionary (either individually or in pairs), but the anagrams don't need to be perfect.

An anagram is the result of a rearrangement of a set of characters:

* `ABCD` and `CADB` are perfect anagrams, all the characters are present in both strings
* `ABCD` and `CADBEF` are imperfect anagrams because the characters `ABCD` are present in both strings but the characters `EF` only exist in the second string

The dictionary contains 1949 words:

```
ability
able
aboard
etc.

```

By taking each word and each pair of distinct words we generate a list of candidates to compare against the input:

```
ability
ability able
ability aboard
ability ...
able
able aboard
able ...
...

```

The program must display only the strings from the previous list which are anagrams of the input string. In other words, the program needs to filter the candidates down to the imperfect anagrams of the input.

# Examples

## Input

Sample:

```
> your_program 85 "Meta Code Golf" ./dict.txt

```

You may take input from any method you like, be it command line arguments or stdin.

## Expected output

```
ExCLAiMED FOOT
FrEEDOM LOCATe

```

(if I didn't make any mistake in my code)

# Rules

## Input:

```
n string filepath

```

(You may take input from any method you like, be it command line arguments or stdin)

* The first input will be an integer `n`. This is a threshold to define the minimum percentage of characters which must be present in the `string` input and the anagrams. `n` will be between `0` and `100`, inclusive
* The second input will be a string (a string with one or more words)
* The path to a file containing one word per line. The dictionary to use is available here (\**), it contains 1949 common words (source). You have to save this file without the comments to keep one word per line

\**: I chose to use only 1949 common words because the dictionaries like wamerican package (with Ubuntu it adds the `/usr/share/dict/american-english` file) contains about 100,000 words, this would lead to 10,000,000,000 possible combinations of 2 words. It may take to much time to compute in the context of code golfing. But a program which works with 2,000 words may still work with 100,000 words if someone wants to use all the words from a complete dictionary.

## Output:

* One matching anagram string per line. The matching letters between the input string and the anagram must be displayed in uppercase, and the non-matching letters must be lowercase. In the example, only 2 of the 3 `e` are in uppercase, because there are only 2 `e` in `Meta Code Golf`
* You must not display the same anagram twice (eg. `ExCLAiMED FOOT` and `FOOT ExCLAiMED` are both valid but they are only the result of a swap between the 2 words)

## Other rules:

* Comparison between input string and anagrams:
    + Lower and upper-case characters are considered as the same character when searching the anagrams
    + Non-letter characters  (space), `-`, etc. are considered as one character
* Standard “loopholes” are forbidden
* Shortest code wins

# Similarity index and threshold

## Similarity index:

The similarity index (**SI**) is calculated by counting the number of times each character from a string appear in another string. So we have to compute 2 SIs if the 2 strings have different lengths.

### Examples

`ABCD` and `CADB` are perfect anagrams, the characters are identical, the SI is 100%

`ABCD` and `CADBEF`: \- `ABCD` in `CADBEF`: the SI is 100% because all the characters of the first string exist in the second string \- `CADBEF` in `ABCD`: the SI is 4/6 because `ABCD` are present in the second string (and not `E` and `F`)

You have to ensure that you compare the input with the word **and** the word with the input, otherwise the word `AAABBBCCCDDDEEE (etc.)` may match the vast majority of the words. So we have to check that the 2 SIs are greater or equal than the threshold in order to *accept* an anagram.

### Example of SI function (pseudo-code):

```
function SI(a, b) {
    s_i = 0

    foreach (character in a) {
        if (character exists in b) {
            remove the character in b /* avoid to find several times "AAAA" in "A" */
            s_i++
        }
    }

    return(s_i / length(a))
}

```

## Threshold

The threshold acts as a filter to display only the anagrams which SI is greater or equal than the threshold.

To apply the threshold, we must use this function twice:

```
if ((SI(input, candidate) >= threshold) && (SI(candidate, input) >= threshold)) {/* anagram is ok */}

```

### Examples:

**Threshold = 100**

```
> program 100 "explanation" ./dict.txt
EXPLANATION

```

There is only one result because there is no perfect anagram for *Explanation*, except the word itself.

**Threshold = 90**

```
> program 90 "explanation" ./dict.txt
ALONE PAINT
EXPLAIN NOT
EXPLANATION
NATION PALE

```

**Threshold = 75**

```
> program 75 "explanation" ./dict.txt
AbLE cONTAIN
AbLE NATION
AbOuT EXPLAIN
AcT EXPLAIN
AcTION ALoNE
AcTION ANgLE
...

```

**Threshold = 0**

```
> program 0 "Meta Code Golf" ./dict.txt
AbILiTy
AbILiTy AblE
AbILiTy AbOard
AbILiTy AbOut
...

```

It will display all the words and all the combination of words from the dictionary (because all the SIs are greater or equal than the threshold).

## Random example

```
> program 85 "Beyonce Knowles" ./dict.txt
BEtWEEN COLONY
COWBOY SENtENcE

```

---

I was inspired by a french TV program named *Le Complot* where they make funny correlations between two unrelated persons, ideas, etc. For example, they showed that the soccer player *Pastore* is an anagram of *Apotres* (the french word for *Apostles*) in order to link Zlatan Ibrahimovic to Catholic Church.

# Answer
# Perl 5 -  166 158 146  143

4 of the new line characters are added for clarity (those following a semicolon).

```
$s.=lc"+s/$_/uc\$&/e"for($i=pop)=~/[a-z]| (?!.* )/ig;
$/=pop;
$_=<>;
s!.+!"$&".join"
$& ",$'=~/^|.+/g!ge;
100*eval$s<$/*length($_|$i)||print"$_
"for split'
'

```

The array based candidate generation actually proved to be shorter than my original string substitution one. Kept the previous 153 version as its output order is exactly as in the examples (though it is not required).

```
$s.=lc"+s/$_/uc\$&/e"for($i=pop)=~/[a-z]| (?!.* )/ig;
$z=pop;
100*eval$s<$z*length($_|$i)||print"$_
"for map{map$&." $_"x!/^$&$/,@s=(@s,/.+/g)}<>

```

Usage:

```
perl ./a.pl 90 "explanation" <dict.txt

```

## Edit

This version should conform to the specification with regard to non letter characters.
> 1 votes

# Answer
# Python 3 - 447

Again, this is one of these programs that takes a long time to test, but I'll add one of the test cases once it's done.

```
from sys import*
l=argv
e=''
t=[]
v=list
n='\n'
g=open(l[3]).read()
def s(a,b):
 m=0;a=list(a)
 for i in a:
  if i in b:b.remove(i);m+=1
 return m/len(a)*100
for i in g.split(n):
 for j in(n+g).split(n):
  a=i+' '+j if j!=''else i
  b=l[2].lower();c='';d=v(b);w=set(b.split(' '))
  t=l[1]
  if(s(a,d)>=t)and(s(d,v(a))>=t):
   if not w in t:
    for k in a:
     if k in d:d.remove(k);c+=k.upper()
     else:c+=k
    t.append(w)
    e+=c+n
print(e)

```

## Edit

The latest edit accounts for the rule that states that you must not print different arrangements of the two words.
> 2 votes

# Answer
# Python 2, ~~375~~ ... 313

```
S=lambda a,b:1.*len([b.remove(q)for q in a if q in b])/len(a)
T=lambda a,b:min(S(a,b[:]),S(b,a[:]))
t,s,d=input()
d=open(d).read().split()
for x in{' '.join(sorted([a,b]))for a in d for b in d}|set(d):
 q=list(s.lower())
 if T(list(x),q)*100>=t:print''.join([w,w.upper()][q.count(w)and not q.remove(w)]for w in x)

```

This expects slightly different input; like so: `90, "explanation", "dict.txt"`. If that's not allowed, I'll fix it.

Sample run, with stdin `90, "explanation", "dict.txt"`:

```
EXPLANATION
NATION PALE
EXPLAIN NOT
ALONE PAINT

```

This works by iterating through a set of all the possibilities, checking them. This is what makes it so slow.

```
S=lambda a,b:1.*len([b.remove(q)for q in a if q in b])/len(a) # define the SI function
  lambda a,b:                                                 # define a lambda with 2 inputs
                     b.remove(q)for q in a if q in b          # for q in a, if q is in b, remove q from b
                len([                               ])        # list.remove returns None, so collect all the removes and the resulting list will have len of the number of times we removed things
             1.*len([b.remove(q)for q in a if q in b])/len(a) # 1.* converts the len to a float, so that when we divide by len(a), we get a float

T=lambda a,b:min(S(a,b[:]),S(b,a[:])) # Determine the min SI for both possibilities
                 S(a,b[:]),           # run S with a and a copy of b; since b gets removes called in S
                           S(b,a[:])  # run S with b and a copy of a
             min(S(a,b[:]),S(b,a[:])) # get the min of those values

t,s,d=input()
d=open(d).read().split() # read the dict file and split it on newlines, creating a list of words

for x in{' '.join(sorted([a,b]))for a in d for b in d}|set(d): # iterate over possible word choices
                         [a,b]  for a in d for b in d          # create all possible pairs of words
                  sorted(     )                                # sort the list, making it so that ['exclaimed', 'foot'] and ['foot', 'exclaimed'] make the same element
         ' '.join(             )                               # combine the words with a space between
        {                                            }         # turn into set; this is a set comprehension
                                                      |set(d)  # take the union of that set and the set of single words.
for x in                                                     : # this is what we iterate over

 q=list(s.lower()) # we want to convert our string to lowercase, but we also want it as a list of characters because str doesn't have a remove function.

 if T(list(x),q)*100>=t: # decide if the element of the set matches the threshold
                        print''.join([w,w.upper()][q.count(w)and not q.remove(w)]for w in x) # it does; now we print the correct output
                                     [w,w.upper()]                               for w in x) # consider both the lower/uppercase versions of the char in the string
                                                  [q.count(w)and not q.remove(w)]            # if w appears at least once in the target string, we remove it from the target string, and do a logical negation on the None, resulting in True ie 1, so we choose uppercase
                             ''.join(                                                      ) # join these elements back into a string
                        print                                                                # print the result

```
> 2 votes

# Answer
# R - 512 (= 29!)

```
v=function(a){unlist(strsplit(tolower(a),""))}
s=function(a,b){
s=0;for(l in a){if(l%in%b){b=b[-(which(l==b)[1])];s=(s+1)}};s/length(a)}
r=function(v,j){p=c();for(l in v){if(l%in%j){j=j[-(which(l==j)[1])]
o=toupper(l)}else{o=tolower(l)};p=c(p,o)};cat(p,"\n",sep="")}
a=commandArgs(T);j=v(a[2]);k=(as.integer(a[1])/100);
d=scan(a[3],what='raw',sep="\n",quiet=T);
for(w in d){t=v(w);if((s(t,j)>=k)&&(s(j,t)>=k)){r(t,j)};
for(x in d[-1]){w2=paste(w,x,sep=" ");t=v(w2)
if((s(t,j)>=k)&&(s(j,t)>=k)){r(t,j)}};d=d[-1]}

```

## Ungolfed

```
get_array = function (a) {unlist(strsplit(tolower(a),""))}

# calculate similarity index of 2 strings
get_s = function (a, b) {
    s = 0
    for (letter in a) {
        if (letter %in% b) {
            b = b[-(which(letter == b)[1])]
            s = (s + 1)
        }
    }
    return(s / length(a))
}

# output
get_result = function (var_string, input) {
    output = c()

    for (letter in var_string) {
        if (letter %in% input) {
            input = input[-(which(letter == input)[1])]
            o = toupper(letter)
        }
        else
        {
            o = tolower(letter)
        }
        output = c(output, o)
    }
    cat(o, "\n",sep="")
}

# get arguments
a = commandArgs(T)
input = get_array(a[2])
threshold = (as.integer(a[1]) / 100)
dict = scan(a[3], what='raw', sep="\n", quiet=T)

# iterate through all the words from the dictionary
for (w in dict)
{
    t = get_array(w)

    # the word only
    if (
        (get_s(t, input) >= threshold)
        &&
        (get_s(input, t) >= threshold)
    )
    {
        get_result(t, input)
    }

    # the word + another word
    for (x in dict[-1]) {
        w2 = paste(w, x, sep=" ")
        t = get_array(w2)
        if (
            (get_s(t, input) >= threshold)
            &&
            (get_s(input, t) >= threshold)
        )
        {
            get_result(t, input)
        }
    }

    dict = dict[-1] # remove the word once it has be permuted with all the other words
}

```
> 0 votes

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


title: Guess the number

text:
# Question
Title: Guess the number
### Description

Create a fully working "Guess the number" game. The game is played by two players as follows:

1. player one chooses a number (A) between 1 and **N**
2. player two tries to guess A choosing a number (B) in the same range
3. the first player responds **"higher"** `if A > B`, **"lower"** `if A < B` or **"correct"** `if A = B`.
4. steps 2-3 are repeated **I** times or until "correct" is responded.
5. If "correct" is heard, player two wins otherwise he loses.

### Specs

Minimum specs for a valid entry:

* user can play either as player one or player two.
* computer plays the other role.
* computer must really try to guess the number while playing as player two (so, guessing against the given data or ignoring the given data is cheating)
* N = 100 **or** input by the user (your choice)
* I = 5 **or** input by the user (your choice)
* program must announce then winner at the end.
* full human readable instructions of what to do in each step (e.g *"Play as player one or player two?"*, *"Enter another guess:"*, etc) - don't go nuts on this one; just keep it simple.

### Winning conditions

In that order:

1. Highest voted entry wins **if** it's at least 3 votes ahead of the second highest voted entry.
2. Shortest entry wins.

# Answer
## Windows PowerShell, 289

```
nal ^ Read-Host
filter p{"Player $_ wins.";exit}
$p=1-(^ Player 1 or 2)
$n=($x=1)..($y=99)|random
if($p){$n=^ Enter number}1..5|%{if($p){'{0:"higher";"lower";"correct";2|p}'-f($n-(^ Guess))|iex}else{"Guessing, "+($g=$x..$y|random);@{104='$x=$g+1';108='$y=$g-1';99='2|p'}[+(^)[0]]|iex}}
1|p

```

History:

* 2011-02-21 18:44 **(620)** Ungolfed.
* 2011-02-21 19:15 **(365)** First round of golfing.
* 2011-02-21 19:31 **(359)** Some inlining.
* 2011-02-21 19:38 **(340)** Some strings shortened.
* 2011-02-21 19:44 **(339)** `while``for`
* 2011-02-21 19:53 **(331)** Some duplicate strings pulled into variables.
* 2011-02-21 19:53 **(330)** Another variable inlined.
* 2011-02-21 19:53 **(328)** Optimized loop condition. Can't use a pipeline, though.
* 2011-02-22 01:57 **(326)** `else{if...}``elseif` – saves the braces.
* 2011-02-22 12:42 **(325)** Moved plenty of stuff around, using a hashtable instead of the `switch` to avoid naming the loop. Now I can use just `break` and a pipeline, too. Winner announcement moved into a filter that uses `exit` so no break required, ever.
* 2011-02-23 01:23 **(308)** Instead of an `elseif` chain for checking the guess I just use a format string with different values for negative, positive and zero values. Saves a lot.
* 2011-02-23 02:16 **(306)** Using subtraction instead of equality.
* 2011-03-12 02:27 **(289)** Reduced to the same level of rudimentary user interaction as the Ruby solution. Of course it's shorter then.
> 3 votes

# Answer
## TRS-80 BASIC, 249 characters

I think this may be the first time I've submitted an answer to this site that I wrote *before* the site existed.

```
0 CLS:RANDOM:A=1:B=1E3:Q=RND(1E3):FORX=1TO8E9:PRINTA"-"B:INPUT"
 Guess";C:IFC<AORC>B,X=X-1:NEXTELSEIFC<QPRINT"Too low":A=C+1:NEXTELSEIFC>QPRINT"Too high":B=C-1:NEXTELSEPRINTC"is right!!
 It took you"X"tries.
":X=9E9:NEXT:FORX=0TO0:X=INKEY$="":NEXT:RUN

```

In fact, I wrote it before the worldwide web existed. Back in the 1980s, just as TRS-80s were becoming irrelevant.

This is an example of a "one-liner" — an attempt to fit the most interesting program you could into a single line of BASIC. It was my first one-liner, and not terribly impressive. (There were some amazing one-liners floating around out there.)

A line of TRS-80 BASIC was limited to 255 characters, minus a couple for overhead. Though you could sometimes exceed this, since the true limit was 255 bytes *after* tokenization — but the editor would also truncate a line that had over 255 characters *before* tokenization, and you needed to use tricks in the line editor in order to insert literal control characters like newlines into your strings.

And yes, to clarify, those line breaks in the listing are literal newline characters. (In order to get them in your code you needed to use the `C`hange command while `EDIT`ing the line. A total pain, but worth it to replace eight or more characters for `+CHR$(13)` with one.)

Damn, I've been golfing for a long time.
> 9 votes

# Answer
**C 397 Characters**

```
N,H=99,L=0,c=0,w=1;main(){char s[9];puts("Play as player 1 or 2: ");scanf("%d",&N);if(N-1){getchar();do{N=rand()%(H-L)+L+1;printf("My guess: %d\n",N);gets(s);if(*s=='c'){w=2;break;}if(*s-'l')H=N-1;else L=N-1;c++;}while(c<5);}else{N=rand()%99+1;while(c<5){puts("Enter guess: ");scanf("%d",&H);if(H==N){puts("correct");break;}else puts(H>N?"higher":"lower");c++;}if(c==5)w=2;}printf("Winner %d",w);}

```

In a more readable form.

```
main()
{
        int i,N,H=100,L=0,c=0,w=1;
        char s[10];
        puts("Play as player 1 or 2: ");
        scanf("%d",&i);
        if(i-1)
        {
                getchar();
                do{
                        N=rand()%(H-L)+L+1;
                        printf("My guess: %d\n",N);
                        gets(s);
                        if(s[0]=='c')break;
                        else if(s[0]=='h')H=N-1;
                        else L=N-1;
                        c++;
                }while (c<5);
                if(c<5)w=2;
        }
        else
        {
                N=rand()%99+1;
                while (c<5)
                {
                        puts("Enter another guess: ");
                        scanf("%d",&H);
                        if(H==N){printf("correct\n");break;}
                        else if(H>N)printf("higher\n");
                        else printf("lower\n");
                        c++;
                }
                if(c==5)w=2;
        }
        printf("Winner %d",w);
}

```
> 6 votes

# Answer
C#:

Character count: With spaces: 575 No spaces: 464

```
    static void Main()
    {
        Action<object> w = s => Console.WriteLine(s);
        Func<object, byte> r = t => { w(t); var s = Console.ReadLine(); return Convert.ToByte(s); };
        var p = r("Player (1/2):");
        int N = 100, g, i = 0, c, d;
        var q = new List<int>(Enumerable.Range(0, N));
        Func<Guid> x = Guid.NewGuid;
        c = p == 1 ? r("Number:") : q.OrderBy(j => x()).First();
        m: i++;
        g = p == 2 ? r("Guess:") : q.OrderBy(j => x()).First();
        d = g < c ? -1 : (g > c ? 1 : 0);
        w(d == -1 ? "Higher" : (d == 1 ? "Lower" : "correct"));
        q = q.Where(n => d == -1 ? n > g : n < g).ToList();
        if(c != g && i < 5) goto m;
        r(g);
    }

```

**Edit** do while is now "Goto" (*shiver*)
> 4 votes

# Answer
Good old plain C

```
#include <stdio.h>
#define x(s) puts(s)
main(){int c,i,l,h,g;srand(time(NULL));p:x("You want to guess (1) or should I (2)?");scanf("%d",&c);i=5;if(c==2){x("Think a number 1..100");h=100;l=1;goto t;}if(c==1){x("Guess a number 1..100");h=rand()%100+1;goto g;}return 0;t:if(!i--)goto u;printf("%d (1)higher (2)lower (3)correct",g=rand()%(h-l)+l);scanf("%d",&c);if(c==1)l=g;if(c==2)h=g;if(c==3)goto c;goto t;g:if (!i--)goto c;scanf("%d",&g);if(g>h)x("lower");if(g<h)x("higher");if(g==h){x("correct");goto u;}goto g;u:x("You win");goto p;c:x("I win");goto p;}

```
* 23/11/2011 16:44:00 **883** nice and cosy
* 24/11/2011 09:38:00 **616** fixed & shortened
* 24/11/2011 11:52:00 **555** shortened
> 3 votes

# Answer
# JavaScript

New minified version (dropped `var` and reduced `alert` calls:

# 268 chars

```
function g(m){n=u(confirm('Player pick?'));function u(p){if (p){do{n=parseInt(prompt('Number'))}while(isNaN(n)||!n||n>m)}else{n=parseInt(Math.random()*m)+1}return n}while(g!==n){do{g=parseInt(prompt('Guess'))}while(isNaN(g));alert(g<n?'higher':g>n?'lower':'correct')}}

```

To run call `g(100);`, self-execution is not counted, as it adds a variable number of characters (275 chars for `g(100);`).

original (somewhere around 600 chars including whitespace):

```
function guessTheNumber(m)
{
  var n = getNum(confirm('Player pick the number?')), g;

  function getNum(p)
  {
    var n;
    if (p)
    {
      do
      {
        n = parseInt(prompt('What number?'));
      } while(isNaN(n) || !n || n > m);
    }
    else
    {
      n = parseInt(Math.random() * m) + 1;
    }
    return n;
  }

  while(g!==n)
  {
    do
    {
      g = parseInt(prompt('Take a guess!'));
    } while(isNaN(g));
    if (g < n)
    {
      alert('higher');
    }
    else if (g > n)
    {
      alert('lower');
    }
    else
    {
      alert('correct!');
    }
  }
}

```

Minified **(312)**:

```
function g(m){var g,n=u(confirm('Player pick?'));function u(p){var n;if (p){do{n=parseInt(prompt('Number'))}while(isNaN(n)||!n||n>m)}else{n=parseInt(Math.random()*m)+1}return n}while(g!==n){do{g=parseInt(prompt('Guess'))}while(isNaN(g));if(g<n) alert('higher');else if(g>n) alert('lower');else alert('correct')}}

```
> 3 votes

# Answer
**Python 2.7 ~~334~~ ~~335~~ ~~327~~ ~~314~~ 300 Characters** (My first time golfing)

(335) Forgot to escape newline.

(327) Removed redundant 100 for randint. Comparison of first character of response, instead of whole string.

(314) Updated printing who won.

(300) Changed when player was player 1: changed guessing of the number as computer

```
from random import*
i=input
s="Enter number:"
p=i("Player 1/2:")-1
h=100
N=(i(s),randint(1,h))[p]
b=l=0
for _ in[0]*5:
 exec("g=(h+l)/2;r=raw_input('Guessing '+`g`+':')[0];exec('h=g','l=g')[r=='l'];b=r=='c'","g=i(s);b=g==N;print(('higher','lower')[N<g],'correct')[b]")[p]
 if b:break
print 1+b,"won"

```
> 3 votes

# Answer
## BASIC, 184

```
100 INPUT "P1 NUMBER? ";
200 FOR I%=1 TO 5
300 INPUT "P2 GUESS? ";G%
400 INPUT "P1 SENTENCE? ";S$
500 IF S$="CORRECT" THEN 800
600 NEXT I%
700 PRINT "WINNER 1":END
800 PRINT "WINNER 2"

```

Here's the no-AI version.
> 2 votes

# Answer
**Lua 360 Chars**

```
i=io.read p=print I=5 N=100 math.randomseed(os.time())r=math.random p"Play as player one or two?"o=i"*n">1 _=o and p("Input number between 1 and",N)n=o and i"*n"or r(I,N)l,u=1,N for k=1,I do p"Guess!"g=o and r(l,u)or i"*n"p("Guessed",g)if n==g then p"Correct"break elseif n>g then p"Higher"l=g else p"Lower"u=g end end p(o and"I"or"You",n==g and"Won"or"Loose")

```

Non-golfed version:

```
i=io.read
p=print
I=5
N=100
math.randomseed(os.time())      -- Make things less predictable
r=math.random
p"Play as player one or two?"
o=i"*n">1
_=o and p("Input number between 1 and",N) -- if one, ask for number
n=o and i"*n"or r(I,N)          -- get number from user or random
l,u=1,N                         -- boundaries for doing "smart" guessing
for k=1,I do
    p"Guess!"
    g=o and r(l,u)or i"*n"      -- get guess (random or input)
    p("Guessed",g)
    if n==g then p"Correct!"break -- break loop if guessed correctly
    elseif n>g then             -- if guess to low
    p"Higher"l=g else           -- print + update boundaries
    p"Lower"u=g end
end
p(o and"I"or"You",n==g and"Won"or"Loose") -- Determine outcome!

```
> 2 votes

# Answer
# Java, 1886 chars

```
import java.io.*;import java.util.*;import java.util.regex.*;public class GuessGame {int L=1;int H=100;int G=5;int N;String HS="higher";String LS="lower";String CS="correct";public static void main(String[] args){if (args.length==2)new GuessGame(Integer.parseInt(args[0]),Integer.parseInt(args[1])).play();else if(args.length==0)new GuessGame(100,5).play();else System.out.println("usage GuessGame HighInteger NumberGuess");}GuessGame(int H,int G){this.H = H;this.G = G;}void play(){int pNum=getInt("Play As Player 1 or Player 2?","1|2");if(pNum==1)playP2();else playP1();System.out.println("The number was "+N);}int getInt(String pmpt,String val){BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));int i=0;Pattern p=Pattern.compile(val);boolean fnd=false;String ln="";try{while(!fnd){System.out.println(pmpt);ln=cin.readLine();Matcher m=p.matcher(ln);fnd=m.find();}i=Integer.parseInt(ln);} catch (Exception ex) {}return i;}String processGuess(int g){if(N>g)return HS;else if(N<g)return LS;else return CS;}void playP1(){N=new Random().nextInt(H);for(;G>0;G--){String rslt=processGuess(getInt("Player 2, enter your guess:","\\d?"));System.out.println(rslt);if(rslt.equals(CS)){System.out.println("Player 2 wins!");break;}}}void playP2() {N=getInt("Player 1, enter your number:", "\\d+");int max=H;int min=L;int nextGuess=min+(max-min)/2;for (;G>0;G--){System.out.println("Player 2, enter your guess:" + nextGuess);String rslt=processGuess(nextGuess);System.out.println(rslt);if(rslt.equals(HS)){min=nextGuess+1;nextGuess=fuzzify(nextGuess+(max-nextGuess)/2,min,max);}if (rslt.equals(LS)){max=nextGuess-1;nextGuess=fuzzify(nextGuess-(nextGuess-min)/2,min,max);}if(rslt.equals(CS)){System.out.println("Player 2 wins!");break;}}}int fuzzify(int i,int mn,int mx){int fz=new Random().nextInt(3);if(fz==1)return Math.max(mn,--i);if(fz==2)return Math.min(mx,++i);return i;}}

```

Non golfed version:

```
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class GuessGame {
    int L = 1;
    int H = 100;
    int G = 5;
    int N;
    String HS = "higher";
    String LS = "lower";
    String CS = "correct";
    public static void main(String[] args) {
        if (args.length == 2)
            new GuessGame(Integer.parseInt(args[0]), Integer.parseInt(args[1])).play();
        else if (args.length == 0)
            new GuessGame(100, 5).play();
        else
            System.out.println("usage GuessGame HighInteger NumberGuess");
    }
    GuessGame(int H, int G) {
        this.H = H;
        this.G = G;
    }
    void play() {
        int pNum = getInt("Play As Player 1 or Player 2?","1|2");
        if (pNum == 1)
            playP2();
        else
            playP1();
        System.out.println("The number was " + N);
    }
    int getInt(String pmpt, String val) {
        BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
        int i = 0;
        Pattern p = Pattern.compile(val);
        boolean fnd = false;
        String ln = "";
        try {
            while (!fnd) {
                System.out.println(pmpt);
                ln = cin.readLine();
                Matcher m = p.matcher(ln);
                fnd = m.find();
            }
            i = Integer.parseInt(ln);
        } catch (Exception ex) {}
        return i;
    }
    String processGuess(int g) {
        if (N > g)
            return HS;
        else if (N < g)
            return LS;
        else
            return CS;
    }
    void playP1() {
        N = new Random().nextInt(H);
        for (; G > 0; G--) {
            String rslt = processGuess(getInt("Player 2, enter your guess:", "\\d?"));
            System.out.println(rslt);
            if (rslt.equals(CS)) {
                System.out.println("Player 2 wins!");
                break;
            }
        }
    }
    void playP2() {
        N = getInt("Player 1, enter your number:", "\\d+");
        int max = H;
        int min = L;
        int nextGuess = min + (max - min) / 2;
        for (; G > 0; G--) {
            System.out.println("Player 2, enter your guess:" + nextGuess);
            String rslt = processGuess(nextGuess);
            System.out.println(rslt);
            if (rslt.equals(HS)) {
                min = nextGuess + 1;
                nextGuess = fuzzify(nextGuess + (max - nextGuess) / 2, min, max);
            }
            if (rslt.equals(LS)) {
                max = nextGuess - 1;
                nextGuess = fuzzify(nextGuess - (nextGuess - min) / 2, min, max);
            }
            if (rslt.equals(CS)) {
                System.out.println("Player 2 wins!");
                break;
            }
        }
    }
    int fuzzify(int i, int mn, int mx) {
        int fz = new Random().nextInt(3);
        if (fz == 1)
            return Math.max(mn, --i);
        if (fz == 2)
            return Math.min(mx, ++i);
        return i;
    }
}

```
> 2 votes

# Answer
# Javascript

This is about 800 characters, and includes your basic binary selection 'AI' for the computer player half. I could probably save a few characters if I got rid of all my `var`s but I don't like leaking variables even while code golfing. I also did a two step "Is this correct?"/"Is this higher?" thing with confirm pop-ups rather than giving a prompt pop-up and checking for "correct"/"higher"/"lower" though that could maybe also save some characters, I didn't really check.

Also, I only tested it on Firefox 4, so I don't know if some of the things I'm doing work consistently, particularly coalescing an invalid input, parsed as NaN, to a default value in my `wp` function.

```
function game(N, I) {
    var wa=function(a){window.alert(a)};
    var wc=function(s){return window.confirm(s)};
    var wp=function(s){return window.prompt(s)};
    var ri=function(s,d){return parseInt(wp(s),10)||d};
    var m=function(l,h){return Math.round((h+l)/2)};
    N = N || pd("Highest possible number?",100);
    I = I || pd("How many guesses?",5);
    var p = wc("Be player 2?");
    var s = [1,N];
    var a = p?Math.ceil(Math.random()*N):Math.min(N,Math.max(1,ri("Pick a number from 1 to " + N,1)));
    var w = 0;
    var g = 0;
    if(p) while(I--){while(!(g = ri("Guess:",0)));if(g==a){wa("correct");w=p+1;break;}else{wa(g<a?"higher":"lower")}}
    else while(I--){g = m(s[0],s[1]);if(wc("Is "+g+" correct?")) { w=p+1;break;} else if (wc("Is "+g+" higher?")){s=[s[0],g];}else{s=[g,s[1]];}}
    if(!w)w=!p+1;
    wa("Player " + w + " wins!");
}
game(100,5);

```
> 2 votes

# Answer
# Alarm Clock Radio, 5756 bits (2159 bytes)

**Coming soon to an alarm clock near you!** *Newlines are for readability only.* ASCII values are used occasionally in place of the literal numeric display on-screen. Fits specs. Uses defaults for `A` and `I`. On the first input, use NULL to be the guesser, otherwise you will set the number. **PADSIZE MUST BE 4! CELLS MUST BE 7-BIT AND WRAP!** Turing-complete! Outputs `higher`, `lower`, `correct`, `you won`, and `you lost`.

```
}+>,[,>>+++++++[>>>>>>>+++++++>+++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++]>>>>>>>++++++.>>>>>>>++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++.++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++[++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++>+>>>>>>>]>+++.+++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++>++++>>>>>>>]>+++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++.[+]+][++++[+++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++>,[+[+++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++>++>>>>>>>]>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++.++++++++.[+
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>.+++++++++++++.[+
]+][++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++[++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++>+>>>>>>>]>++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++++++++.+++..++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++>+>>>>>>>]>+++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++.>>>>>>>[+]>>>>>>>+++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++]]][>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>+++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++.+++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++[+++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++>+>>>>>>>]>+++.++[+++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>+
+>>>>>>>]>.+++.++++.+.>>>>>>>[+]+][+++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++[++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++>+++>>>>>>>]>+++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++[+++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++>+>>>>>>>]>+++.++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++[+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>++++>>>>>>>]>++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.]

```
> 2 votes

# Answer
## Ruby 1.9 (298)

```
b=->f{puts "> "+f;gets}
a=->f{b[f].to_i}
q=a["Player 1 or 2?"]
i,j,g=100,1
n=q<2?a["Enter number:"]:rand(i)+j
5.times{q<2?(g=j+(i-j)/2
c=b["Guessing, #{g}"]
c[0]==?c?break: c[0]==?h?j=g :i=g):(
g=a["Guess:"]
puts g==n ?"correct":g<n ?"higher":"lower"
g==n&&break)}
puts "Player #{g==n ?2:1} won!"

```

Not very friendly instructions though.
> 1 votes

# Answer
I felt the need to do Java some justice. :)

# Java - ~~486~~ ~~437~~ ~~421~~ 414

**Golfed**

```
import java.util.*;class GuessANumber{static<T>void p(T p){System.out.println(p);}static int i(){return new Scanner(System.in).nextInt();}public static void main(String[]a){int c,g,f=101,i=0;p("Pick (1) or guess (2)?");c=i();if(c==1)p("Pick a number (1-100)");g=c==1?i():new Random().nextInt(100);while(f!=g&&i++<5){p("Guess:");f=c==2?i():f>g?f/2:f+f/2;if(c==1)p(f);p(f>g?"lower":"higher");}if(f==g)p("correct");}}

```

**Slightly Ungolfed**

```
import java.util.*;

class a{

    static<T>void p(T p){
        System.out.println(p);
    }

    static int i(){
        return new Scanner(System.in).nextInt();
    }

    public static void main(String[]a){
        int c,g,f=101,i=0;
        p("Pick (1) or guess (2)?");
        c=i();
        if(c==1)p("Pick a number (1-100)");
        g=c==1?i():new Random().nextInt(100);
        while(f!=g&&i++<5){
            p("Guess:");
            f=c==2?i():f>g?f/2:f+f/2;
            if(c==1)p(f);
            p(f>g?"lower":"higher");
        }
        if(f==g)p("correct");
    }
}

```
> 1 votes

---
Tags: code-challenge, game
---