title: Hidden stereogram message

text:
# Question
Title: Hidden stereogram message
You must generate an text stereogram according to an input string containing a paragraph of text, an empty line then the hidden message. The result will be displayed as a pair of paragraphs, one with different spacing causing the effect of it being raised up when viewed stereographically (An explanation can be found here).

### Example

Input:

```
I invented vegetarianism.  It is a diet involving no meat, just vegetables.  It is also common in cows - they are awesome.

vegetarianism. is awesome.

```

Output:

```
I      invented    I      invented
 vegetarianism.    vegetarianism.
It   is a  diet    It  is  a  diet
involving    no    involving    no
meat,      just    meat,      just
vegetables.  It    vegetables.  It
is  also common    is  also common
in cows  - they    in cows  - they
are    awesome.    are   awesome.

```

### Bonuses

* Add option to choose between parallel and cross-eyed as user input (-20)
* Adjustable column width as user input (-50)

This is code golf, so shortest code after bonuses wins.

# Answer
> 1 votes
## Bash, sed: ~~228~~ ~~223~~ ~~197~~ (242 - 70) = 172

```
c=${5:-=};R=$c;L=;for f in r l;do
e="sed -e ";$e"$ d;s/$\|  */ \n/g" $1>m
o=1;for w in `$e"$ p;d" $1`;do
$e"$o,/^$w /s/^$w /$L$w$R /" m>n;o="/$c/"
cp n m;done;tr -d \\n<n|fold -sw${2:-35}|$e"s/$c/ /g">$f
L=$c;R=;done;pr -tmw${3:-80} ${4:-l r}

```

If the script is in an executable file called "stereo", then type

```
stereo file.in [column_width [page_width ["r l"]]]

```

column\_width is a number; 25-45 will work, default is 35.

page\_width is a number, should be about twice the column\_width, default is 80

For cross-eyed viewing, use "r l" as the 4th argument. Default is "l r" which sets up for parallel viewing.

EDIT: Rewrote to split the file into one word per line, then reassemble at the end. Note: reserves the "=" sign for its own use. Any "=" signs in the input file will become blanks.

EDIT: If your message has "=" signs in it, you can choose another symbol for the script to use, by supplying it as the 5th parameter.

**Example**

Input: vegetarianism.txt:

```
I invented vegetarianism.  It is a diet involving no meat, just
vegetables.  It is also common in cows - they are awesome.

vegetarianism. is awesome.

```

**Result**

./stereo vegetarianism.txt 32 72 "l r" : | expand (using the colon for its internal working symbol)

```
I invented  vegetarianism. It       I invented vegetarianism.  It
 is a diet involving no meat,       is  a diet involving no meat,
just vegetables. It is also         just vegetables. It is also
common in cows - they are           common in cows - they are
 awesome.                           awesome.

```

./stereo washington.txt 35 75 "l r" |expand

```
In a little district west of          In a little district west of
 Washington Square the streets        Washington  Square the streets
have run crazy and broken             have run crazy and broken
themselves into small strips          themselves into small strips
called 'places'. These 'places'       called 'places'. These 'places'
make strange angles and curves.       make strange angles and curves.
One Street crosses itself a time      One Street crosses itself a time
or two. An artist once discovered     or two. An artist once discovered
a valuable possibility in this        a valuable possibility in this
street. Suppose a collector with a    street. Suppose a collector with a
bill for  paints, paper and canvas    bill for paints,  paper and canvas
should, in traversing this route,     should, in traversing this route,
suddenly meet  himself coming         suddenly meet himself  coming
back, without a cent having been      back, without a cent having been
paid on account!                      paid on account!

```

The "|expand" isn't necessary but when shifting the output by 4 places the TABs get handled incorrectly. It could be put into the script at a cost of 7 bytes.

## ImageMagick variation

Replacing the last line with a text-to-image ImageMagick command:

```
c=${6:-=};R=$c;L=;for f in r l;do
e="sed -e ";$e"$ d;s/$\|  */ \n/g" $1>m
o=1;for w in `$e"$ p;d" $1`;do
$e"$o,/^$w /s/^$w /$L$w$R /" m>n;o="/$c/"
cp n m;done;tr -d \\n<n|fold -sw${2:-35}|$e"s/$c/ /g">$f
L=$c;R=;done;
convert -border 10x30 label:@${4:-l} label:@${5:-r} +append show:

```

In this one, the "r" and "l" for cross-eyed versus parallel viewing are separate arguments:

./im\_stereo vegetarianism.txt 40 80 l r =

(source: simplesystems.org)

EDIT 3: Added ImageMagick variation.

# Answer
> 8 votes
# TeX 212

I am using a typesetting system, not ASCII. The column width can be changed by changing `90pt` in the fourth line, but I don't know if that's enough to qualify for the 50 bytes discount. The distance between the two copies of the text can be changed by changing the `9pt`, also in the fourth line. The code can probably be made shorter. One can replace each newline by a single space, but not remove them completely.

```
\let\e\expandafter\read5to\t\read5to\.\def\a#1
{\def\~##1#1##2\a{\def\t{##1\hbox{\
#1\~{}}##2}\a}\e\~\t\a}\e\a\.{}\shipout\hbox
spread9pt{\hsize90pt\fontdimen3\font\hsize\vbox{\t}\
\let\~\ \def\ {}\vbox{\t}}\end.

```

After calling `tex filename.tex` in the terminal, the user is prompted to give the main text, then prompted again for a list of words to shift. No empty line in between. The (space-separated) list of words given in the second line should appear exactly as it is in the main text (punctuation is treated just like a letter would be, only spaces delimit words).

# Answer
> 4 votes
# Javascript 391 (441 - 50)

(My first code golf)

```
k=' ';Q='length';A=prompt().split(k);S=prompt().split(k);i=-1;M=25;L=[[]];j=0;R='';while(i++<A[Q]-1){if((j+A[i][Q])<M){if(S.indexOf(A[i])>-1){A[i]=(j?k+k:k)+A[i]}L[L[Q]-1].push(A[i]);j+=A[i][Q]+1}else{j=0;i--;L.push([])}}for(i=0;i<L[Q]-1;P(L[i++].join(C))){C=k;while(L[i].join(C+k)[Q]<M){C+=k}}P(L[i].join(k)+k);function P(a){while(a[Q]<M){a=a.replace(k,k+k)}R+=a;for(c in S){a=a.split(k+k+S[c]).join(k+S[c]+k)}R+=k+k+a+'\n'}console.log(R);

```

## Result

```
In    a  little  district   In    a  little  district
west    of     Washington   west    of    Washington
Square   the streets have   Square   the streets have
run    crazy  and  broken   run    crazy  and  broken
themselves    into  small   themselves    into  small
strips   called 'places'.   strips   called 'places'.
These     'places'   make   These     'places'   make
strange     angles    and   strange     angles    and
curves.     One    Street   curves.     One    Street
crosses  itself a time or   crosses  itself a time or
two.     An  artist  once   two.     An  artist  once
discovered    a  valuable   discovered    a  valuable
possibility     in   this   possibility     in   this
street.      Suppose    a   street.      Suppose    a
collector   with  a  bill   collector   with  a  bill
for   paints,  paper  and   for  paints ,  paper  and
canvas      should,    in   canvas      should,    in
traversing   this  route,   traversing   this  route,
suddenly   meet   himself   suddenly   meet  himself
coming    back, without a   coming    back, without a
cent  having been paid on   cent  having been paid on
account!                    account!

```

## Long code:

```
var arr = "In a little district west of Washington Square the streets have run crazy and broken themselves into small strips called 'places'. These 'places' make strange angles and curves. One Street crosses itself a time or two. An artist once discovered a valuable possibility in this street. Suppose a collector with a bill for paints, paper and canvas should, in traversing this route, suddenly meet himself coming back, without a cent having been paid on account!".split(' ');
var secret = "Washington paints himself".split(' ');
var i = -1;
var MAX_WIDTH = 25;
var lines = [[]];
var _l = 0;

var result = '';

while (i++ < arr.length - 1) {
    if ((_l + arr[i].length) < MAX_WIDTH) {
        if (secret.indexOf(arr[i]) > -1) {arr[i] = (_l?'  ':' ') + arr[i]}
        lines[lines.length - 1].push(arr[i]);
        _l += arr[i].length + 1;

    } else {
        _l = 0;
        i--;
        lines.push([]);
    }
}

for (var i = 0; i < lines.length - 1; putText(lines[i++].join(chars))) {
  // Align text
  var chars = ' ';
  while (lines[i].join(chars + ' ').length < MAX_WIDTH) {
    chars += ' ';
  }
}
putText(lines[i].join(' ') + ' ');
function putText(line) {
  while (line.length < MAX_WIDTH) {
    line = line.replace(' ', '  ');
  }
  // Make the illusion
  result += line;
  for (var val in secret) {
    line = line.split('  '+secret[val]).join(' ' + secret[val] + ' ');
  }
  result += ('   ' + line) + '\n';
}
console.log(result);

```

# Answer
> 3 votes
# Javascript 493 (minimum expectations)

```
g=" ";l=prompt().split(g);r=l.slice();m=prompt().split(g);f=[];s=f.slice();w=0;n=0;a="";for(i=0;i<l.length;i++){if(l[i]==m[0]){m.shift();l[i]=g+r[i];r[i]+=g;}if(l[i].length+1>w)w=l[i].length+1;}while(l.length){f[f.length]="";s[s.length]="";while(l.length&&f[f.length-1].length+l[0].length<w){f[f.length-1]+=l[0]+g;s[s.length-1]+=r[0]+g;l.shift();r.shift();}f[f.length-1]+=g.repeat(w-f[f.length-1].length);}console.log(f,s);while(f.length){a+=f[0]+s[0]+"\n";f.shift();s.shift();}console.log(a);

```

This code sets up two arrays of lines (left and right), arranges them in a string and prints to `f12` console.

This is just a minimum answer, not intended to win.

# Answer
> 3 votes
# GolfScript 209 (279 -50 -20)

This is my first big GolfScript program. I wouldn't be surprised if there are optimizations to be had. Both the bonuses are supported; they are expected to be found after the message inputs, like:

```
"I invented vegetarianism.  It is a diet involving no meat, just vegetables.  It is also common in cows - they are awesome."

"vegetarianism. is awesome."

16  # column width
0   # view type, 1 for cross eyed (?)

```

If you've saved that file to `input` (and downloaded GolfScript) you can invoke the script with:

```
> cat input | ruby golfscript.rb

```

### Golfed

```
~{{\}}{{}}if:v;:w;n%~' '%\' '%[.]zip 0:c;{' '*}:s;{[.;]}:r;\{:x;{.c=0=x=}{1c+:c;}until.c<\1c+>[[x' 'v+' 'x v+]]\++}/zip{0:c;[[]]\{.,.c+w<{1c++:c;\)@r+r+}{:c;[r]+}if}/{.{,}%{+}*w\- 1$,1-.{1$1$/@@%@0:g;{3$3$g>+s\++1g+:g;}*\;\;}{[;.2/\2%1$s@@+s@)\;\]{+}*}if}%}%zip{{4s\++}*}%n*puts

```

### Ungolfed

```
~
#The program:

# Parameters, in reverse natural order

{{\}}{{}}if:v;   # view - truthy for parallel, falsey for cross-eyed
:w;         # col width

n%~         # split input on newlines

' '%\       # split secret message tokens
' '%        # split public message

[.]zip      # left and right

0:c;        # word count

{' '*}:s;   # spaces
{[.;]}:r;   # array of top

# for each secret word
\{

  :x;       # word

  {.c=0=x=}
  {1c+:c;} until
  # next public word is this private word

  # splice edits
  .c< \1c+> [[x' 'v+  ' 'x v+]]\ ++

}/
zip

# layout both messages
{

  0:c;    # char count

  [[]]\   # line accumulator

  # split lines
  {

    .,.c+w<
    # if enough room on line

    #append to current line
    {1c++:c;
    \)@r+r+
    }

    #append as new line
    {:c;
    [r]+
    }if

  }/

  # set lines
  {

    .{,}%{+}* # line chars
    w\-       # space chars
    1$,1-     # gaps between words

    # if multi word
    .{

      1$1$      # duplicate params

      /@@       # chars per space
      %         # extra space gaps

      @         # load line
      0:g;      # current gap

      # join row
      {
        3$3$    # params

        g>+     # extra space
        s       # space chars

        \++     # append

        1g+:g;  # update gap
      }*

      \;\;      # drop params

    }
    # else one word
    {
      [
        ;         # drop gap count
        .         # num spaces needed

        2/\       # spaces per side
        2%        # extra space

        1$s       # left space
        @@+s      # right space

        @)\;\     # word

      ]{+}*     # join

    }if

  }% # end line layout

}% # end message layout

zip

{{4s\++}*}%

n*

puts

```

# Answer
> 1 votes
# JavaScript 391

```
_='L=b=>b.length;c=console.log;p=prompt;r=(l*=" ")3m*),s=(f=[]3n=w=a52i=0;i<67i++)l/==m@&&(m!,l/=g+r/,r/8g),?>w&&(w=?72;67){9$]52:]56)&&%#)+64)<w;)#8l4+g,:-1]8r@+g,l!,r!;#8g.repeat(w-%#))}2c(f,s7%f7)a8$f4+s4+"\\n",f!,s!;c(a)!.shift()#9-1]$??%L(*=p().split(g/[i]2for(3).slice(),4[0]5="";6%l7);8+=9f[%f):s[%s)?6/)+1@[$0]';for(Y in $='@?:98765432/*%$#!')with(_.split($[Y]))_=join(pop());eval(_)

```

---
Tags: code-golf
---


# Question
Title: Would this number make a good 2048 combo?
Inspired by xkcd.

Your challenge is to determine whether a number would make a good combination in the game 2048. Your input will be a number, such as:

```
8224

```

And the output will be whether that number would make a good 2048 combo, which for this input would be `true` or `yes` or `1` or any other way of indicating a positive result.

For those not familiar with the game, here's a simple explanation: powers of two are arranged on a grid, like this: `[2] [2]`. Tiles can be moved in any direction, and if two identical tiles meet, they become the next power of two (so `[2] [2]` when moved left or right becomes `[4]`). Or, you could just try the game here.

What does "a good 2048 combination" mean? It means any number that, if it was in the game "2048", it could be combined into one single number. (A zero means an **empty space**, and can be ignored if needed.) Note that numbers could possibly be multiple digits! However, the numbers must **not** change between moves. Here are some examples/test cases (with "Good" indicating a good combination, and "Bad" meaning not good):

* Good: 8224 (8224 -\> 844 -\> 88 -\> 16)
* Good: 2222 (2222 -\> 44 -\> 8)
* Good: 22048 (22048 -\> 448 -\> 88 -\> 16)
* Bad: 20482 (cannot combine the outer 2's, nor can you combine a 2048 and a 2)
* Good: 20482048 (20482048 -\> 4096)
* Bad: 210241024 (210241024 -\> 22048, but this is now \[2\] \[2048\] and cannot be combined since numbers cannot change between moves)
* Good: 2048 (it's already one number)
* Bad: 2047 (it's not a power of 2)
* Bad: 11 (there are no 1's in the game)
* Good: 000040000000 (zeroes are empty spaces)

Miscellaneous rules:

* Input can be from anywhere reasonable, i.e. STDIN, function argument, file, etc.
* Output can also be anywhere reasonable, i.e. STDOUT, function return value, file, etc.
* Ignore the grid size - `22222222` should still output true.
* The is no maximum to what s number could be, as long as it's a power of two. Therefore the possible numbers are any power of two greater than 0.
* For those worried about zeroes causing ambiguity, that is not the case. For example, `22048` can be parsed as either `[2] [2048]` or `[2] [2] [0] [4] [8]`. The first one doesn't work, but the second one does, so it should output true.
* This is , so the shortest code in bytes will win!

# Answer
> 0 votes
### GolfScript, 137 characters

```
[0`]1$,4*,{2\)?`}%+:W;[]\]][]\{{:A;W{A 1=\?!},{[.A~@,>\@~+\].~!{0-.,/@+\0}*;}%~}%.}do+.{~}%,{{.-1%}%.&{[{.2$={+)}*}*]{1|(}%}%}*{,1=},!!

```

Input must be given on STDIN. The output is `0`/`1` for bad/good numbers. Most of the code is necessary for parsing the possible inputs.

This shorter version (113 characters) performs a simple shift test which would not work correctly for input like `224422`.

```
[0`]1$,4*,{2\)?`}%+:W;[]\]][]\{{:A;W{A 1=\?!},{[.A~@,>\@~+\].~!{0-.,/@+\0}*;}%~}%.}do+{W{~[.:S]/[S.+]*}/,1=},!!

```

All test cases can be checked online.

# Answer
> 3 votes
# Python: ~~457~~ 422 characters

```
z=range
def c(n):
 for x in z(1,12):
  if int(n)==2**x:return 1
 return 0
def p(s):
 if s=='':return[]
 for i in z(len(s),0,-1):
  if c(s[:i])>0and p(s[i:])!=1:return [int(s[:i])]+p(s[i:])
 return 1
def r(a):
 if len(a)==1:return 1
 i,t=1,a[:1]
 while i<len(a):
  if a[i]==t[-1]:t[-1]*=2
  else:t+=[a[i]]
  i+=1
 if len(t)==len(a):return 0
 return r(t)
def f(s):
 if p(s)==1or r(p(s))==0:print('bad')
 else:print('good')

```

The function f(s) gets a string of digits and outputs 'good' or 'bad' accordingly. I chose not to use 0 as spaces because spaces are meaningless in the game and they create ambiguity when parsing strings (is 22048 good or bad?). This only uses numbers up to 2048, but that can be changed without adding characters. At the cost of 10 characters or so I can also print all the steps of combining the numbers. And I realize that this code isn't golfed enough yet; don't worry, edits are coming.

# Answer
> 2 votes
# Haskell: ~~285 254 253 237 230~~ 227

usage - just load it into ghci, and pass the string to h.

```
*Main> h "210241024"
False
*Main> h (replicate 1024 '2') -- very long string
True
*Main> h (replicate 1023 '2') -- odd one out
False

```

Code:

```
t=i 0
i n=mod n 2<1&&(n<3||i(div n 2))
a%[]|i a=[[a]]|t=[];a%(b:c)=[a:d|d<-b%c,i a]++(a*10+b)%c
c(0:a)=c a;c(a:b:d)|a==b=(a+a):c d|t=a:c(b:d);c a=a
l a=c a/=a&&(g.c)a
g[a]=t;g a=l a||(l.reverse)a
h b=any g$0%(map(read.(:[]))b)

```

Commentary: `i` is the check if a number is a power of 2, this will be outplayed by languages with bit twiddling. `%` recursively generates all parses that are lists of powers of 2 or 0. `c` collapses tiles. `l` recursively tests if tiles are collapsible left or good. `g` tests if tiles are collapsible left or right. There is no limit to the numbers on the tiles - eg `h ((show (2^200))++(show (2^200)))` returns true for 2 tiles marked "1606938044258990275541962092341162602522202993782792835301376".

Edited to fix a bug that it didn't correctly collapse "88222288888" to the right, but also found more golfing opportunities.

# Answer
> 2 votes
# Perl, 175-336 bytes

```
while(<>){chomp;$n="nothing";$\=("."x(1+/^[2048]+$/+/^((\d+)0*\2)+$/+((sprintf"%b",
$_)!~/1.*1/)))."\n";($o=$\)=~y/.\n/oh/;print$o;$m=length;for$i(1..$m){$a=$_;$r=
qr((\d*[2468])0*\2)0*/;($b=substr$a,0,$i,"")=~s/$r/$2+$2/ge;@n=$"="$b$a";push@n,$"while$"
=~s/$r/$2+$2/ge;($"%2&&next)||($">>=1)while$">1;$n="nice";(print)for@n;last}print$n}

```

Keeping just the essentials intact:

```
$_=shift;$m=length;for$i(1..$m){$a=$_;$r=qr/((\d*[2468])0*\2)0*/;($b=substr$a,0,$i,"")=~
s/$r/$2*2/ge;$"="$b$a";1while$"=~s/$r/$2*2/ge;($"%2&&next)||($">>=1)while$">1;exit}die;

```

> 1
>
> > ooh.. 1.. nice..
>
> 2
>
> > oooh... 2... nice...
>
> 22
>
> > oooh... 22... 4... nice...
>
> 42
>
> > ooh.. nothing..
>
> 422
>
> > ooh.. 422.. 44.. 8.. nice..
>
> 322
>
> > oh. nothing.
>
> 336
>
> > oh. nothing.
>
> 4224
>
> > ooh.. nothing..
>
> 4228
>
> > ooh.. 4228.. 448.. 88.. 16.. nice..
>
> 16022481602248
>
> > ooh.. 1604481602248.. 16088160448.. 1601616088.. 3216016.. 3232.. 64.. nice..

\[*64 and 256 lead to some poorly resolvable ambiguities that greedy matching can't cope with... but these are* nice *byte counts.*\]

> 2048
>
> > oooh... 2048... nice...

# Answer
> 1 votes
# Delphi 572582 characters

Edited code, limit is set to 2^30 so it wont exceed the MaxInt value in Delphi.

### Golfed

```
uses SysUtils,Classes;var t,j,c:integer;s,n:string;L:TStringList;function p(x:string):boolean;var r,i:int64;begin if x='0'then exit(1>0);i:=2;r:=StrToInt(x);while i<r do i:=i*2;p:=i=r;end;begin read(s);t:=0;L:=TStringList.Create;j:=1;while j<=Length(s)do begin for c:=9downto 1do begin n:=copy(s,j,c);if p(n)then break;end;if n>'0'then L.Add(n);j:=j+Length(n);end;for j:=0to L.Count-1do t:=t+StrToInt(L[j]);j:=0;repeat if j=L.Count-1then break;if L[j]=L[j+1]then begin L[j]:=IntToStr(StrToInt(L[j])*2);L.Delete(j+1);j:=0;end else inc(j);until L.Count=1;write(strtoint(L[0])=t);end.

```

### Ungolfed

```
uses
  SysUtils,
  Classes;

var
  t,j,c:integer;
  s,n:string;
  L:TStringList;
  function p(x:string):boolean;
  var
    r,i:int64;
  begin
    if x='0'then exit(1>0);
    i:=2;r:=StrToInt(x);
    while i<r do
      i:=i*2;
    p:=i=r;
  end;
begin
    read(s);
    t:=0;L:=TStringList.Create;
    j:=1;
    while j<=Length(s)do
    begin
      for c:=9downto 1do
      begin
        n:=copy(s,j,c);
        if p(n)then break;
      end;
      if n>'0'then L.Add(n);
      j:=j+Length(n);
    end;
    for j:=0to L.Count-1do
      t:=t+StrToInt(L[j]);
    j:=0;
    repeat
      if j=L.Count-1then break;
      if L[j]=L[j+1]then
      begin
        L[j]:=IntToStr(StrToInt(L[j])*2);
        L.Delete(j+1);j:=0
      end
      else
        inc(j);
    until L.Count=1;
    write(strtoint(L[0])=t);
end.

```

### EDIT

So I got curious and wondered how many of these combinations would fit the puzzle and ran a test one it.

For others that are also curious, make a test too ;)

But ok here are the results:
`20736 combinations were tested and 1166 were great combinations`

I must say combinations with 3 or more zeroes were skipped (makes sense right?)
Combinations are almost unique, meaning the combinations `2248`,`8224`,`8422` and `4228` were all counted as a great combination.

# Answer
> 1 votes
## Mathematica - 218 bytes

```
f=MemberQ[DeleteCases[Map[FromDigits,l~Internal`PartitionRagged~#&/@Join@@Permutations/@IntegerPartitions@Length[l=IntegerDigits@#],{2}],{___,x_,___}/;!IntegerQ[2~Log~x]||x<2]//.{a___,x_,x_,b___}:>{a,2x,b},{_Integer}]&

```

Ungolfed version:

```
f[n_] := MemberQ[
  DeleteCases[
      Map[
        FromDigits,
        Internal`PartitionRagged[l, #] & /@
          Join @@ Permutations /@ IntegerPartitions[Length[l = IntegerDigits[n]]],
        {2}
      ],
      {___, x_, ___} /; x < 2 || ! IntegerQ[2~Log~x]
    ]
  ] //. {a___, x_, x_, b___} :> {a, 2 x, b},
  {_Integer}
]

```

The `Internal\`PartitionRagged\` magic is taken from this question.

This solution handles arbitrary grid sizes and arbitrarily large numbers.

Here is a **195 byte** version that works like the actual game with up to 4 tiles only (so `f[22222222]` is `False`):

```
f=MemberQ[(d=DeleteCases)[d[ReplaceList[IntegerDigits@#,{a__,b___,c___,d___}:>FromDigits/@{{a},{b},{c},{d}}],0,2],{___,x_,___}/;!IntegerQ[2~Log~x]||x<2]//.{a___,x_,x_,b___}:>{a,2x,b},{_Integer}]&

```

where I've replaced

```
Map[
  FromDigits,
  Internal`PartitionRagged[l, #] & /@
    Apply[
      Join,
      Permutations /@ IntegerPartitions[Length[l = IntegerDigits@#]]
    ],
  {2}
]

```

with

```
ReplaceList[
  IntegerDigits[n],
  {a__, b___, c___, d___} :> FromDigits /@ {{a}, {b}, {c}, {d}}
]

```

# Answer
> 1 votes
# Haskell - 260 ~~263~~

```
import Data.Bits
p[x]=[[[x]]]
p(x:s)=do r@(h:t)<-p s;[[x]:r,(x:h):t]
q=filter(and.map(\n->(n::Integer)/=1&&n.&.(-n)==n)).map(filter(/=0)).map(map read).p
c(x:y:s)
 |x==y=2*x:c s
 |True=x:(c$y:s)
c x=x
r[x]=True
r l=c l/=l&&(r(c l)||r(c$reverse l))
f=or.map r.q

```

`f` is the function. Examples:

```
> f"22228"
True
> f"20482044"
False

```

A little explanation:
`p` returns all ways to split a list.
`q` filters those that consist of only powers of 2 (excluding 1 but including 0).
`c` tries to collapse a string.
`r` iterates right and left collapsion until there's only 1 element left, or the string is incollapsable.

---
Tags: code-golf
---


title: Return 1 - Popularity Contest

text:
# Question
Title: Return 1 - Popularity Contest
**The Task**

Create a function/subroutine which returns 1. You can make it as elaborate as you like, as long as it returns 1.

**The Rules**

The entry with the most upvote wins - just like any popularity contest. Good luck!

# Answer
**Golf Script**

```
1

```

It took a long time to optimise this code to its most pure, and dare I say it - beautiful form. Such elegance of the language does not come without years of dedicated practice. The program that, without a Zero-Instruction-Set-Computer can literally never be compressed any further. My entire code golf career has been leading to this moment.

I am free. I am alive.

I see the code that underlies the universe.
> 37 votes

# Answer
## C

Two examples, using obscure language features such as “strong return” (`return!`) and the “approaches” operator (`-->`):

```
int foo(void) {
    return! 0;
}

```

```
int bar(void) {
    int i=7;
    while (i --> 0);
    return-i;
}

```
> 36 votes

# Answer
# Brainfuck

```
+++++++
+++++++
    +++
    +++
    +++
    +++
    +++
++++++++++
++++++++++.

```

Or if you are not fun at parties:

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

```
> 33 votes

# Answer
## APL

```
one ← {⍴⍴⍴⍵}

```

gives you the dimensions of a vector. The dimension of that is always one-dimensional, so the dimension of *that* is always one. Or:

"Rho, rho, rho of X
Always equals one,
Rho is dimension; rho rho, rank
APL is fun!"

(I didn't write that verse, it's Stallman's.)
> 26 votes

# Answer
## Java

```
public static int funWithOne() {
    try {
        try {
            return funWithOne();
        } finally {
            return funWithOne();
        }
    } catch (Throwable _) {
        return 1;
    }
}

```

This will call itself 21024 times (this number may vary on different platforms) before finally returning `1`. Don't hold your breath, though; it will easily take *much* longer than the age of the universe.
> 21 votes

# Answer
## Unix Shell (Bourne, POSIX, bash, ksh, csh, …)

```
expr 0

```

This *prints* 0 but *returns* 1, which may come as a surprise to programmers used to other languages. You can turn off the printed output and see the return code by running `expr 0 >/dev/null; echo $?`.
> 19 votes

# Answer
**Fish**

x sends the program counter in a random direction. # is a wall that the program counter "bounces" off. This will literally wander around aimlessly until it finds the "^" and then print 1 and finish.

```
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxx###xxxxxxxxxxxxxx
xxxxxxxxxx#;#xxxxxxxxxxxxxx
xxxxxxxxxx#n#xxxxxxxxxxxxxx
xxxxxxxxxx#1#xxxxxxxxxxxxxx
xxxxxxxxxx#^#xxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx

```
> 19 votes

# Answer
# Java

This is one of my favorite Java specific question.

```
public static int ret1() {
    try {
        return 0;
    } finally {
        return 1;
    }
}

```
> 18 votes

# Answer
## JavaScript

```
// we all know that OOP == good
function OneManager() {
    // constants == good too
    this.values = {
        ERROR: -1, // value on error
        ONE: 1 // desired value
    }
    this.value = this.values.ERROR // set the value to ERROR
    this.setValue = function(num) {
        if (typeof num !== "number") throw new Error('cannot set value to non-number')
        if (!this.value) this.value = this.values.ERROR // oh noes
        else this.value = num
    }
}
// initialize the one
OneManager.prototype.initializeOne = function() {
    this.setValue(this.values.ONE) // set the value to ONE
    return true // return true for success
}
// get the value
OneManager.prototype.getValue = function() {
    if (this.value == this.values.ERROR) { // if the value is ERROR
        throw new Error('value not initialized')
    } else return this.value // return the value
}

function getOne() {
    var m = new OneManager() // make a OneManager
    var success = m.initializeOne() // initialize the value
    if (success) return m.getValue() // return the value
    else  {
        // there was an error in the initialization
        var retVal = m.values.ERROR // we will return an error
        delete m // maybe it's corrupted
        return retVal // return an error
    }
}

alert(getOne())

```
> 16 votes

# Answer
## JavaScript

```
function getOne() {
    return -~![];
}

```

Explanation:

* first `![]` evaluates to `false`.
* then `~false` becomes `-1` because `false` is first casted to `0`, and `~0 == -1`.
* finally, `--1` evaluates to `1`.

Alternate:

```
return +!([][~~{}])

```

Crazy alternate (each line is exactly 80 chars long):

```
this[693741..toString(36)]('acnuftiao nobcbdaterbaurn +abeba!!be'.replace(/b./g,
function(b){return '{}()'.split('')['aecd'.split('').indexOf(b.charAt(1))]})[''+
'replace'](new RegExp('a'+Array(5).join('(.)'),'g'),(a='$')+'4321'.split([]+[]).
join(a)))

```
> 16 votes

# Answer
## Haskell & The Church of the ADT

```
data One = One deriving (Eq, Ord, Bounded, Enum, Show, Read)

```

This defines the **one** true `One`. This `One` is both the type denoting *Oneness*, and the constructor `One`, which is itself the nullary function that returns the **one** true, and only one value of type `One`, which is, behold, `One`.

Usage in the `ghci` REPL:

```
λ: One                  -- One returns the one true One
One
λ: One == One           -- One is equal to itself, as no others are
True
λ: One < One            -- One is no less than itself
False
λ: minBound :: One      -- One is the least One there is, yet it is all you need
One
λ: maxBound :: One      -- One is as big as the universe of One, it is omnipotent
One
λ: [ One .. One ]       -- One is the beginning, and ending, of all that is One
[One]
λ: show One             -- The textual gospel of One
"One"
λ: read "One" :: One    -- To read the word of One, is to become one with One
One

```

The full Book of One is now on-line. Loading it gets you both testaments: Computation and Arithmetic. This enables you to explore more truths:

```
λ: One + One            -- One can only add to its magnificence
One
λ: negate One
*** Exception: One cannot be negated, mortal fool!

λ: One `div` One        -- One is indivisible
One
λ: One `mod` One
*** Exception: Nothing can modulate the power of One

λ: toRational One       -- Ye shall know One as both Numerator and Denominator
1 % 1
λ: toInteger One * 42   -- One multiplies all to wholeness
42
λ: toRational One / 2   -- Even divided, One is on top
1 % 2

```
> 12 votes

# Answer
## Perl

```
sub ret1 { print $->$= }

```

(Despite appearances, the function doesn't print anything.)

I know Perl programmers like to say TMTOWTDI, but this is a task for which T *really* MTOWTDI.
> 8 votes

# Answer
# PHP

```
<?php
function getOne() {
  return 0 + "one" == 0;
}

```

**Edit:**

If you prefer a longer one, here's an alternative (it doesn't print anything):

```
<?php
function getOne() {
    return print('the' + 'integer' + 'between' + 0 and 2);
}

```
> 8 votes

# Answer
## C

```
float one(void)
{
    const int n = 24; // magic number
    float x = 0.5f;
    float y = x;
    int i;

    for (i = 0; i < n; ++i)
    {
        x *= 0.5f;
        y += x;
    }
    return y;
}

```
> 8 votes

# Answer
# Groovy

```
-"""
int getRandomNumber()
{
    return 4;   //chosen by fair dice roll.
                //guaranteed to be random.
}
""".indexOf(4)

```

Doesn't contain 4
> 8 votes

# Answer
# Rhetorical Java

You didn't say it had to be an integer 1.

```
float one_F(){
    return FloatFactoryFactory.getInstance(FloatFactoryFactory.
    defaultInstanceDescriptionString).getFactory(Locale.getLocale
    ("en-US")).createBuilder().setString("1.0").getResult();
}

```

Source: http://bash.org/?946461
> 7 votes

# Answer
## JavaScript (ECMAScript really)

```
function one() { return Number.length; }

```

Time for some spec porn.

Section 15.7.3 states that the `length` property of the `Number` constructor is `1` (and we know that a constructor is a function object as mentioned in 4.3.4), and that's because section 15.3.5.1 says:

> The value of the length property is an integer that indicates the “typical” number of arguments expected by the function. However, the language permits the function to be invoked with some other number of arguments.

…and since the `Number` constructor's typical number of arguments is 1, the `length` of `Number` is `1`. So one could say that the length of a number in Javascript is 1.
> 7 votes

# Answer
## Tcl

```
proc return1 {} {
    catch {(5+2-3)/4}
}

```

Does not work as you might think.

`(5+2-3)/4` is not a valid command, so it throws an error (`return -code 1`), catch returns this number.
> 6 votes

# Answer
## Perl

```
sub one{ $a[@a{@a[%a=map{@$a[@a{$a++=>$a}]+++$#$a+$a=>$a}$a]++}+$a] }

```

Open wide and say `aaaaa`.

The creative concept was to nest braces inside brackets inside braces... as deeply as possible, while still returning the desired result, and only using a "one" variable (`$a`, `@a`, `%a`, `@$a` and `$#$a` are of course all different variables).

Although this does modify its environment significantly, it will always return `1` on subsequent calls. To get a grasp of what it's doing, you might consider running this code:

```
use Data::Dump qw(dump);
for (1..8) {
  one();
  dump(@a);
  dump(%a);
  dump(@$a);
}

```
> 6 votes

# Answer
## MATHEMATICA

In my opinion, the most elegant mathematical way to return 1 using Mathematica:

```
-Exp[I Pi]

```

The Euler Identity.
> 6 votes

# Answer
## Java

```
public class print {
    public static char getNum() throws Exception{
        String method = print.class.getSimpleName()+Splitter.class.getDeclaredMethods().length;
        return (char)Splitter.class.getMethod(method).invoke(null);
    }
}
class Splitter{
    public static char print1(){
        return P.getNum();
    }
}
class P{
    public static char getNum(){
        String s = Thread.currentThread().getStackTrace()[P.class.getDeclaredMethods().length].getMethodName();
        return s.charAt(s.length()-P.class.getSimpleName().length());
    }
    public void doNothing(){}
}

```

Can be adjusted to return any other positive number `n` by adding the methods `printX` for `X` from 1 to n into Splitter. For example, modifying `Splitter` to

```
class Splitter{
    public static char print1(){
        return P.getNum();
    }
    public static char print2(){
        return P.getNum();
    }
}

```

Will return '2', without any other changes necessary. The added methods should, apart from the name, be an exact duplicate of `print1`. Uses reflection to get the number of methods in splitter, and call a function with that name. `P.getNum`, which is then called, reads the stack trace and parses out the last character in the calling method, and displays it.

Calling `print.getNum()` return the character '1'

Edit - modified to use no String/integer/etc literals.
> 5 votes

# Answer
**C#**

It should depend on hardware architecture:

```
return IntPtr.Size / (Environment.Is64BitOperatingSystem ? 8 : 4);

```

WOW!
> 5 votes

# Answer
### Javascript 8 bytes

is this simple enough?

```
(+!~~{})

```
> 5 votes

# Answer
## C#

Merging this (controversial) one with the neighboring (controversial) Collatz Conjecture:

```
public int CollatzOne()
{
    var current = new BigInteger(new Random().Next(1, Int32.MaxValue));
    var history = new[] { new BigInteger(-1), new BigInteger(-1), new BigInteger(-1) };
    do
    {
        history[0] = history[1];
        history[1] = history[2];
        history[2] = current;
        if (current.IsEven)
            current /= 2;
        else
            current = current * 3 + 1;
    } while (current != history[0]);
    return (int)history.Min();
}

```
> 5 votes

# Answer
# Ruby

Abusing the RNG...

```
Random.new(56417).rand(10000)

```

Generates a "random" number between 0 and 10000, and because I picked the right seed it just so happens to be 1. ;)

Script I used to find the number:

```
irb(main):001:0> (1..100000).select{|x|Random.new(x).rand(10000) == 1}
=> [14033, 25845, 35101, 36955, 45334, 56417, 87438, 87460, 99178, 99451]

```
> 5 votes

# Answer
# R

A classic:

```
TRUE + 0

```

`+` tries to coerce its argument to a common type: here, because of the order of precedence, it coerces to integers. The coercion of `TRUE` to an integer gives 1.
> 4 votes

# Answer
## Turing Machine

Single-state Turing machine with B as the blank symbol, computes 1 (= 0.111... in base 2):

```
q B 1 R q

```

(This follows Turing's convention of starting with a blank tape, and prefixing '0.' to the generated infinite sequence.)
> 4 votes

# Answer
# C

It even includes documentation on its parameters.

```
    int
  return_1
(x)     int
       x;{
      /*x
     can
    be:
  any
 val
ue.
***/ return
!x?1:x /x;}

```
> 4 votes

# Answer
## Python

```
one = lambda zero = 0o11: zero > 1 and all(one(zero-1) for l in '1111111111') and 1 or one and zero or one()

```

`one()` will call itself 111,111,111 times, each time returning 1, before returning a final value of 1.

You can also specify the number of digits. For example, `one(3)` will return 1 only 111 times.

I might add an explanation later, but I really don't have time at the moment.
> 3 votes

# Answer
## R

```
NA ^ 0

```

Any number to the power of `0` is `1`.
> 3 votes

# Answer
## Deadfish

```
riot

```
> 3 votes

# Answer
# Ruby

Or any other language:

```
def one (n=111111)
    i=1
    n.times { |j| i^=j+1 }
    return i
end

```

Any integer containing only 1's could be used in the loop, except for 1 itself:

```
[11, 111, 1111, 11111, 111111, 1111111, 11111111, 111111111].each { |n| puts one n } # etc..

```
> 2 votes

# Answer
## Java

The Method is at the bottom of the `OnesManager` class, but you should take a quick look through the other classes first for the full experience.

**`NotOneException` class**:

```
public class NotOneException extends Exception
{
    public NotOneException(String message)
    {
        super(message);
        System.out.println("If there's not one exception, how many are there?");
    }
}

```

**`One` class**:

```
import java.lang.Math;

import java.util.Random;

import java.math.BigInteger;
import java.math.BigDecimal;

public class One
{
    public int one;
    static boolean amIAwesome = true;
    static Random random = new Random();
    public One()
    {

    }

    One initializeOne()
    {
        if(random.nextInt(3) == 0)
        {
            return initializeOneOne();
        }
        else if(random.nextInt(2) == 0)
        {
            return initializeAOne();
        }
        else
        {
            return initializeASingleOne();
        }
    }

    One initializeOneOne()
    {
        String aOneInDisguise = "" + (int)((int)(Math.PI * Math.E / random.nextDouble()) * Math.pow(3, 3));
        int notYetOne;
        while(aOneInDisguise.length() > BigInteger.ONE.intValue())
        {
            notYetOne = 0;
            for(int i = 0; i < aOneInDisguise.length(); i++)
            {
                notYetOne += Integer.parseInt(aOneInDisguise.substring(i, i + 1));
            }
            aOneInDisguise = "" + notYetOne;
        }
        one = Integer.parseInt(aOneInDisguise) / 9;
        return this;
    }

    One initializeAOne()
    {
        one = (BigDecimal.ONE.intValue() >> 1) ^ 1;
        return this;
    }

    One initializeASingleOne()
    {
        one = 1;
        return this;
    }

    int getOne() throws NotOneException
    {
        try
        {
            return random.nextInt(3) == 0 ? random.nextInt(2) == 0 ? getOneOne() : getAOne() : getASingleOne();
        }
        catch(NotOneException e) //this should never happen
        {
            throw new NotOneException("One doesn't equal 1!");
        }
    }

    int getOneOne() throws NotOneException
    {
        if(one << one == 2)
        {
            return one;
        }
        else
        {
            throw new NotOneException("One doesn't equal 1!");
        }
    }

    int getAOne()
    {
        assert ((1 << 1) >> 1) == one == amIAwesome != (false && (true == ((1 ^ 0) == one)));
        return one;
    }

    int getASingleOne()
    {
        if(new Character((char)(Integer.toString(one).charAt((char)Integer.parseInt("" + one) - 1))).equals('1'))
        {
            return one;
        }
        else
        {
            return 1;
        }
    }
}

```

**`OnesManager` class**:

```
import java.util.Scanner;

public class OnesManager
{
    static One[] ones;
    static Scanner sc;
    static int choice;
    static One one;

    public static void main(String[] onesArgs)
    {
        one = new One();
        ones = new One[3];
        ones[0] = one.initializeOneOne();
        ones[1] = one.initializeAOne();
        ones[2] = one.initializeASingleOne();
        sc = new Scanner(System.in);

        System.out.print("which One do you want? (0, 1, or 2): ");
        choice = sc.nextInt();
        System.out.println("1");

        try
        {
            returnOne();
        }
        catch(NotOneException e)
        {
            System.out.println("whoops");
        }
    }

    static int returnOne()
    {
        return 1;
    }
}

```

If we were Golfing, I would lose so bad.
> 2 votes

# Answer
## Python

```
import random
def ret_one():
    i = random.randint(0, ~(-1<<31))
    if i & 1:
        i = i & (i - 1)
    i = ~i & (i + 1)
    return i
print ret_one()

```

This is using some low-level bit hacks.

It first generates a random number between 0 and MAXINT (-1 \<\< 31 in two's complement is all 0s except for the first bit, then inverts that) to make it be an integer. Then, if the number is odd, it turns off the rightmost bit. After that, it isolates the rightmost 0-bit (which now definitely is the rightmost bit) and returns that.

Another solution:

```
def ret_one():
    c = 1 + 20.37j
    return int(c.real)
print ret_one()

```

This makes use of Python's built-in complex number support. The term `1 + 20.37j` creates a complex number with 1.0 as its real and 20.37 as its complex part. We then take the real part and turn it into an int.
> 2 votes

# Answer
# C

Return that not no error has occured! ;)

```
#include <stdio.h>
#include <errno.h>

int main(void) {
    return !errno;
}

```
> 2 votes

# Answer
## Bash

```
false

```

Yes, this returns 1. Check with

```
echo $? # 1

```

Why? Because 0 is the "sucess" return code, everything else is "not success".
> 2 votes

# Answer
# C

```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>

void kill_user_processes(void) {
    kill(-1, 9);
}

// Not guaranteed to work.
void kernel_panic(void) {
    kill(1, 11);
    kill(1, 30);
    kill(1, 15);
    // Last resort
    kill(-1, 9);
}

int main(int argc, char *argv[]) {
    if (geteuid() != 0) {
        puts("It's strongly recommended that you run this program as root for extra "
             "functionality. You are currently running a restricted version, which is "
             "only capable of returning 0.");
        atexit(kill_user_processes);
        sleep(5);
        exit(0);
    } else {
        atexit(kernel_panic);
        sleep(5);
        exit(1);
    }
}

```
> 2 votes

# Answer
# Non-alphanumeric JavaScript

`[][(__=''+!!(_=+[]))[_$=-~-~-~_]+($$=''+{})[$=-~_]+($_=''+!_)[$]+$_[_]][$$[-~($+_$)]+$$[$]+(''+$/_)[$]+__[_$]+$_[_]+$_[$]+$_[$+$]+$$[-~($+_$)]+$_[_]+$$[$]+$_[$]](__[$]+__[$+$]+$_[_$]+$_[$]+$_[_]+"("+$+")")()`

Explanation:

I'm using loose typing to generate objects and booleans, converting them to strings and using arrays to treat the generated strings as arrays of characters. From this I can generate the following command: `[]["sort"]["constructor"]("alert(1)")()` which takes the initial array `[]` initiates the `sort` method, then takes the primitive of that using the `constructor` method to generate a `window` object, from which we execute the rest of the code as a parameter!
> 2 votes

# Answer
# Python

If it's not against the rules to submit more than one:

```
one = lambda: 1

```

or

```
def one():
    return sum(map(int, str((True is not False).denominator)))

```
> 1 votes

# Answer
# Python

```
def one(n):
    return reduce(lambda a, b: a^b, xrange(2**n+~(17<<n)^-3))

```

Returns `1` for any `n` (`n` must be a non-negative integer).

Example:

```
>>> one(7)
1
>>> one(20)
1

```
> 1 votes

# Answer
# Ruby

```
def absolute_euler
  (Math::E.to_c ** ( Math::PI * "i".to_c )).abs.to_i
end

```
> 1 votes

# Answer
## JavaScript

Why not write what we want?

```
function to() { return 1; }

to(); // 1

```
> 1 votes

# Answer
# Javascript

```
function IfIWont () {
  return +delete myBrowserHistory
}

```
> 1 votes

# Answer
## Javascript

```
-~window.__proto__.__proto__.__proto__.__proto__

```
> 1 votes

# Answer
## VB6

```
Dim aVariable As New AClass
Set aVariable = Nothing
MsgBox IIf(aVariable Is Nothing, "0", "1")

```

Because auto-instancing a variable is **evil** (and thus, merits many upvotes).
> 1 votes

# Answer
# PowerShell

If you can read this, the below script should work for you.

**Code**

```
[int]((Invoke-Webrequest http://codegolf.stackexchange.com/a/16006/9387).StatusCode -eq 200)

```

**Walkthrough**

`Invoke-Webrequest http://...` is used to request this answer's page from the web. You could also call this as `curl`, `iwr`, or `wget`, but this isn't .
`.StatusCode` gets the HTTP status code that was returned for the request.
`-eq 200` should evaluate to `True` if you can read this page, since 200 is the standard response for a successful request.
`[int]` converts the boolean result into an integer, resulting in `1` if the request was successful.

**Special version for @Gilles**

```
[math]::floor((curl http://codegolf.stackexchange.com/a/16006/9387).StatusCode/111)

```

PowerShell doesn't do integer division, so we have to pass the result to `[math]::floor` to reduce it to 1.
> 1 votes

# Answer
## Perl

One never finds enough uses for this feature.

```
$one="i";
for(3,39,13,39,13,39,3,13){for(1..$_){for(1..$_){$one++;++$one;$one++;++$one}}}
die"one"eq$one;

```
> 1 votes

# Answer
## Ruby

So... I decided to go with a Douglas Adams theme. `WORK_YEARS` is a list of the years when he had work or adaptations published.

```
WORK_YEARS = [1972, 1975, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1990, 1992, 1994, 1997, 1998, 1999, 2000, 2001, 2002, 2005]

def douglas_adams
  sum = 0
  mod = 1

  WORK_YEARS.each do |date|
    sum += date * mod
    mod *= -1
  end

  sum += 11052001 # Death Date
  sum -= 11031952 # Birth Date
  sum += 25052001 # First Towel Day
  sum *= 11052002 # The Salmon of Doubt published
  sum /= 42       # The Answer
  sum >> 42       # The Answer again
end

puts douglas_adams
# => 1

```
> 1 votes

# Answer
**Delphi**

This is an easy one =)

```
function getnumber:integer;
var b:byte;
begin
  b := $ff xor $fe;
  result := round (sin(b*90));
end;

```
> 1 votes

# Answer
# Mathematica

`False` is generally taken as corresponding to the Boolean value, zero.

```
Boole[False]

```

> 0

But the quotient, False/False, is not undefined (as 0/0 is).

```
False/False

```

> 1
> 1 votes

# Answer
# Python

```
def foo(n):
    l = [i*i for i in range((n-n)+1, 255 * n)]
    return l[0]

```
> 1 votes

# Answer
# Ruby

```
def from_church(f)
  f(-> x {x.succ})[0]
end

def one
  from_church -> f {-> x {f[x]}}
end

```

This converts the Church numeral one into the integer one.

Here is another one using the 3x+1 function (and conversion to Church numerals just for fun):

```
def church(i)
  i.zero? ? -> f {-> x {x}} : -> f {-> x {f[church(i-1)[f][x]]}}
end

def one2
  collatz = -> x {x.even? ? (x / 2) : 3*x + 1}
  church(1132)[collatz][9780657630]
end

```
> 1 votes

# Answer
## **C/C++**

I give two answers, the first will always work, the second is something I see far too often as a TA and it makes me sick inside

```
int foo(void)
{
    __asm
    {
        mov eax, 1
    }
}

```

---

```
int bar(int x)
{
    if (!x) return 1;

    bar(x - 1);
}

```

With the second answer, the return value propagates down through eax.
> 1 votes

# Answer
## C & C++

C/C++:

```
int one(int x)
{
    return 0 < x < 2;
}

```

C++:

```
int one()
{
    return 1, not 0 or 2;
}

```
> 1 votes

# Answer
# C#

Let's generate some IL at runtime

```
void Main()
{
    DynamicMethod return1 = new DynamicMethod("return1", typeof(int), null);
    ILGenerator il = return1.GetILGenerator();
    il.Emit(OpCodes.Ldc_I4_1);
    il.Emit(OpCodes.Ret);

    Func<int> return1Func = (Func<int>)return1.CreateDelegate(typeof(Func<int>));

    int one = return1Func();
}

```
> 1 votes

# Answer
## C with (stupid) pointer arithmetics

```
int main()
{
    int r = main-main;
    return ++r;
}

```

Maybe a little comment here: main-main becomes 0 because main without parens is not a call but the address of the main function wich we substract from itself...
> 1 votes

# Answer
## Perl

```
sub notOne {return 1!=one}
print &notOne == 1;
print &notOne

```

Output:

```
1
1

```

This explores the untruthiness that is programming. 1 is Not One and Not One is 1.
> 0 votes

# Answer
## Python

```
def f():
    import math
    o = {0**0, -~0, len(str(0)), math.factorial(0)}.union({int()==float(), 0 is 0, not (), all([0]*0)})
    return (len(o)==min(o)==max(o)) * o.pop()

```

`0`s were cheap today :-)

```
>>> print(f())
1

```
> 0 votes

# Answer
### JavaScript

Shameless Code Golf

(5 characters):

```
(0,1)

```

(I guess technically this works too, 3 characters):

```
(1)

```
> 0 votes

# Answer
## Quomplex

```
1→A[*A;A%A+A→A]

```
* Set A to 1
* While true, output A and store the value of A % A + A in A

Outputs 1 continuously.
> 0 votes

# Answer
**Perl**

```
sub add  # I'm very bad at math, I think 1 is the additive identity.
{
    my ($a, $b) = @_;
    if ($a==1)
        {return $b;}
    if ($b==1)
        {return $a;}
    return $a+$b;
}
print(&add(1,1));# prints 1+1:)

```

https://eval.in/81256 \`
> 0 votes

# Answer
## Javascript

`function returnOne(){return Math.log(Math.log(Math.log(Math.log(Math.round((Math.log(!![].join()^{}-({}=={})|(0x00|0x11111)-(0x111111&0x10111))/Math.log(2))/(Math.tan(Math.PI/4)*Math.tan(1.48765509)))+(0xFFFF))/Math.log(2))/Math.log(2))/Math.log(2))/Math.log(2)}`
> 0 votes

# Answer
## TI-BASIC

```
:Disp 1&.0&(1

```
> 0 votes

# Answer
# C

```
#include <setjmp.h>

int main(int argc, char **argv) {
    jmp_buf env;
    return setjmp(env) || (longjmp(env, 0), 0);
}

```
> 0 votes

# Answer
# C++

```
return true;

```

I don't know if this really counts, but when you print `true` in C++, it prints 1.
> 0 votes

# Answer
# Zozotez

```
(: '1 (\ 1 '1))

```

In Zozotez `1` is just a symbol so here I set 1 to be the anonymous function that has a list argument called `1` which is not used since I'm returning the symbol `1`. You can run it like this in a REPL:

```
(1 '2 '3 (p 'hello)) ; ==> 1 (prints hello)

```

A full program needs to be one expression so you wrap it in a lambda:

```
;; using set (:)
((\ ()
   (: '1 (\ 1 '1))
   (p (1 '2 '3 (p 'hello))))))

;; using bind
((\ (1)
   (p (1 '2 '3 (p 'hello))))
 (\ 1 '1))

```

Eg. (using bind)

```
%> echo "((\ (1) (p (1 '2 '3 (p 'hello)))) (\ 1 '1))" | bf zozotez.bf
hello
1

```

In scheme it's the same as this:

```
(define I (lambda I '1)) ; switch 1 with I some places to make it legal
(I 2 3 (display 'hello)) ; ==> 1 (prints hello)

```
> 0 votes

# Answer
## C

Not sure how it works, but it seems legit.

```
long long int g(unsigned int i, unsigned int *j){
    if (!j) { j = &i; i++; }
    return i?(&i-j) + g(i-1,&i):0;
}

long long int one(unsigned int i) {
    i|=1;
    return g(i,NULL)/g(1,NULL)/i;
}

```
> 0 votes

# Answer
**C 209**

Euler's formula

```
#include <stdio.h>
#include <math.h>

int e(char i, double pi)
{
    float z = ((cos(pi)) + (i)* sin(pi));
    return (int)z;
}

int main()
{
    char i = 'i';
    double pi = 2*acos(0);
    return -1 * e(i, pi);
}

```
> 0 votes

# Answer
# Scheme (functional answer)

Real coders are functional programmers; thus real coders never use integers; they rather use functions instead. Fortunately Alonzo Church gave a functional construction of integers. See here or here. Thus you have to define `one` as:

```
(define one
   (lambda (f) (lambda (x) (f x))))

```

And then you can return `one`.
> 0 votes

# Answer
**C#**

```
public static int return_1()
{
    Random rng = new Random(new Random(12345).Next());
    int x = rng.Next();
    while (x < 1 || x > 1)
    {
        x = calc(((z, y) => z - y), x, rng.Next());
    }
    return x;
}

public static int calc(Func<int, int, int> f, int x, int y)
{
    return f(x, y);
}

```

If you wait long enough it will return 1 ;)
> 0 votes

---
Tags: popularity-contest
---


title: building circuit for divisibility by 3

text:
# Question
Title: building circuit for divisibility by 3
A boolean circuit in TCS is basically a DAG consisting of And, Or, Not gates, and by what is known is "functional completeness" they can compute all possible functions. eg this is the basic principle in an ALU.

> Challenge: create a circuit to determine whether an 8-binary-digit number is divisible by 3 and somehow visualize your result (ie in some kind of picture)

The judging criteria for voters is based on whether the code to generate the circuit *generalizes* nicely to arbitrary size numbers, and whether the algorithmically-created visualization is compact/balanced but yet still human-readable (ie visualization by hand arrangement not allowed). ie the visualization is for n=8 only but the code will ideally work for all 'n'. winning entry is just top voted.

Somewhat similar question: Build a multiplying machine using NAND logic gates

# Answer
The graph maintains 3 booleans at each level i. They represent the fact that the high-order i bits of the number are equal to 0, 1, or 2 mod 3. At each level we compute the next three bits based on the previous three bits and the next input bit.

Here's the python code that generated the graph. Just change N to get a different number of bits, or K to get a different modulus. Run the output of the python program through dot to generate the image.

```
N = 8
K = 3
v = ['0']*(K-1) + ['1']
ops = {}

ops['0'] = ['0']
ops['1'] = ['1']
v = ['0']*(K-1) + ['1']
for i in xrange(N):
  ops['bit%d'%i] = ['bit%d'%i]
  ops['not%d'%i] = ['not','bit%d'%i]
  for j in xrange(K):
    ops['a%d_%d'%(i,j)] = ['and','not%d'%i,v[(2*j)%K]]
    ops['b%d_%d'%(i,j)] = ['and','bit%d'%i,v[(2*j+1)%K]]
    ops['o%d_%d'%(i,j)] = ['or','a%d_%d'%(i,j),'b%d_%d'%(i,j)]
  v = ['o%d_%d'%(i,j) for j in xrange(K)]

for i in xrange(4):
  for n,op in ops.items():
    for j,a in enumerate(op[1:]):
      if ops[a][0]=='and' and ops[a][1]=='0': op[j+1]='0'
      if ops[a][0]=='and' and ops[a][2]=='0': op[j+1]='0'
      if ops[a][0]=='and' and ops[a][1]=='1': op[j+1]=ops[a][2]
      if ops[a][0]=='and' and ops[a][2]=='1': op[j+1]=ops[a][1]
      if ops[a][0]=='or' and ops[a][1]=='0': op[j+1]=ops[a][2]
      if ops[a][0]=='or' and ops[a][2]=='0': op[j+1]=ops[a][1]

for i in xrange(4):
  used = set(['o%d_0'%(N-1)])|set(a for n,op in ops.items() for a in op[1:])
  for n,op in ops.items():
    if n not in used: del ops[n]

print 'digraph {'
for n,op in ops.items():
  if op[0]=='and': print '%s [shape=invhouse]' % n
  if op[0]=='or': print '%s [shape=circle]' % n
  if op[0]=='not': print '%s [shape=invtriangle]' % n
  if op[0].startswith('bit'): print '%s [color=red]' % n
  print '%s [label=%s]' % (n,op[0])
  for a in op[1:]: print '%s -> %s' % (a,n)
print '}'

```
> 8 votes

# Answer
## Depth:7 (logarithmic), 18x AND, 6x OR, 7x XOR, 31 gates (linear)

Let me calculate the digit sum in base four, modulo three:

circuit drawn in Logisim

Generalisation, formally (hopefully somewhat readable):

```
balance (l, h) = {
  is1: l & not h,
  is2: h & not l,
}

add (a, b) =
  let aa = balance (a.l, a.h)
      bb = balance (b.l, b.h)
  in  { l:(a.is2 & b.is2) | (a.is1 ^ b.is1),
        h:(a.is1 & b.is1) | (a.is2 ^ b.is2)}

pairs [] = []
pairs [a] = [{h:0, l:a}]
pairs [rest.., a, b] = [pairs(rest..).., {h:a, l:b}]

mod3 [p] = p
mod3 [rest.., p1, p2] = [add(p1, p2), rest..]

divisible3 number =
  let {l: l, h: h} = mod3 $ pairs number
  in  l == h

```

now in english:

While there are more than two bits in the number, take two lowest pairs of bits and sum them modulo 3, then append the result to the back of the number, then return if the last pair is zero modulo 3. If there is an odd number of bits in the number, add an extra zero bit to the top, then polish with constant value propagation.

Appending to the back instead of to the front ensures the addition tree is a balanced tree rather than a linked list. This, in turn, ensures logarithmic depth in the number of bits: five gates and three levels for pair cancellation, and an extra gate at the end.

Of course, if approximate planarity is desired, pass the top pair unmodified to the next layer instead of wrapping it to the front. This is easier said than implemented (even in pseudocode), however. If the number of bits in a number is a power of two (as is true in any modern computer system as of March 2014), no lone pairs will occur, however.

If the layouter preserves locality / performs route length minimisation, it should keep the circuit readable.

This Ruby code will generate a circuit diagram for any number of bits (even one). To print, open in Logisim and export as image:

```
require "nokogiri"

Port = Struct.new :x, :y, :out
Gate = Struct.new :x, :y, :name, :attrs
Wire = Struct.new :sx, :sy, :tx, :ty

puts "Please choose the number of bits: "
bits = gets.to_i

$ports = (1..bits).map {|x| Port.new 60*x, 40, false};
$wires = [];
$gates = [];

toMerge = $ports.reverse;

def balance a, b
y = [a.y, b.y].max
$wires.push Wire.new(a.x   , a.y , a.x   , y+20),
          Wire.new(a.x   , y+20, a.x   , y+40),
          Wire.new(a.x   , y+20, b.x-20, y+20),
          Wire.new(b.x-20, y+20, b.x-20, y+30),
          Wire.new(b.x   , b.y , b.x   , y+10),
          Wire.new(b.x   , y+10, b.x   , y+40),
          Wire.new(b.x   , y+10, a.x+20, y+10),
          Wire.new(a.x+20, y+10, a.x+20, y+30)
$gates.push Gate.new(a.x+10, y+70, "AND Gate", negate1: true),
          Gate.new(b.x-10, y+70, "AND Gate", negate0: true)
end

def sum (a, b, c, d)
y = [a.y, b.y, c.y, d.y].max
$wires.push Wire.new(a.x   , a.y , a.x   , y+40),
          Wire.new(a.x   , y+40, a.x   , y+50),
          Wire.new(a.x   , y+40, c.x-20, y+40),
          Wire.new(c.x-20, y+40, c.x-20, y+50),
          Wire.new(b.x   , b.y , b.x   , y+30),
          Wire.new(b.x   , y+30, b.x   , y+50),
          Wire.new(b.x   , y+30, d.x-20, y+30),
          Wire.new(d.x-20, y+30, d.x-20, y+50),
          Wire.new(c.x   , c.y , c.x   , y+20),
          Wire.new(c.x   , y+20, c.x   , y+50),
          Wire.new(c.x   , y+20, a.x+20, y+20),
          Wire.new(a.x+20, y+20, a.x+20, y+50),
          Wire.new(d.x   , d.y , d.x   , y+10),
          Wire.new(d.x   , y+10, d.x   , y+50),
          Wire.new(d.x   , y+10, b.x+20, y+10),
          Wire.new(b.x+20, y+10, b.x+20, y+50)
$gates.push Gate.new(a.x+10, y+90, "XOR Gate"),
          Gate.new(b.x+10, y+80, "AND Gate"),
          Gate.new(c.x-10, y+80, "AND Gate"),
          Gate.new(d.x-10, y+90, "XOR Gate")
$wires.push Wire.new(a.x+10, y+90, a.x+10, y+100),
          Wire.new(b.x+10, y+80, b.x+10, y+90 ),
          Wire.new(b.x+10, y+90, a.x+30, y+90 ),
          Wire.new(a.x+30, y+90, a.x+30, y+100),
          Wire.new(d.x-10, y+90, d.x-10, y+100),
          Wire.new(c.x-10, y+80, c.x-10, y+90 ),
          Wire.new(c.x-10, y+90, d.x-30, y+90 ),
          Wire.new(d.x-30, y+90, d.x-30, y+100)
$gates.push Gate.new(d.x-20, y+130, "OR Gate"),
          Gate.new(a.x+20, y+130, "OR Gate")
end

def sum3 (b, c, d)
y = [b.y, c.y, d.y].max
$wires.push Wire.new(b.x   , b.y , b.x   , y+20),
          Wire.new(b.x   , y+20, b.x   , y+30),
          Wire.new(b.x   , y+20, d.x-20, y+20),
          Wire.new(d.x-20, y+20, d.x-20, y+30),
          Wire.new(c.x   , c.y , c.x   , y+60),
          Wire.new(c.x   , y+60, b.x+30, y+60),
          Wire.new(b.x+30, y+60, b.x+30, y+70),
          Wire.new(d.x   , d.y , d.x   , y+10),
          Wire.new(d.x   , y+10, d.x   , y+30),
          Wire.new(d.x   , y+10, b.x+20, y+10),
          Wire.new(b.x+20, y+10, b.x+20, y+30),
          Wire.new(b.x+10, y+60, b.x+10, y+70)
$gates.push Gate.new(b.x+10, y+60 , "AND Gate"),
          Gate.new(d.x-10, y+70 , "XOR Gate"),
          Gate.new(b.x+20, y+100, "OR Gate" )
end

while toMerge.count > 2
puts "#{toMerge.count} left to merge"
nextToMerge = []
while toMerge.count > 3
 puts "merging four"
 d, c, b, a, *toMerge = toMerge
 balance a, b
 balance c, d
 sum *$gates[-4..-1]
 nextToMerge.push *$gates[-2..-1]
end
if toMerge.count == 3
 puts "merging three"
 c, b, a, *toMerge = toMerge
 balance b, c
 sum3 a, *$gates[-2..-1]
 nextToMerge.push *$gates[-2..-1]
end
nextToMerge.push *toMerge
toMerge = nextToMerge
puts "layer done"
end

if toMerge.count == 2
b, a = toMerge
x = (a.x + b.x)/2
x -= x % 10
y = [a.y, b.y].max
$wires.push Wire.new(a.x , a.y , a.x , y+10),
          Wire.new(a.x , y+10, x-10, y+10),
          Wire.new(x-10, y+10, x-10, y+20),
          Wire.new(b.x , b.y , b.x , y+10),
          Wire.new(b.x , y+10, x+10, y+10),
          Wire.new(x+10, y+10, x+10, y+20)
$gates.push Gate.new(x, y+70, "XNOR Gate")
toMerge = [$gates[-1]]
end

a = toMerge[0]
$wires.push Wire.new(a.x, a.y, a.x, a.y+10)
$ports.push Port.new(a.x, a.y+10, true)

def xy (x, y)
"(#{x},#{y})"
end
circ = Nokogiri::XML::Builder.new encoding: "UTF-8" do |xml|
xml.project version: "1.0" do
xml.lib name: "0", desc: "#Base"
xml.lib name: "1", desc: "#Wiring"
xml.lib name: "2", desc: "#Gates"
xml.options
xml.mappings
xml.toolbar do
  xml.tool lib:'0', name: "Poke Tool"
  xml.tool lib:'0', name: "Edit Tool"
end #toolbar
xml.main name: "main"
xml.circuit name: "main" do
  $wires.each do |wire|
    xml.wire from: xy(wire.sx, wire.sy), to: xy(wire.tx, wire.ty)
  end #each
  $gates.each do |gate|
    xml.comp lib: "2", name: gate.name, loc: xy(gate.x, gate.y) do
      xml.a name: "facing", val: "south"
      xml.a name: "size", val: "30"
      xml.a name: "inputs", val: "2"
      if gate.attrs
        gate.attrs.each do |name, value|
          xml.a name: name, val: value
        end #each
      end #if
    end #comp
  end #each
  $ports.each.with_index do |port, index|
    xml.comp lib: "1", name: "Pin", loc: xy(port.x, port.y) do
      xml.a name: "tristate", val: "false"
      xml.a name: "output",   val: port.out.to_s
      xml.a name: "facing",   val: port.out ? "north" : "south"
      xml.a name: "labelloc", val: port.out ? "south" : "north"
      xml.a name: "label",    val: port.out ? "out" : "B#{index}"
    end #port
  end #each
end #circuit
end #project
end #builder

File.open "divisibility3.circ", ?w do |file|
file << circ.to_xml
end

puts "done"

```

finally, when asked to create an output for 32 bits, my layouter generates this. Admittedly, it's not very compact for very wide inputs:
> 13 votes

# Answer
# 2×24 NOT, 2×10+5 AND, 2×2+5 OR, 2×2 NOR

This totally does not scale. Like not at all. Maybe I'll try to improve it.

I did test this for numbers up to 30 and it worked fine.

Those 2 big circuits are counting the number of active inputs:

* The upper right one counts the number of bits with an even power (zero to 4)
* The lower left one counts the number of bits with an odd power (zero to 4)

If the difference of those numbers is `0` or `3` the number is divisible by `3`. The lower right circuit basically maps each valid combination (`4,4`, `4,1`, `3,3`, `3,0`, `2, 2`, `1, 1`, `0, 0`) into an or.

The little circle in the middle is an LED that is on if the number if divisible by 3 and off otherwise.
> 6 votes

---
Tags: popularity-contest, graphical-output, combinatorics, logic-gates
---


# Question
Title: Ration your integers and feed the people
It is wartime, and rationing is taking place in certain regions of your country. Your cities' region is one such region. The city chooses to give everyone the same amount, but in reality, larger people need more food. Chances are, a 200lb man is going to be eating more than that 7lb baby over there. The city, realizing that some people need more food, hires you, their best computer programmer, to solve the issue. They want you to write a program that will divvy up the food appropriately.

Being a smart programmer, you have developed a formula that gives an approximation of how much someone will eat based on their weight.

`EAT = (WEIGHT - 1) / 20 + 1`

For example, a 124 pound man will eat 7.125 units of food. Knowing that the food is served in packages of 1, and it would be irrational to cut them up, you can round the food units.

Each day, every person eats that many food units. If somebody goes for five days straight with less than that much food per day, they die of starvation.

You will receive population data in this form: `Population*Weight`, so if you receive `700*180`, you know that their are 700 180lb men in the city. Your city has 100,000 units of food stored away.

For every day your city goes without anyone dying, you get one point. Whoever has the most points wins. Make sure you output how many days your city lasted before someone died.

Here is the input:

`1000x90
2500x80
3000x150
2500x200`

Edit: So, the rule "For every day your city goes without anyone dying, you get one point" was terribly abused. Rule change here: if *anybody* dies, then game over. No more counting.

# Answer
# Ruby, 100003 days/points (~274 years), 5 days before *someone* dies

> For every day your city goes without anyone dying, you get one point.

I shall abuse this rule as much as possible!

> Make sure you output how many days your city lasted before someone died.

Ok, I did. You didn't say anything about that affecting your score.

```
#input = STDIN.read
input = "1000x90
2500x80
3000x150
2500x200" # temporary debugging tool

food = 100000

input = input.split.map{|x| x.split('x').map &:to_i }
onlyPersonToFeedWeight = input.sort_by! {|a|
  a[1] # weight of person
}.first[1] # find the lightest weighing person
foodForOnePerson =  ((onlyPersonToFeedWeight - 1) / 20.0 + 1).ceil # EAT = (WEIGHT - 1) / 20 + 1

# you can see where this is going

daysNobodyDied = 0
daysSomeoneDied = 0

# first kill off all these overweight people
daysNobodyDied += 4
food -= foodForOnePerson
daysSomeoneDied += 1 # it's only all but one person in the city, don't worry

# I have a good feeling about this now
# ... I'm evil

loop {
  daysNobodyDied += 4
  food -= foodForOnePerson
  if food >= 0
    daysNobodyDied += 1
  else
    daysSomeoneDied += 1
    break
  end
}

puts "Survived for #{daysNobodyDied} days"
puts "There were #{daysSomeoneDied} days in which someone died"
puts "The first person died on day 5"

```

Output:

```
Survived for 100003 days
There were 2 days in which someone died
The first person died on day 5

```

I suggest you read the comments in the code first; they're quite amusing. ;) (Code is intentionally verbose.)

The strategy is simple:

* On the first five days, only feed the lightest person (on the fifth day). Then everyone else dies so you don't have to worry about them.
* Continue to starve this poor man with no friends or family by only feeding him once every five days until you run out of food.
* The man will probably die before you run out of food since it will now last 274 years.

Does this make me evil or something?

Oh, and by the way, if he was lying down the whole time, he'd have a better than even chance that a bird would poop in his mouth. (Assuming the birds didn't starve.) Thanks for the... interesting fact, @Synthetica :-P
> 12 votes

---
Tags: code-challenge
---


title: Make a codegolf scorer

text:
# Question
Title: Make a codegolf scorer
You are to make a program that given a number, such as `22009`, will go for example to Pi Calculation Code Golf. Then it will, for each answer, try to figure out what the code is, and count its characters. It will then output, for each answer, its number of characters, and a link to it. It should be sorted with fewest characters at the top. For example :

```
$ answers 22009
5 https://codegolf.stackexchange.com/a/22138/16842
5 https://codegolf.stackexchange.com/a/22188/16842
6 https://codegolf.stackexchange.com/a/22012/16842
6 https://codegolf.stackexchange.com/a/22043/16842

and so on

```

This is code-golf, so shortest code wins!

Note: If there are multiple things that look like code blocks, it doesn't matter which you choose. It is better though if you look which block actually looks like a program, or you could post a different one for each block.

Note: This specifically says characters. It does not matter what the question actually says, just count characters.

# Answer
## Perl - 233

```
use LWP::Simple;for($s="http://codegolf.stackexchange.com",$h=get"$s/questions/@ARGV";$h=~/-answerid="(\d+).+?(<div id="answer-|$)/sg;){$a=$&;$i=$1;$_=$1,$_=~s/&.+?;/@/sgm,print length."$u\t$s/a/$i/\n"while$a=~/<pre><code>(.+?)</sg;}

```

More aerated version:

```
use LWP::Simple;
$s="http://codegolf.stackexchange.com";
$h=get"$s/questions/@ARGV";
for(;$h=~/-answerid="(\d+).+?(<div id="answer-|$)/gs;){
    $a=$&;
    $i=$1;
    while($a=~/<pre><code>(.+?)</gs){
        $_=$1;
        $_=~s/&.+?;/@/sgm;
        print length."$u\t$s/a/$i/\n"
    }
}

```

This is my first script in this language... so there's still probably a lot of golfing to do.
> 1 votes

# Answer
# Javascript? (jQuery) 321

This is my first golf in javascript.

```
var l={};$(".answercell").each(function(){var w=0,c=0,t=$(this),s;t.find("pre code").each(function(){w+=$(this).text().length;c+=1});s=Math.floor(w/c);if(!isNaN(s)){l[t.find(".short-link").prop("href")]=s}});var s=Object.keys(l).sort(function(a,b){return l[a]-l[b]});for(var i=0;i<s.length;i++){console.log(l[s[i]],s[i])}

```

Ungolfed:

```
var list = {};
$(".answercell").each(function () {
    var w = 0, c = 0, s;
    t.find("pre code").each(function () {
       w += $(this).text().length;
       c += 1;
    });
    s = Math.floor(w/c);
    if (!isNaN(s)) {
       list[$(this).find(".short-link").prop("href")] = s;
    }
});
var sorted = Object.keys(list).sort(function(a,b){return list[a]-list[b]});
for (var i=0; i<sorted.length; i++) {
    console.log(list[sorted[i]], sorted[i]);
}

```

Works in the browser console, so maybe it's against the rules, idk. The way it computes for the score is adding all lenghts of code blocks and then dividing by the number of blocks, for each question.

This version, at 257, just counts the first code block:

```
var l={};$(".answercell").each(function(){var t=$(this),s;s=t.find("pre code").text().length;if(s>0){l[t.find(".short-link").prop("href")]=s}});var s=Object.keys(l).sort(function(a,b){return l[a]-l[b]});for(var i=0;i<s.length;i++){console.log(l[s[i]],s[i])}

```
> 0 votes

---
Tags: code-golf
---


title: Find the odd character out in a pattern

text:
# Question
Title: Find the odd character out in a pattern
# Input

The first line will be a certain string repeated any amount of times. For example, it could be `abcabcabcabc`, `[];[];[];`, etc. It may be cut off; for example: `1231231231`. Always find the shortest string; for example, if the line is `22222`, then the string is `2`, not `22` or `22222` or anything else. The string will always be repeated at least 2 full times.

All subsequent lines will be that pattern offset by any number. For example, it could be:

```
abcabcabc
cabcabcab
bcabcabca

```

(offset by 1), or it could be:

```
abcdefabcdefabcdefabc
cdefabcdefabcdefabcde
efabcdefabcdefabcdefa

```

(offset by 4).

One of the characters in the input will be wrong. (It is guaranteed not to be on the first line.) For example, in this input:

```
a=1a=1a=1
=1a=1a=1a
1a=11=1a=
a=1a=1a=1
=1a=1a=1a

```

the `1` on line 3 is the odd one out.

# Output

You must output the (zero-based, starting from the top left) coordinates of the odd one out. For example, in the above input, the corresponding output is `4,2`. You may also output `4 2`, or `"4""2"`, or even `[[4],[2]]`, or any other format, as long as you can tell what the output is supposed to be.

# Test cases

Input:

```
codegolfcodegolfco
egolfcodegolfcodeg
lfcodegolfcodegoff
odegolfcodegolfcod
golfcodegolfcodego
fcodegolfcodegolfc

```

Output: `16,2`

Input:

```
][[][][[][][[][][[][][[
[][][[][][[][][[][][[][
[][[][][[][][[][][[][][
[[][][[]]][[][][[][][[]

```

Output: `8,3`

Input:

```
...
. .
...

```

Output: `1,1`

Input:

```
ababa
babab
ababb
babab

```

Output: `4,2`

# Go!

# Answer
> 7 votes
# ~~Bash~~ Perl, ~~231~~ ~~229~~ ~~218~~ ~~178~~ ~~164~~ ~~166~~ ~~138~~ ~~106~~ 74 bytes

```
/^(((.*).*)\2+)\3$/;$_.=$1x2;$.--,die$+[1]if/^(.*)(.)(.*)
.*\1(?!\2).\3/

```

The script requires using the `-n` switch, which accounts for two of the bytes.

The idea of appending two copies of all full repetitions of the pattern has been taken from MT0's answer.

In contrast to all other answers, this approach attempts to extract the pattern of the current input line in each iteration; it will fail on the line containing the odd character (and use the pattern of the previous line instead). This is done to include the pattern extraction in the loop, which manages to save a few bytes.

### Ungolfed version

```
#!/usr/bin/perl -n

# The `-n' switch makes Perl execute the entire script once for each input line, just like
# wrapping `while(<>){…}' around the script would do.

/^(((.*).*)\2+)\3$/;

# This regular expression matches if `((.*).*)' - accessible via the backreference `\2' -
# is repeated at least once, followed by a single repetition of `\3" - zero or more of the
# leftmost characters of `\2' - followed by the end of line. This means `\1' will contain
# all full repetitions of the pattern. Even in the next loop, the contents of `\1' will be
# available in the variable `$1'.

$_.=$1x2;

# Append two copies of `$1' to the current line. For the line, containing the odd
# character, the regular expression will not have matched and the pattern of the previous
# line will get appended.
#
# Since the pattern is repeated at least two full times, the partial pattern repetition at
# the end of the previous line will be shorter than the string before it. This means that
# the entire line will the shorter than 1.5 times the full repetitions of the pattern,
# making the two copies of the full repetitions of the pattern at least three times as
# long as the input lines.

$.-- , die $+[1] if

# If the regular expression below matches, do the following:
#
#   1. Decrement the variable `$.', which contains the input line number.
#
#      This is done to obtain zero-based coordinates.
#
#   2. Print `$+[1]' - the position of the last character of the first subpattern of the
#      regular expression - plus some additional information to STDERR and exit.
#
#      Notably, `die' prints the (decremented) current line number.

/^(.*)(.)(.*)
.*\1(?!\2).\3/;

# `(.*)(.)(.*)', enclosed by `^' and a newline, divides the current input line into three
# parts, which will be accesible via the backreferences `\1' to `\3'. Note that `\2'
# contains a single character.
#
# `.*\1(?!\2).\3' matches the current input line, except for the single character between
# `\1' and `\3' which has to be different from that in `\2', at any position of the line
# containing the pattern repetitions. Since this line is at least thrice as long as
# `\1(?!\2).\3', it will be matched regardless of by how many characters the line has been
# rotated.

```

### Example

For the test case

```
codegolfcodegolfco
egolfcodegolfcodeg
lfcodegolfcodegoff
odegolfcodegolfcod
golfcodegolfcodego
fcodegolfcodegolfc

```

the output of the golfed version is

```
16 at script.pl line 1, <> line 2.

```

meaning that the odd character has the coordinates `16,2`.

This ~~blatantly abuses~~ takes advantage of the liberal output format.

Just before exiting, the contents of some of Perl's special variables are:

```
$_  = lfcodegolfcodegoff\ncodegolfcodegolfcodegolfcodegolf
$1  = lfcodegolfcodego
$2  = f
$3  = f

```

(`$n` contains the match of the subpattern accessible via the backreference `\n`.)

# Answer
> 8 votes
# Perl, 212 191 181 168 bytes

```
$_=<>;/^(((.*?)(.*?))\2+)\3$/;$x=$1x4;while(<>){chop;$x=~/\Q$_\E/&&next;for$i(0..y///c-1){for$r(split//,$x){$b=$_;$b=~s/(.{$i})./$1$r/;$x=~/\Q$b\E/&&die$i,$",$.-1,$/}}}

```
* This version uses an optimized trick for catching the reply unit, learned in Dennis' answer.
* Optimization by using the property that all lines have equal lengths.
* Line end is also needed for the last line, otherwise `chomp` instead of `chop` should be used.
* Optimizations of ardnew's comment added.

Old version, 212 bytes:

```
$_=<>;chop;/^(.+?)\1+(??{".{0,".(-1+length$1).'}'})$/;$;=$1;while(<>){$x=$;x length;chop;$x=~/\Q$_\E/&&next;for$i(0..-1+length$_){for$r(split//,$;){$b=$_;$b=~s/(.{$i})./$1$r/;$x=~/\Q$b\E/&&exit print$i,$",$.-1}}}

```

## Ungolfed version:

```
$_ = <>;  # read first line
/^(((.*?)(.*?))\2+)\3$/;
# The repeat unit \2 consists of \3 and \4,
# and the start part \2 can be added at the end (as partial or even full unit).
$x = $1 x 4; # $x is long enough to cover each following line

# Old version:
# /^(.+?)\1+(??{ ".{0," . (-1 + length $1) . '}' })$/;
# $a = $1; # $a is the repeat unit.
# The unit is caught by a non-greedy pattern (.+?) that is
# repeated at least once: \1+
# The remaining characters must be less than the unit length.
# The unit length is known at run-time, therefore a "postponed"
# regular expression is used for the remainder.

# process the following lines until the error is found
while (<>) {
    # old version:
    # $x = $a x length;
    # $x contains the repeated string unit, by at least one unit longer
    # than the string in the current line
    chop; # remove line end of current line
    $x =~ /\Q$_\E/ && next;
          # go to next line, if current string is a substring of the repeated units;
          # \Q...\E prevents the interpretation of special characters
    # now each string position $x is checked, if it contains the wrong character:
    for $i (0 .. y///c - 1) {  # y///c yields the length of $_
        for $r (split //, $x) { #/ (old version uses $a)
            # replace the character at position $i with a
            # character from the repeat unit
            $b = $_;
            $b =~ s/(.{$i})./$1$r/;
            $x =~ /\Q$b\E/
               && die $i, $", $. - 1, $/;
               # $" sets a space and the newline is added by $/;
               # the newline prevents "die" from outputting line numbers
        }
    }
}

```

# Answer
> 3 votes
# C, 187 bytes

Limitations.

* Don't use input strings longer than 98 characters :)

**Golfed version**

```
char s[99],z[99],*k,p,i,I,o,a;c(){for(i=0;k[i]==s[(i+o)%p];i++);return k[i];}main(){for(gets(k=s);c(p++););for(;!(o=o>p&&printf("%d,%d\n",I,a))&&gets(k=z);a++)while(o++<p&&c())I=I<i?i:I;}

```

**Ungolfed version**

```
char s[99],z[99],*k,p,i,I,o,a;

c()
{
    for(i=0
       ;k[i]==s[(i+o)%p]
       ;i++)
       ;
    return k[i];
}

main()
{
    for(gets(k=s);c(p++);)
         ;
    for(;!(o=o>p&&printf("%d,%d\n",I,a)) && gets(k=z);a++)
           while(o++ < p && c())
            I=I<i?i:I;
}

```

# Answer
> 2 votes
## Python, ~~303~~ 292

```
r=raw_input
R=range
s=r()
l=len(s)
m=1
g=s[:[all((lambda x:x[1:]==x[:-1])(s[n::k])for n in R(k))for k in R(1,l)].index(True)+1]*l*2
while 1:
 t=r()
 z=[map(lambda p:p[0]==p[1],zip(t,g[n:l+n]))for n in R(l)]
 any(all(y)for y in z)or exit("%d,%d"%(max(map(lambda b:b.index(False),z)),m))
 m+=1

```

Input goes through stdin. I'll explain it if there's any demand, but it doesn't look like I'm going to win anyway.

# Answer
> 1 votes
## Perl, ~~157~~ 154

**Edit**: -3 thanks to ardnew' suggestion.

```
<>=~/^(((.*?).*?)\2+)\3$/;$p=$2;$n=$+[1];while(<>){s/.{$n}/$&$&/;/(\Q$p\E)+/g;$s=$p;1while/./g*$s=~/\G\Q$&/g;print$n>--($m=pos)?$m:$m-$n,$",$.-1,$/if pos}

```

It took me some time (on and off, of course, not 5 days ;-) ), and idea about algorithm was initially elusive (though I felt it was there), but finally (and suddenly) it became all clear.

If string length is multiple of pattern length, and even if the string doesn't start with the beginning of the pattern, concatenating string with itself will produce pattern in place of concatenation (imagine infinite repetition of a word on circular ribbon - the place of welding is not important). So, the idea is to trim the line to multiple unit length and concatenate original to it. The result, even for the string containing the wrong character, is guaranteed to match to pattern at least once. From there on it's easy to find position of offending character.

First line is shamelessly borrowed from Heiko Oberdiek's answer :-)

```
<>=~/^(((.*?).*?)\2+)\3$/;      # Read first line, find the repeating unit
$p=$2;                          # and length of whole number of units.
$n=$+[1];                       # Store as $p and $n.
while(<>){                      # Repeat for each line.
    s/.{$n}/$&$&/;              # Extract first $n chars and
                                # append original line to them.
    /(\Q$p\E)+/g;               # Match until failure (not necessarily from the
                                # beginning - doesn't matter).
    $s=$p;                      # This is just to reset global match position
                                # for $s (which is $p) - we could do without $s,
                                # $p.=''; but it's one char longer.
                                # From here, whole pattern doesn't match -
    1while/./g*$s=~/\G\Q$&/g;   # check by single char.
                                # Extract next char (if possible), match to
                                # appropriate position in a pattern (position
                                # maintained by \G assertion and g modifier).
                                # We either exhaust the string (then pos is
                                # undefined and this was not the string we're
                                # looking for) or find offending char position.

    print$n>--($m=pos)?$m:$m-$n,$",$.-1,$/if pos
}

```

# Answer
> 1 votes
# JavaScript (ES6) - ~~147~~ ~~133~~ 136 Characters

```
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

```

Expects the string to be tested to be in the variable `s` and outputs the result to the console.

```
var repetitionRE = /^(((.*).*)\2+)\3\n/;
                                        // Regular expression to find repeating sequence
                                        // without any trailing sub-string of the sequence.
var sequence = repetitionRE.exec(s)[1]; // Find the sequence string.
s.split('\n')                           // Split the input into an array.
 .map(
   ( row, index ) =>                    // Anonymous function using ES6 arrow syntax
   {
     var testStr = row + '᛫'+ sequence + sequence;
                                        // Concatenate the current row, a character which won't
                                        // appear in the input and two copies of the repetitions
                                        // of the sequence from the first line.
     var match = /^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(testStr);
                                        // Left of the ᛫ finds sub-matches for a single
                                        // character and the sub-strings before and after.
                                        // Right of the ᛫ looks for any number of characters
                                        // then the before and after sub-matches with a
                                        // different character between.
      if ( match )
       console.log( match[1].length, index );
                                        // Output the index of the non-matching character
                                        // and the row.
   }
 );

```

**Test Case 1**

```
s="codegolfcodegolfco\negolfcodegolfcodeg\nlfcodegolfcodegoff\nodegolfcodegolfcod\ngolfcodegolfcodego\nfcodegolfcodegolfc"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

```

Outputs

```
16 2

```

**Test Case 2**

```
s="][[][][[][][[][][[][][[\n[][][[][][[][][[][][[][\n[][[][][[][][[][][[][][\n[[][][[]]][[][][[][][[]"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

```

Outputs

```
8 3

```

**Test Case 3**

```
s="...\n. .\n..."
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

```

Outputs

```
1 1

```

**Test Case 4**

```
s="ababa\nbabab\nababb\nbabab"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

```

Outputs

```
4 2

```

**Test Case 5**

```
s="xyxy\nyyxy"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

```

Outputs

```
0 1

```

**Test Case 6**

```
s="ababaababa\nababaaaaba"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

```

Outputs

```
6 1

```

---
Tags: code-golf
---


# Question
Title: Solve a deterministic version of 2048 using the fewest bytes
Write a program that generates a winning sequence of moves to the deterministic variant of the game 2048. The sequence should be in the form of a string of numbers 0-3, with 0: up, 1: right, 2: down, 3: left. For example, the string "1132" means right right left down. The winning program is the shortest source code that gets to 2048!

The rules to deterministic 2048: The game is played on a 4x4 grid initially containing 1 tile, in the upper left-hand corner. Each move consists of the command "left", "right", "up" or "down". The command left slides all the tiles on the grid to the left, then combines and sums like tiles starting from the left. Likewise, the command right slides tiles to the right, then combines starting from the right.

Each tile can only participate in one combination per move.

After a move, a new 2 tile is created in the first column from the left with an available space, in the first available space from the top in that column.

For example, the sequence "right right left down" leads to the states

```
2___
____
____
____

2__2
____
____
____

2__4
____
____
____

24__
2___
____
____

2___
____
____
44__

```

The command right applied to the row _ 2 2 2 results in _ _ 2 4 The command right applied to the row 2 2 2 2 results in _ _ 4 4

This question inspired by http://jmfork.github.io/2048/

# Answer
> 26 votes
# Python, 740 characters (665 characters compressed)

**Code**:

```
R=range
G=lambda:[[0]*4for _ in R(4)]
J=[(0,4,1),(2,-1,-1),(1,4,1)]
H=[0,-1,1]
def M(P,d):
 C=G();g,z=[(0,-1),(1,0),(0,1),(-1,0)][d];Q=H[g];W=H[z]
 while 1:
    N=[r[:]for r in P]
    for x in R(*J[g]):
     for y in R(*J[z]):
        s=N[y][x];q,w=y-W,x-Q;d=N[q][w];a,b,c=(((0,s,d),(1,0,s+d))[s==d],(0,0,s or d))[s<1 or d<1];
        if 2-a-(C[y][x]+C[q][w]>0):N[y][x]=b;N[q][w]=c;C[q][w]+=a
    if N==P:break
    P=N
 return N
def F(N):
 for x in R(4):
    for y in R(4):
     if N[y][x]==0:N[y][x]=2;return N
def Z(P,i):
 X=[d for d in R(4)if M(P,d)!=P]
 return i==0and(sum((256,c)[c>0] for v in P for c in v)+P[3][3]*10+P[3][2]*9,-1)or max((Z(F(M(P,d)),i-1)[0],d)for d in X)if X else(-1,-1)
B=G()
B[0][0]=2
h=''
while B[3][3]!=2048:_,X=Z(B,4);h+=`X`;B=F(M(B,X))
print h

```

(Mixes tabs with spaces for indentation to save a few bytes)

I must have sucked at golfing it because if I just compress the above code, base-64 encode it, and `exec` it, it's only 665 characters. The following is exactly equivalent to the above, no hard-coded solution or anything:

```
exec"""eJxVUl1vozAQfMa/wn2qnRjJcNzpDnf7QKS2qlRE+1IUy2oJkARdwl2hbT5+/a0NiXqSZXYH78zY
u0/QFe2qJrewKbaLqoi1lmYSLf909IU2LX1iETfkHjSTIhIBFywUfoALo8AhhtyBlhYMDKnqJX1g
mah4TOgMbhlXK3F01WOJxF06It8mRldGPcKdXhn1jJ+jIXS3bjY1DWLipaA7HRvrprNuMkM8m+wH
a5N7LEMlj1rwcAaPDvR6SPXB6L1Rb2IHB/9Z7P1HVSH6ZvTOqEIsRAmMoZ8eHTt3op9WnOseoDLW
KAIUuR12FbjwKjAK2ZslDf3CZ7NBYzobWK8lj0dZWKhRCko1/p5CQWxpCpDFi64ufhMvg5TQrn7/
6Fqauie8Yal9wC9XjeyNvtzS5dQSjVogz7Kh+o9sjv1oLF0OunKc1YmjOXXrAvBpTx4aJCvaivUf
W8bC7z9EyXV5LY2r/XR9cGFpw08+zfQ3g2sSyCEMzeSXbTce2RZ7xubshg0yXDSI44RhfDaSWxs5
rTd9zYbRIomdHJLgQVwQkjVcXpJhLJJB7AJCGf2MX0QOc5aIiKv1FF7zV5WAFUtEzjn52zXtO13/
AwRvylc=""".decode('base64').decode('zip')

```

**Answer**:

Takes ~47 seconds (17 seconds ungolfed) to find the 1111-move sequence:

> 2221230232213120120232222222221221203211012312310123123101223113322222123230210302321222323223212322101202323123322032132021233212312332023123312111123231223113312312322312232123222021221332111332221012222312222302232021233212312332023212222222123221202332023120312123223221232232222222122122323222222212212232222222221322233231222322200232122312232313132022322212312332121332312320212211332312323223212320232322322133223213212323202123123321231313332122232310112113322212323222220130231233211313332122232312312223232231231232312222220232212312220212232312232123222021221332111332221012222312222302232021233212312332023212222222123221202332023120312123223221322323223312230230323312232313133232223233212312323123323222332222222132221321320323233223232121323212232013221323233032021223320231233220322203132123202123321231233202131321221111231213232131210212312232332132103123130213133213232213321323212332332212222123323322202302333121220222323232113123323221223032131201123212133123131222323313133313300123231332011222221223232331313313112312113230231121232332122323232321312323213212232313212323211330231231012

With the following final board position and move:

```
   4    2   16    4
   2    8  128    8
   2    .    . 1024
   .    .    . 1024
Best move: s, with EV=25654

```

Trivia: the solution is 309 bytes gzipped and 418 bytes if gzipped and base64-encoded. Thus it would be a shorter program to just decode that and print it out, but that is no fun at all.

**Explanation**:

Here's a pastebin of the ungolfed version which prints out the board after each move, very fun to watch!

It's a very simple brute-force AI. It assigns an EV for each board position:

```
ev =   256 * number of spaces
     + sum_of_values
     + 10 * board_bottom_right
     +  9 * board_bottom_2nd_right

```

It does a depth-first search four moves ahead and picks the path that leads to the highest EV in four moves. The ev function encourages it to clean up the board and to keep the highest-valued pieces in the corner, which ends up being pretty optimal. It's enough to get it there!

If you modify the EV function to place a higher value on other board spots, something like:

```
1  1  1  1
1  1  1  1
1  1  9 10
1  9 10 11

```

That function gets it as far as:

```
   2    8    4    2
  16   32   64   16
  64  128  512 1024
   2  256 2048 8192

```

**16k**:

Eureka! With a 5-step lookahead instead of a 4, and the following weights:

```
1  1  4  4
1  1  4 10
1  1 14 16
1 16 18 20

```

It almost almost gets 32k, ending on:

```
   2  128    4     2
  64  256  512     4
   4  128 1024  4096
  16 2048 8192 16384

```

The sequence is here.

**32k**:

Yes ladies and gentlemen, we have hit the 32k mark. The EV function, instead of multiplying squares by a constant, raises each square to the following powers and adds them. `x` means the square isn't involved:

```
x x x 3
x x x 4
x x 5 6
x 6 7 8

```

It still sums all the values once and adds 256 for each empty square. Lookahead was 4 all the way up to 32k, and then it bumped up to 5, but it doesn't really seem to do much. End board:

```
   2  128    8     2
  64  256  512     4
   4  128 1024  2048
  16 4096 8192 32768

```

Pastebin of the 24,625-move sequence.

---
Tags: code-golf, sliding-puzzle
---


# Question
Title: EBCDIC code golf (Happy birthday, System/360!)
Pretty soon it's going to be 50 years since IBM unveiled its System/360 family of computers. These were the first to use the EBCDIC character set.

To mark the occasion, let's see who can write the shortest program capable of converting "ordinary" text to and from EBCDIC code page 037. We'll be using a translation table from Wikipedia that maps CP037 to a superset of ISO-8859-1:

```
EBCDIC037_to_Latin1 = [
    0x00,0x01,0x02,0x03,0x9c,0x09,0x86,0x7f,0x97,0x8d,0x8e,0x0b,0x0c,0x0d,0x0e,0x0f,
    0x10,0x11,0x12,0x13,0x9d,0x85,0x08,0x87,0x18,0x19,0x92,0x8f,0x1c,0x1d,0x1e,0x1f,
    0x80,0x81,0x82,0x83,0x84,0x0a,0x17,0x1b,0x88,0x89,0x8a,0x8b,0x8c,0x05,0x06,0x07,
    0x90,0x91,0x16,0x93,0x94,0x95,0x96,0x04,0x98,0x99,0x9a,0x9b,0x14,0x15,0x9e,0x1a,
    0x20,0xa0,0xe2,0xe4,0xe0,0xe1,0xe3,0xe5,0xe7,0xf1,0xa2,0x2e,0x3c,0x28,0x2b,0x7c,
    0x26,0xe9,0xea,0xeb,0xe8,0xed,0xee,0xef,0xec,0xdf,0x21,0x24,0x2a,0x29,0x3b,0xac,
    0x2d,0x2f,0xc2,0xc4,0xc0,0xc1,0xc3,0xc5,0xc7,0xd1,0xa6,0x2c,0x25,0x5f,0x3e,0x3f,
    0xf8,0xc9,0xca,0xcb,0xc8,0xcd,0xce,0xcf,0xcc,0x60,0x3a,0x23,0x40,0x27,0x3d,0x22,
    0xd8,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0xab,0xbb,0xf0,0xfd,0xfe,0xb1,
    0xb0,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0xaa,0xba,0xe6,0xb8,0xc6,0xa4,
    0xb5,0x7e,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0xa1,0xbf,0xd0,0xdd,0xde,0xae,
    0x5e,0xa3,0xa5,0xb7,0xa9,0xa7,0xb6,0xbc,0xbd,0xbe,0x5b,0x5d,0xaf,0xa8,0xb4,0xd7,
    0x7b,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0xad,0xf4,0xf6,0xf2,0xf3,0xf5,
    0x7d,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0xb9,0xfb,0xfc,0xf9,0xfa,0xff,
    0x5c,0xf7,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0xb2,0xd4,0xd6,0xd2,0xd3,0xd5,
    0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0xb3,0xdb,0xdc,0xd9,0xda,0x9f];

```

## Rules:

1. Your program should take two inputs: (a) a text string, and (b) a flag indicating the operation to be performed.
2. Based on this flag, your program should either convert each byte of text into the corresponding EBCDIC character, or vice versa.
3. Input can be obtained from any sensible sources (e.g., command line arguments, stdin, keyboard input), but must not be hard-coded into your program.
4. Output should be displayed on the screen (e.g., stdout, `document.write`) or written to a file/pipeline.
5. Don't use any built-in or external encoding conversion functions (`iconv`, etc.).
6. This is a challenge, so the shortest answer (fewest bytes) will win.

## Examples:

(Note: These examples were produced in a terminal configured to use UTF-8 encoding. You may see different results depending on how your system is configured. Hex equivalents are shown for reference only, and don't have to be generated by your code.)

```
Input: "HELLO WORLD", convert to EBCDIC
Output: "ÈÅÓÓÖ@æÖÙÓÄ" (0xc8c5d3d3d640e6d6d9d3c4)

Input: "ÈÅÓÓÖ@æÖÙÓÄ", convert from EBCDIC
Output: "HELLO WORLD"

Input: "lower case mostly ends up as gremlins", convert to EBCDIC
Output "" <-- unprintable in utf-8
(0x9396a68599408381a285409496a2a393a840859584a240a4974081a24087998594938995a2)

```

# Answer
# Bash + tr, 240 bytes

### Hexdump

```
00000000  58 3d 27 9c 09 86 7f 97  8d 8e 0b 2d 13 9d 85 08  |X='........-....|
00000010  87 18 19 92 8f 1c 2d 1f  80 2d 84 0a 17 1b 88 2d  |......-..-.....-|
00000020  8c 05 06 07 90 91 16 93  2d 96 04 98 2d 9b 14 15  |........-...-...|
00000030  9e 1a 20 a0 e2 e4 e0 e1  e3 e5 e7 f1 a2 2e 3c 28  |.. ...........<(|
00000040  2b 7c 26 e9 ea eb e8 ed  ee ef ec df 21 24 2a 29  |+|&.........!$*)|
00000050  3b ac 5c 2d 2f c2 c4 c0  c1 c3 c5 c7 d1 a6 2c 25  |;.\-/.........,%|
00000060  5f 3e 3f f8 c9 ca cb c8  cd ce cf cc 60 3a 23 40  |_>?.........`:#@|
00000070  27 5c 27 27 3d 22 d8 61  2d 69 ab bb f0 fd fe b1  |'\''=".a-i......|
00000080  b0 6a 2d 72 aa ba e6 b8  c6 a4 b5 7e 73 2d 7a a1  |.j-r.......~s-z.|
00000090  bf d0 dd de ae 5e a3 a5  b7 a9 a7 b6 bc bd be 5b  |.....^.........[|
000000a0  5d af a8 b4 d7 7b 41 2d  49 ad f4 f6 f2 f3 f5 7d  |]....{A-I......}|
000000b0  4a 2d 52 b9 fb fc f9 fa  ff 5c 5c f7 53 2d 5a b2  |J-R......\\.S-Z.|
000000c0  d4 d6 d2 d3 d5 30 2d 39  b3 db dc d9 da 9f 27 3b  |.....0-9......';|
000000d0  5b 20 24 31 20 5d 26 26  74 72 20 04 2d ff 20 22  |[ $1 ]&&tr .-. "|
000000e0  24 58 22 7c 7c 74 72 20  22 24 58 22 20 04 2d ff  |$X"||tr "$X" .-.|

```

Rather trivial solution. Reads from STDIN, prints to STDOUT.

### How to use

* To save the script and make it executable, run these commands:

```
base64 -d <<< WD0nnAmGf5eNjgstE52FCIcYGZKPHC0fgC2EChcbiC2MBQYHkJEWky2WBJgtmxQVnhogoOLk4OHj5efxoi48KCt8Junq6+jt7u/s3yEkKik7rFwtL8LEwMHDxcfRpiwlXz4/+MnKy8jNzs/MYDojQCdcJyc9IthhLWmru/D9/rGwai1yqrrmuMaktX5zLXqhv9Dd3q5eo6W3qae2vL2+W12vqLTXe0EtSa309vLz9X1KLVK5+/z5+v9cXPdTLVqy1NbS09UwLTmz29zZ2p8nO1sgJDEgXSYmdHIgBC3/ICIkWCJ8fHRyICIkWCIgBC3/ > ebcdic.sh
chmod +x ebcdic.sh

```
* To convert to EBCDIC (encode), execute the plain command:

```
./ebcdic.sh

```
* To convert from EBCDIC (decode), specify any first argument:

```
./ebcdic.sh -d

```
> 7 votes

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