title: Create a Nonogram Puzzle

text:
# Question
Title: Create a Nonogram Puzzle
A nonogram is a two-dimensional logic puzzle that looks something like this (screenshots from the game Pixelo, my favourite nonogram game):

The goal of the game is to figure out what image those numbers are encoding. The rules are simple: A number on a column or row means that somewhere in that column or row, that many boxes are filled in in a row. For example, the bottom row in the above image must have no boxes filled in, while the one above it must have all of its boxes filled. The third row from the bottom has 8 filled boxes, and they will all be in a row.

Two or more numbers for the same column or row mean that there are multiple "runs" of filled boxes, with at least one space between, with those lengths. The order is preserved. For example, there are three filled in boxes on the very right column of the above image, at least one space below them, and then one more filled in box.

Here's that same puzzle, almost completed:

(The Xs aren't important, they're just a hint the player leaves for themself to say "This square is definitely not filled in". Think flags in Minesweeper. They have no rules meaning.)

Hopefully you can see that, for example, the middle columns with hints that say "2 2" have two 2-length runs of filled in boxes.

Your mission, should you choose to accept it, is to write a program or function that will create a puzzle like this. You are given the size of the board as a single integer (5 \<= n \<= 50) on stdin or as an argument (there's no reason why a nonogram puzzle has to be square, but for this challenge it will be). After that, you will be given a series of 1s and 0s representing filled and unfilled squares in the image, respectively. The first n of them are the top row, then the next row, etc. You will return or print to stdout a board of 2\*1 cells (because they look better, and it gives you room for 2-digit hints for a column), all of them empty, with hints corresponding to the input data.

# Output Format

# Sample

Input:

```
./nonogram <<< '5 0 1 1 1 0 1 1 0 1 1 1 0 1 0 1 1 1 0 1 1 0 1 1 1 0'
                                 OR
      n(5,[0,1,1,1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1,1,1,0])

```

Image:

Output:

```
           1
         2 1 2
       3 2 1 2 3
     +----------
    3|
  2 2|
1 1 1|
  2 2|
    3|

```

Input:

```
./nonogram <<< '15 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1'

```

Image:

Output:

```
                   1                       1
                 1 1 3       3 5   5 3   3 1
                 7 2 3 2 4 2 3 210 2 3 0 4 215
               +------------------------------
              2|
              1|
              1|
              1|
              1|
            1 1|
        3 3 1 1|
        1 5 1 1|
          3 5 3|
          1 5 1|
          1 3 1|
      1 1 1 1 1|
1 1 1 1 1 1 1 1|
           11 3|
           11 3|

```

# Clarifications

* Your output need not be a solvable puzzle. Not all nonograms are solvable, but that isn't your concern. Just output the hints that correspond to the input, whether they make for a good puzzle or not.
* A program that takes arguments on the command line is allowed. This is kind of stated above, but it's possible to get the wrong idea. That's what clarifications are for.
* Printing a `0` for a row or column that has no filled in boxes is mandatory. I don't say this with words anywhere but it's in the sample data.

# Answer
> 9 votes
### GolfScript, 128 characters

```
~](:k/.{{1,%{,}%.!,+}%}:^~{' ':s*}%.{,}%$-1=:9{s*\+9~)>'|'n}+%\zip^.{,~}%$0=){.~[s]*@+>{s\+-2>}%}+%zip{9)s*\n}%\[9s*'+''--'k*n]\

```

The input has to be provided on STDIN as space separated numbers.

You can test the example here.

*Commented code:*

```
# Parse the input into an 2D array of digits. The width is saved to variable k
~](:k/

# Apply the code block ^ to a copy of this array
.
{                # begin on code block
  {              # for each line
   1,%           #   split at 0s (1, => [0]) (leading, trailing, multiple 0s are
                 #   removed because of operator % instead of /)
   {,}%          #   calculate the length of each run of 1s
   .!,+          #   special case: only zeros, i.e. []
                 #   in this case the ! operator yiels 1, thus [0], else []
  }%             # end for
}:^              # end of code block
~                # apply

# Format row headers
{' ':s*}%        # join numbers with spaces
.{,}%$-1=:9      # calulate the length of the longest row header
                 # and save it to variable <9>
{                # for each row
  s*\+           #   prepend padding spaces
  9~)>           #   and cut at length <9> from the right
  '|'n           #   append '|' and newline
}+%              # end for

# Format column headers
\zip^            # transpose input array and apply the code block ^
                 # i.e. calculate length of runs
.{,~}%$0=)       # determine (negative) length of the longest column header
{                # for each column
  .~[s]*@+       #   prepend enough spaces
  >              #   and cut at common length (from right)
  {s\+-2>}%      #   format each number/empty to 2 chars width
}+%              # end for
zip              # transpose column header into output lines
{9)s*\n}%        # prepend spaces to each line and append newline

# Inject separator line
\[
9s*              # spaces
'+'              # a plus sign
'--'k*           # k (width) number of '--'
n                # newline
]\

```

# Answer
> 7 votes
# Ruby, 216 ~~255~~

```
n=$*.shift.to_i;k=*$*.each_slice(n)
u=->k{k.map{|i|r=i.join.scan(/1+/).map{|i|"%2d"%i.size}
[*["  "]*n,*r[0]?r:" 0"][-n,n]}}
puts u[k.transpose].transpose.map{|i|" "*(n-~n)+i*""},"  "*n+?++"--"*n,u[k].map{|i|i*""+?|}

```

While this doesn't produce the exact sample output given in the question, it does follow the specs. The only difference to the examples is that I print a few leading spaces/newlines.

Example:

```
$ ruby nonogram.rb 15 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1
# empty lines removed for brevity
                                  1                       1
                                1 1 3       3 5   5 3   3 1
                                7 2 3 2 4 2 3 210 2 3 0 4 215
                              +------------------------------
                             2|
                             1|
                             1|
                             1|
                             1|
                           1 1|
                       3 3 1 1|
                       1 5 1 1|
                         3 5 3|
                         1 5 1|
                         1 3 1|
                     1 1 1 1 1|
               1 1 1 1 1 1 1 1|
                          11 3|
                          11 3|

```

### Changelog:

* 240 -\> 231: Changed input format to use command line arguments instead of stdin.
* 231 -\> 230: Eliminated a space by moving the value check from `chunk` to `map`.
* 230 -\> 226: Subtract `[nil]` instead of calling `Array#compact`.
* 226 -\> 216: Simplify hint generation.

# Answer
> 4 votes
# Ruby, 434

```
n=$*[i=0].to_i
a,b=[],[]
a.push $*.slice!(1..n)*""while $*.size>1
(b.push a.map{|c|c[i]}*"";i+=1)while i<n
a,b=*[a,b].map{|c|c.map{|d|e=d.split(/[0]+/).map(&:size).select{|f|f>i=0}.map &:to_s;(e.size>0)?e:[?0]}}
m,k=*[a,b].map{|c|c.map(&:size).max}
s="  "*m
k.times{$><<s+"  "+b.map{|c|(" "+((c.size==k-i)?(c.shift):(" ")))[-2..-1]}*"";i+=1;puts}
puts s+" "+?++?-*n*2
a.each{|c|puts"  "*(m-c.size)+" "+c.map{|d|(" "+d)[-2..-1]}*""+?|}

```

# Answer
> 4 votes
## GolfScript ~~149~~ 147

### The Code

```
~](:s/.zip{{[0]%{,`}%['0']or}%.{,}%$)\;:¶;{.,¶\-[' ']*\+}%}:f~¶:v;\[f~]\zip{{{.,2\-' '*\+}%''*}:d~¶2*)' '*:z\+{puts}:o~}%z(;'+'s'-'2**++o~{d'|'+o}/

```

Edits:

* removed useless space
* defined a reusable one-char function for `puts` to save one more char

### Online demos

### A somewhat annotated version of the code

```
# split lines
~](:s/

# make transposed copy
.zip

#prepare numbers to show in the header
{{[0]%{,`}%['0']or}%.{,}%$)\;:¶;{.,¶\-[' ']*\+}%}:f~¶:v;

# prepare numbers to show in the left column
\[f~]\zip

#print header (vertical hints)
{  {{.,2\-' '*\+}%''*}:d~  ¶2*)' '*:z\+puts}%

#print first line
z(;'+'s'-'2**++puts

#print horizontal hints
~{d'|'+ puts}/

```

# Answer
> 4 votes
# Javascript (E6) 314 ~~334 357 410~~

```
N=(d,l)=>{J=a=>a.join(''),M=s=>(s.match(/1+/g)||['']).map(x=>x.length),f=' '.repeat(d+1),c=[n='\n'],o=n+f+'+'+'--'.repeat(d);for(i=-1;++i<d;)c[i]=M(J(l.map((e,p)=>p%d-i?'':e))),o+=n+(f+J(M(J(l).substr(i*d,d)).map(P=n=>n>9?n:n<10?' '+n:'  '))+'|').slice(-d-2);for(;--i;)o=n+f+' '+J(c.map(e=>P(e.pop())))+o;return o}

```

**Ungolfed**

```
N=(d,l)=> {
  J = a => a.join(''),
  M = s => (s.match(/1+/g)||['']).map(x=>x.length),
  f=' '.repeat(d+1), c=[n='\n'], o=n+f+'+'+'--'.repeat(d);
  for(i = -1; ++i < d;)
    c[i] = M(J(l.map((e,p)=>p%d-i?'':e))),
    o += n+(f+J(M(J(l).substr(i*d,d)).map(P=n=>n>9?n:n<10?' '+n:'  '))+'|').slice(-d-2);
  for(;--i;)
    o=n+f+' '+J(c.map(e=>P(e.pop())))+o;
  return o
}

```

**Usage**

`N(5,[0,1,1,1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1,1,1,0])`

`N(15,[0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,0,0,1,0,1,0,0,1,0,0,0,1,1,1,1,1,0,1,0,1,1,1,1,0,0,0,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,1,0,0,0,1,0,0,0,1,0,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1])`

**Edit history**

1 Removed regexp used to find columns.Overkill
2 Simpler is better. Output to a string, not to an array. Removed helper function FILL (F)
3 Even simpler. I can't do better than this. Still can't compare to Golfscript :(

# Answer
> 1 votes
## R, 384 chars

```
a=scan();p=function(x)paste(x,collapse="");P=paste0;s=sapply;l=length;f=function(i)lapply(apply(matrix(a[-1],nr=a,b=T),i,rle),function(x)if(any(x$v)){x$l[!!x$v]}else{0});g=function(j,i)apply(s(j,function(x)sprintf("%2s",c(rep("",max(s(j,l))-l(x)),x))),i,p);c=P(g(f(1),2),"|");d=g(f(2),1);h=p(rep(" ",nchar(c[1])-1));e=P(h,"+",p(rep("-",nchar(d[1]))));d=P(h," ",d);cat(d,e,c,sep="\n")

```

With indentations and some explanations:

```
a=scan() #Takes input

p=function(x)paste(x,collapse="") #Creates shortcuts
P=paste0
s=sapply
l=length

#This function finds the number of subsequent ones in a line (using rle = run length encoding).
#It takes 1 or 2 as argument (1 being row-wise, 2 column-wise
f=function(i)lapply(apply(matrix(a[-1],nr=a,b=T),i,rle),function(x)if(any(x$v)){x$l[!!x$v]}else{0})

#This function takes the result of the previous and format the strings correctly (depending if they are rows or columns)
g=function(j,i)apply(s(j,function(x)sprintf("%2s",c(rep("",max(s(j,l))-l(x)),x))),i,p)

c=paste0(g(f(1),2),"|") #Computes the rows
d=g(f(2),1) #Computes the columns
h=p(rep(" ",nchar(c[1])-1))
e=paste0(h,"+",p(rep("-",nchar(d[1])))) #Prepare vertical border
d=paste0(h," ",d) #Pad column indices with spaces
cat(d,e,c,sep="\n") #Prints

```

Usage:

```
> a=scan();p=function(x)paste(x,collapse="");P=paste0;s=sapply;l=length;f=function(i)lapply(apply(matrix(a[-1],nr=a,b=T),i,rle),function(x)if(any(x$v)){x$l[!!x$v]}else{0});g=function(j,i)apply(s(j,function(x)sprintf("%2s",c(rep("",max(s(j,l))-l(x)),x))),i,p);c=P(g(f(1),2),"|");d=g(f(2),1);h=p(rep(" ",nchar(c[1])-1));e=P(h,"+",p(rep("-",nchar(d[1]))));d=P(h," ",d);cat(d,e,c,sep="\n")
1: 15 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 1 0 1 0 0 1 0 0 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 0 1 1 1 1 1 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1
227:
Read 226 items
                    1                       1
                  1 1 3       3 5   5 3   3 1
                  7 2 3 2 4 2 3 210 2 3 0 4 215
                +------------------------------
               2|
               1|
               1|
               1|
               1|
             1 1|
         3 3 1 1|
         1 5 1 1|
           3 5 3|
           1 5 1|
           1 3 1|
       1 1 1 1 1|
 1 1 1 1 1 1 1 1|
            11 3|
            11 3|

```

# Answer
> 1 votes
# C - 511

C was definitely not made for formatting output nicely. Character count includes only necessary spaces/new lines.

Input is from STDIN, numbers separated by spaces.

```
#define P printf
#define L(x) for(x=0;x<s/2+1;x++)
#define l(x) for(x=0;x<s;x++)
#define B(x,y) x[i][j]||y==s/2?P("%2d",x[i][j]):P("  ");
a[50][50],i,j,s,h[25][50],v[50][25],H[50],V[50],x[25],y[25];
main(){
    scanf("%d",&s);
    L(j)x[j]=y[j]=s/2+1;
    l(i)l(j)scanf("%d",&a[i][j]);
    for(i=s-1;i>=0;i--)
        for(j=s-1;j>=0;j--)
            a[i][j]?
                !H[j]&&(x[j]--,H[j]=1),
                h[x[j]][j]++,
                !V[i]&&(y[i]--,V[i]=1),
                v[i][y[i]]++:
            (H[j]=V[i]=0);
    L(i){
        L(j)P("  ");
        P(" ");
        l(j)B(h,i);
        P("\n");
    }
    L(i)P("  ");
    P("+");
    l(i)P("--");
    P("\n");
    l(i){
        L(j)B(v,j);
        P("|\n");
    }
}

```

# Answer
> 1 votes
It's been a few days and no one's answered in python, so here's my (probably pretty poor) attempt:

# Python 2.7 - ~~404~~ ~~397~~ 380 bytes

```
def p(n,m):
 k=str.join;l=[];g=lambda y:[['  ']*(max(map(len,y))-len(t))+t for t in[[' '*(a<10)+`a`for a in map(len,k("",c).split('0'))if a]or[' 0']for c in y]]
 while m:l+=[map(str,m[:n])];m=m[n:]
 x=g(l);j=k('\n',['  '*max(map(len,x))+'+'+k("",a)for a in zip(*[list(a)+['--']for a in g(zip(*l))])]);return j.replace('+',' ',j.count('+')-1)+'\n'+k('\n',[k("",a+['|'])for a in x])

```

~~I'll post an ungolfed version soon, but at the moment I think it's pretty readable. :)~~

**EDIT:** While writing the ungolfed version, I noticed some improvements I could make that added up to be fairly significant! For some reason that I can't explain, it now has additional newlines at the top and spaces at the left (even though I don't think I changed anything functional), but it still meets spec. ~~Ungolfed version is coming!~~

Ungolfed:

```
def nonogram(board_size, pixels):
    def hints(board):
        output = []
        for row in board:
            # Convert the row to a string of 1s and 0s, then get a list of strings
            # that came between two 0s.
            s = "".join(row).split('0')

            # A list of the length of each string in that list.
            l = map(len, s)

            # We now have our horizontal hints for the board, except that anywhere
            # there were two 0s consecutively we have a useless 0.
            # We can get rid of the 0s easily, but if there were no 1s in the row at
            # all we want exactly one 0.
            # Solution:
            output.append([h for h in l if h != 0] or [0])
            # In this context, `foo or bar` means `foo if foo is a truthy value, bar
            # otherwise`.
            # An empty list is falsey, so if we strip out all the strings we hardcode
            # the 0.
        return output

    def num_format(hints):
        # For both horizontal and vertical hints, we want a space before single-
        # digit numbers and no space otherwise. Convert hints to strings and add
        # spaces as necessary.
        output = []

        for row in hints:
            output.append([' '*(a < 10) + str(a) for a in row])
            # Multiplying a string by n repeats it n times, e.g. 'abc'*3=='abcabcabc'
            # The only numbers that need a space are the ones less than 10.
            # ' '*(a < 10) first evaluates a < 10 to get a True or False value.
            # Python automatically converts True to 1 and False to 0.
            # So, if a is a one digit number, we do `' '*(1) + str(a)`.
            # If it's a two digit number, we do `' '*(0) + str(a)`.
        return output

    def padding(hints):
        output = []
        longest = max(map(len, hints)) # how long is the longest row?
        for row in hints:
            output.append(['  ']*(longest - len(row)) + row)
            # Add '  ' to the beginning of every row until it's the same length
            # as the longest one. Because all hints are two characters wide, this
            # ensures all rows of hints are the same length.
        return output

    board = []

    while pixels: # non-empty list == True
        # Make a list of the first (board_size) pixels converted to strings, then
        # add that list to board. Remove those pixels from the list of pixels.
        # When pixels is empty, board has a seperate list for each row.
        board.append([str(n) for n in pixels[:board_size]])
        pixels = pixels[board_size:]

    horizontal_hints = padding(num_format(hints(board)))

    vertical_hints = padding(num_format(hints(zip(*board))))
    # zip(*l) is a common way to transpose l.
    # zip([1,2,3], [4,5,6], [7,8,9]) == [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
    # the star operator unpacks an iterable so the contents can be used as
    # multiple arguments, so
    # zip(*[[1,2,3],[4,5,6],[7,8,9]]) is the same as what we just did.
    # Transposing the board and getting the horizontal hints gives us the
    # vertical hints of the original, but transposed. We'll transpose it back,
    # but we'll also add '--' to the end of all of them to make up the line
    vertical_hints = zip(*[a + ['--'] for a in vertical_hints])

    # add n spaces, where n is the length of the longest horizontal hint, plus
    # one space to the beginning of each line in the vertical hints, then join
    # with newlines to make it all one string.
    vertical_hints = '\n'.join(['  '*max(map(len, horizontal_hints)) + '+' +
                               ''.join(a) for a in vertical_hints])

    # find the number of plus signs in the string
    # replace the first (that many - 1) plus signs with spaces
    vertical_hints = vertical_hints.replace('+', ' ', vertical_hints.count('+')-1)

    # add a pipe to each row of horizontal hints, then join it with newlines
    horizontal_hints = '\n'.join([''.join(a + ['|']) for a in horizontal_hints])

    # add and return
    return vertical_hints + '\n' + horizontal_hints

```

A few changes were made for readability sake (`g` being split into three named functions, complex list comprehensions made into `for` loops) but logically it works exactly the same way.

Which is why it's confusing that this one doesn't print extra spaces and newlines, while the golfed one does. ¯\\\_(ツ)\_/¯

---
Tags: code-golf
---


# Question
Title: Write a sorting program that looks erroneous but it is actually correct
Write a program that sorts a vector of numbers (or any type of element) that looks like having one or more bugs, but it is actually ok.

* The code must be clear. Someone looking over the code must easily identify that it is a sort algorithm and must easily confuse a correct piece of code with a bug.
* The (apparent) bug can by anything that makes the code syntactically or semantically ill-formed (e.g. make the program not compile/run, exhibit UB when runned), make the program produce incorrect results, not terminate, or nondeterministic.
* The code must actually be well-formed and the program must deterministically produce the correct output in a finite time.
* The input can be hard coded in the program or can be read (from user, from file etc.).
* Input is considered valid and the program is not needed to verify input correctness.
* Any sorting algorithm is accepted. The data structure to hold the numbers is not needed to be an actual vector. The program can be designed to sort a variable number of numbers or a fixed number of numbers (e.g. **a program to sort 3 numbers is ok**). Sorting can be stable or not (note: a program designed to do a stable sort that has an apparent bug that makes the sort look unstable, but in actuality it is not a bug: the program actually does a stable sort — is a valid answer).
* you can call any functions (including sort functions) except 3rd party tools (unless they are widely spread and used e.g. `boos` for `C++`, `JQuery` for `Javascript` – those are ok to use)
* specify the language
* comment in code the part that looks like a bug.
* explain what the bug looks like doing wrong.
* explain (in a spoiler box) why it is actually not a bug.

This is a popularity contest. The answer with most votes wins.

---

This challenge is now over. The winner is @Clueless https://codegolf.stackexchange.com/a/30190/11400 with 8 votes. Thanks to all the submitters!

If you want to come in after the winner was awarded, please feel free to add a new answer. You are out of the race, but we are all interested to see interesting answers.

# Answer
## C++

Inspired by Apple's `goto fail`; bug.

```
#include <vector>
#include <map>
#include <iostream>

/**
 * Sorts a vector of doubles in reverse order using the bucket sort algorithm.
 */
std::vector<double> reverse_bucket_sort(const std::vector<double>& input) {
    // put each element into a bucket as many times as it appears
    std::map<double, int> bucket_counts;
    for (auto it : input)
        ++bucket_counts[it];

    std::vector<double> sorted_elements; // the return value

    // loop until we are done
    while (bucket_counts.size() > 0) {
        // find the largest element
        double maximum = std::numeric_limits<double>::lowest();
        for (auto it : bucket_counts) {
            if (it.first > maximum)
                maximum = it.first;
                maximum = it.first;
        }

        // add the largest element N times to our sorted vector
        for (int i = 0; i < bucket_counts[maximum]; ++i)
            sorted_elements.push_back(maximum);

        // and now erase the bucket
        bucket_counts.erase(maximum);
    }

    return sorted_elements;
}

int main(int argc, const char * argv[]) {
    std::vector<double> test_case = { 0, 1, 2.5, 10, 2.5, 2 };

    std::cout << "unsorted:";
    for (auto it : test_case) std::cout << " " << it;
    std::cout << std::endl;

    std::cout << "sorted:";
    for (auto it : reverse_bucket_sort(test_case)) std::cout << " " << it;
    std::cout << std::endl;

    return 0;
}

```

> About halfway down the page there is a bug: we have a duplicate line after our `if` check! We are always going to update the maximum with whatever is the last value in `bucket_count`. Thankfully we are OK. In C++ `std::map` is sorted by keys. So we are just reversing the buckets, which is what we want.
> 11 votes

# Answer
# Python2.x

```
import random
L = [random.randrange(20) for x in range(20)]
print "Unsorted:", L

def sort(L):
    # terminal case first. Otherwise sort each half recursively and combine
    return L.sort() if L > 1 else sort(L[:len(L)//2]) + sort(L[len(L)//2:])

sort(L)
print "Sorted:", L

```

Test run

> `list.sort` returns `None`, so the part after the `else` is `None + None`. Luckily this doesn't cause a problem because the comparison of a list and and an int `(L > 1)` is always `True`. The function always returns `None` so we ignore the return value and Just print `L` which has been sorted in place Merging the sorted halves by catenation wouldn't have worked either even if the execution did get there.
> 8 votes

# Answer
# C

Using sort incorrectly - on a 64 bit system `int` is 4 bytes and `char *` is 8 bytes, so shouldn't work.

Code:

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

/* Compare integers to sort in reverse order */
int compare(const void *p, const void *q)
{
    const int *a = p;
    const int *b = q;

    return *b - *a;
}

int main()
{
    char *strings[] = {"B", "Que", "Ro", "Sum", "T"};
    int i;

    /* Let's use the integer compare to sort strings */
    qsort(&strings, sizeof(strings) / sizeof(char *), sizeof(char *), compare);

    /* Output the sorted results */
    for (i = 0; i < sizeof(strings) / sizeof(char *); i++)
        printf("%s\n", strings[i]);

    return 0;
}

```

Build:

```
$ gcc -o sort-no-sort sort-no-sort.c

```

Run:

```
$ ./sort-no-sort
T
Sum
Ro
Que
B

```

Yep, sorts okay!

> Five things going on: 1) `qsort` passes pointers to integers, which are the same size as pointers to characters. 2) The strings are no more than four bytes in length (three + one terminator) = the size of an integer, which the sort routine happily treats as an integer. 3) Most compilers force alignment of data structures, so shorter strings take up the same space. Any larger though and be prepared for failures. 4) Endian-ness. 5) Zero initialization of internal bytes.
> 5 votes

# Answer
# Cobra

```
class Program
    var _target as List<of bool?> = [true, true, false, true, true, nil, nil, false, true, nil, true]
    def main
        .sort(_target)
        print _target
    def sort(target as List<of bool?>)
        for i in target.count, for n, in target.count -1, if target[n] <> target[n + 1] and (target[n] or target[n + 1] == nil), target[n], target[n + 1] = target[n + 1], target[n]
            #should return sorted as [nil][false][true]

```

Oh dear, I appear to have incorrectly assigned `n`... and how did all those commas get there!?

> When `n` is assigned the compiler assumes that it's being give the first half of a key-value pair (due to the comma), but there is no key-value pair so the compiler doesn't complain when it can't assign the second half of it to a non-existent variable. This results in `n` simply being given the key value.. which in this case is an index number. All of the other out-of-place-looking commas in the final line are actually part of standard Cobra syntax.
> 2 votes

# Answer
# Java

```
public final class WeirdSort {
    public static void main(final String[] args) {

        //Random
        final Random random = new Random(441287210);

        //Some numbers:
        final List<Integer> list = new ArrayList<Integer>();
        list.add(9);
        list.add(11);
        list.add(3);
        list.add(5);
        list.add(7);

        //Sort randomly:
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(final Integer o1, final Integer o2) {
                return (o1 - o2) + random.nextInt(10);
            }
        });

        //Print
        for(final Integer i:list) {
            System.out.print(i + " ");
        }
    }
}

Prints: 3 5 7 9 11

```

> Works because this specific random value returns '1' for the first 10 results
> 2 votes

# Answer
# Perl

Contractors these days! Don't they know that the `<=>` (a.k.a "spaceship") operator is only used for numeric sorting?

And why are they comparing operators?

How did this code even pass our stringent tests??!! It even uses `strict` and `warnings`!

```
use strict;
use warnings;

sub asciibetically { 0-($a lt $b) || 0+($a gt $b) || <=><=><=> }
                                                   #  ^  ^  ^
                                                   # What?? How did Perl even compile??!!

my @sorted = sort asciibetically qw( bravo charlie alpha );

print "@sorted";   # "alpha bravo charlie"
                   # And how come it works??!!

```

---

### Why Perl compiles

> The only real `<=>` operator is the one in the middle. The other two are just another way of writing `glob("=")`. This means that `<=><=><=>` (nicknamed "space fleet") evaluates to `0`.

---

### Why it works

> The `asciibetically` subroutine is an implementation of the string-comparing `cmp` operator: Binary "`cmp`" returns `-1`, `0`, or `1` depending on whether the left argument is stringwise less than, equal to, or greater than the right argument.
> 2 votes

---
Tags: popularity-contest, underhanded
---


title: If community would have been a person

text:
# Question
Title: If community would have been a person
Well the community is just a bot. But what if it would have been a person?

Your task is to find what community's reputation might have been if it would have been given reputation for the edits it makes.(simply 2\*edits)

This should work for any site, but we would consider PP&CG for this question.

Use any language, even data.stackexchange would work.

As it is code golf, smallest code wins as much reputation I gain+15(via bounty, I will leave 101 for myself :P ).

EDIT: consider all kind of edits that increase reputation.

# Answer
> 4 votes
I know URL shorteners are cheaty but since everyone else is using them I probably should.

# Bash, with `bc` and URL shortener: ~~67 62 60 58~~ 54

```
bc<<<`wget x.co/4Ccg3 -qO-|grep -oP "(?<='>)[0-9]+"`*2

```

Downloads the relevant page to STDOUT, then searches for `'>` followed by a sequence of digits - it misuses the fact that in the page's source code, single quotes are only rarely used; in fact the sequence `'>` occurs twice, and only once followed by a number, which is the number of edits. Using the Perl-style lookbehind, the `'>` isn't actually included in the match.

The `-o` option makes `grep` output only the matched string rather than the entire line containing it (there is a `h1` on the same line and I don't want that).

The resulting number of edits is concatenated with `*2` and sent to `bc`.

**@11684 pointed out that you start out with 1 reputation, but the asker clearly forgot that so it's not mentioned in the question (it would break existing answers if it was). If you want to add that in just put in `+1` at the end of the code, adding 2 chars.**

# SHELF, 36 - doesn't count as the language was created after the question

```
, `W x.co/4Ccg3|t "(?<='>)[0-9]+"`*2

```

SHELF is a golfed version of Bash, like PYG is for Python.

# Answer
> 2 votes
# Python (~~191~~ ~~181~~ ~~170~~ ~~126~~ 117)

@Henrik: Good idea to use an url shortener. Don't mind if I just borrow yours, do you? Just to kick it off, this will probably get beaten very, very fast ;)

```
i=__import__("urllib2").urlopen("http://x.co/4Ccg3").read();j=i[i.index("<span class='count")+20:];print 2*int(j[:2])

```

Searches for the `<span class='count'>` that contains the amount of reputation the bot has.

# Answer
> 2 votes
# JavaScript (EcmaScript 6 + jQuery) - 80 Characters

```
$.get('/users/-1/?tab=activity&sort=revisions',r=>alert($('.count',r).text()*2))

```

Run it in the JavaScript console on any StackExchange page (although ECMAScript 6 arrow functions are only supported on FireFox at the moment so it will have do be done in that browser until the others catch up) and will get Community's reputation on that domain. So running it on `http://codegolf.stackexchange.com` will get the Code Golf Community's reputation (currently 118) and running it on `http://academia.stackexchange.com/` would get the reputation from that site (currently 162).

Which hopefully answers the

> This should work for any site

bit of the question.

# Answer
> 1 votes
## JavaScript (with jQuery) - 141

```
$.get('http://codegolf.stackexchange.com/users/-1/?tab=activity&sort=revisions',function(o){alert($('<a>').html(o).find('.count').html()*2)})

```

**EDIT** : only works if executed from any StackExchange page... or if same origin policy is disabed.

If same origin policy is disabled, can be shorten to 96 chars :

```
$.get('http://tinyurl.com/pfmsq8w',function(o){alert($('<a>').html(o).find('.count').html()*2)})

```

# Answer
> 1 votes
***I've included the 1 reputation that you start with!***

# jQuery, 76

```
$a=$("body");$a.load("//x.co/4Ccg3 .count",function(){$a.text($a.text()*2+1)

```

on any page with jQuery and requested by http.

# jQuery, only works on the relevant page - 23

```
$(".count").text()*2+1;

```

The page it runs on is http://goo.gl/JOqzpF.

# Answer
> 1 votes
# StackExchange Data 78 chars

Click here to run the query

```
SELECT COUNT(*)*2FROM PostHistory WHERE UserId=-1AND PostHistoryTypeId IN(4,5)

```

# Answer
> 0 votes
# PowerShell (143)

My first ever PowerShell script! Counts the number of revisions and times it by two (very inspired by @Synthetica's Python answer).

```
$s=(New-Object Net.WebClient).DownloadString("http://tinyurl.com/pfmsq8w");(0+($s.Substring($s.IndexOf("s='cou")+10,8) -replace "[^\d]",""))*2

```

---
Tags: code-golf
---


title: Leet to English Translation

text:
# Question
Title: Leet to English Translation
Your challenge is to **write a program to translate (English) leetspeak/lolspeak/txtspk into normal English.** Your program should read from standard input and output to standard output, unless your language does not support these.

You may use a file containing a list of words in the English language, separated by new lines. It should be called `W` and will be located in the same directory as your program. (On GNU/Linux systems and possibly others, you can make `W` a link to `/usr/share/dict/words`) The list doesn't have to be all-lowercase, you can use it to determine whether words should have capitals.

This is based on a now-deleted question posted by Nikos M. which could be found here. This is not a duplicate as this original question was closed and did not receive any answers, because there was no winning criterion and the user was unwilling to put one in.

# Scoring

The scoring is a bit complicated!

Your score is

```
(leet items + bonuses) * 10 / (code length)

```

Highest score wins.

**Your program doesn't have to be and probably can't be perfect, but the more accurate it is, the more bonuses it gets!**

Since `$` can mean both `s` and `S`, you get a bonus of 5 points per leet item for deciding whether it should have a capital letter (i.e. capital letters at the start of sentences).

You get a further bonus of 5 points per leet item for implementing proper nouns (words which always have capitals) - the way this works is that you would look through the word list, make the output capitalised if only a capitalised version is present in the list, and if both versions are there, just guess.

If a character has two meanings (e.g. `1` can mean `L` or `I`), you get 20 points per leet item for only picking those translations of the item which make real English words - use the wordlist for this. If more than one translation of a leet item makes a real English word, you can arbitrarily pick one of the valid translations and still get the bonus.

# List of Leet

These are the leet items which you may implement. You don't have to implement all of them, but the more you add, the more points you get.

**You cannot ever score points by translating an item or character to itself. This rule overrides any mistakes I might have made in the list.**

It's tempting to do a simple `tr` or `s/.../.../g`. The real challenge is to determine which of multiple meanings could and couldn't be correct, using the wordlist.

## Leet Items (each of these adds 1 to `leet items` in the formula)

```
$      -> s,S
(      -> c,C
5      -> s,S
@      -> a,A
4      -> a,A
3      -> e,E
7      -> t,T
+      -> t,T
#      -> h,H
teh    -> the
'd     -> ed
pwnd   -> pwned
pwnt   -> pwned
k,K    -> OK
kk     -> OK
0[zero]-> o,O
y,Y    -> why
4      -> for
txt    -> text
dafuq  -> what the f**k
/\,^   -> a,A
\/     -> v,V
d00d   -> dude
n00b   -> newbie
\/\/   -> w,W
8      -> b,B
|_|    -> u,U
|-|    -> h,H
Я      -> r,R
j00    -> you
joo    -> you
vv,VV  -> w,W
tomoz  -> tomorrow
|<     -> k,K
[),|)  -> d,D
<3     -> love
><     -> x,X
10100111001       -> leet (binary representation of 1337)
2      -> to,too
ur,UR  -> your,you're (no need to correctly distinguish between the two)
u,U    -> you
8      -> -ate-,8
x,X    -> -ks-,-cks-
z,Z    -> s,S
1      -> i,I,l,L
!      -> i,I,!
c,C    -> see,C,sea
b,B    -> be,B,bee
[accented letter] -> [non-accented form] (score 1 per accented letter supported)
&,7    -> and,anned,ant (may be used in the middle of a word)

```

## Harder "Leet": score 30 points for `leet items` each

```
!!!1!!1-> !!!!!!! (translate 1's in a sequence of !'s into !'s)
!!!one!-> !!!!!
!eleven-> !!!

```

## Examples

These are examples of what a program which implements all the leet characters above, and some of the bonuses, might be able to do:

Example sentence: `|-|3 15 $|_|(# @ n00b` = `He is such a newbie`

Leet-based censorship: `$#!+` = `s**t`

Extreme leet: `\/\/ 1 |< 1 P 3 [) 1 A` = `Wikipedia`

-xor suffix: `H4X0R` = `hacker`

More extreme leet: `@1\/\/4Y5 p0$+ ur n3VV qu35710nz 1n teh $&80x` = `Always post your new questions in the sandbox`

## Example Scoring

Bash, 10 characters, 3 items, no bonuses:

```
tr 137 let

```

This scores `( 1 * 3 ) * 10 / 10 = 3`.

# Answer
# Javascript (49 + 5635) * 10 / 2174 = 26.14

**Online Demo:**

"Real dictionary" option doesnt work on drop box but it will work if run in a real web server. Tested in visual studio development server and google chrome.

https://dl.dropboxusercontent.com/u/141246873/leettranslator/index.html

**Score:**

49 leet items = 49

Capitalization bonus = 5 * 49 = 245

dictionary lookup bonus = 20 * 49 = 980

exclamation bonus * 3 = 90 * 49 = 4410

(leet items + bonuses) * 10 / (code length)

(49 + 5635) * 10 / 2174 = 26.14

**Code:**

```
function IsInDict(e) { return W[e] } function translate(e) { words = e.split(" "); res = ""; for (var t in words) { ex = ""; function n(e, r, i) { var s = false; for (var o = 1; o <= e.length; o++) { var u = e.substring(0, o) === "!" || i; var a = et[e.substring(0, o)]; var f = e.substring(o); if (a) { s = true; if (f.length === 0) { if (u) { ex = r + a; words[t] = "" } } else n(f, r + a, u) } } if (i && !s && r) { ex = r; words[t] = e.split("").reverse().join("") } } n(words[t].split("").reverse().join(""), "", false); mes = []; function r(e, t) { for (var n = 1; n <= e.length; n++) { var i = tokens[e.substring(0, n)]; var s = e.substring(n); if (i) { mFound = true; if (s.length === 0) for (var o in i) { mes.push(t + i[o]) } else for (var o in i) r(s, t + i[o]) } } if (e.length > 1) r(e.substring(1), t + e.substring(0, 1)); else { mes.push(t + e) } } m = ""; if (words[t] !== "") { r(words[t].toLowerCase(), ""); if (mes.length === 1) m = mes[0]; else { sl = []; for (var i in mes) { if (IsInDict(mes[i].slice(-1) === "." ? mes[i].substring(0, mes[i].length - 1) : mes[i])) { sl.push(mes[i]) } } if (sl.length > 0) m = sl[0]; else m = mes[0] } if (res === "") { m = cap(m) } if (res.slice(-1) === ".") { m = cap(m) } } res += " " + m; if (ex !== "") res += ex } return res.trim() } function cap(e) { return e.charAt(0).toUpperCase() + e.slice(1) } tokens = { $: ["s"], "(": ["c"], 5: ["s"], "@": ["a"], 4: ["a", "for"], 3: ["e"], "+": ["t"], "#": ["h"], teh: ["the"], "'d": ["ed"], pwnd: ["pwned"], pwnt: ["pwned"], k: ["ok"], kk: ["ok"], 0: ["o"], y: ["why"], txt: ["text"], dafuq: ["what the f**k"], "/\\": ["a"], "^": ["a"], "\\/": ["v"], d00d: ["dude"], n00b: ["newbie"], "\\/\\/": ["w"], 8: ["b", "ate"], "|_|": ["u"], "|-|": ["h"], "Я": ["r"], j00: ["you"], joo: ["you"], vv: ["w"], tomoz: ["tomorrow"], "|<": ["k"], "[)": ["d"], "|)": ["d"], "<3": ["love"], "><": ["x"], 10100111001: ["leet"], 2: ["to", "too"], ur: ["your", "you're"], u: ["you"], x: ["ks", "cks"], z: ["s"], 1: ["i", "l"], "!": ["i"], c: ["see", "sea"], b: ["be", "bee"], "&": ["and", "anned", "ant"], 7: ["and", "anned", "ant", "t"] }; et = { eno: "!", nevele: "!!", 1: "!", "!": "!" }

```

**Ungolfed:**

```
            tokens={
            '$':['s'],'(':['c'],'5':['s'],'@':['a'],'4':['a','for'],'3':['e'],'+':['t'],'#':['h'],'teh':['the'],"'d":['ed'],'pwnd':['pwned'],
            'pwnt':['pwned'],'k':['ok'],'kk':['ok'],'0':['o'],'y':['why'],'txt':['text'],'dafuq':['what the f**k'],
            '/\\':['a'],'^':['a'],'\\/':['v'],'d00d':['dude'],'n00b':['newbie'],
            '\\/\\/':['w'],'8':['b','ate'],'|_|':['u'],'|-|':['h'],'Я':['r'],'j00':['you'],
            'joo':['you'],'vv':['w'],'tomoz':['tomorrow'],'|<':['k'],'[)':['d'],'|)':['d'],'<3':['love'],
            '><':['x'],'10100111001':['leet'],'2':['to','too'],'ur':["your","you're"],
            'u':['you'],'x':['ks','cks'],'z':['s'],'1':['i','l'],'!':['i'],'c':['see','sea'],
            'b':['be','bee'],'&':['and','anned','ant'],'7':['and','anned','ant','t']}
            var excTokens = {'eno':'!','nevele':'!!','1':'!','!':'!'}

            function IsInDict(word)
            {
                return (W[word]);
            }

            function translate(input) {
                var words = input.split(" ");
                var result = "";
                for (var i in words) {
                    var exclamations = "";
                    function parseExclamations(s, prev, exclamationFound) {
                        var matchFound = false;
                        for (var j = 1; j <= s.length; j++) {
                            var hasExclamation = (s.substring(0, j) === "!") || exclamationFound;
                            var currentToken = excTokens[s.substring(0, j)];
                            var remaining = s.substring(j);
                            if (currentToken) {
                                matchFound = true;
                                if (remaining.length === 0) {
                                    if (hasExclamation) {
                                        exclamations = prev + currentToken;
                                        words[i] = "";//word only had exclamations in it so dont parse the rest of it
                                    }
                                }
                                else
                                    parseExclamations(remaining, prev + currentToken, hasExclamation);
                            }
                        }
                        if (exclamationFound && !matchFound && prev) {
                            exclamations = prev;
                            words[i] = s.split("").reverse().join("");//reverse back again
                        }
                    }
                    var reverseWord = words[i].split("").reverse().join("");
                    parseExclamations(reverseWord, "", false);

                    var matches = []
                    function parse(s, prev) {
                        for (var j = 1; j <= s.length; j++) {
                            var currentTokenArray = tokens[s.substring(0, j)];
                            var remaining = s.substring(j);
                            if (currentTokenArray) {
                                matchFound = true;
                                if (remaining.length === 0)
                                    for (var k in currentTokenArray) {
                                        matches.push(prev + currentTokenArray[k]);
                                    }
                                else
                                    for (var k in currentTokenArray)
                                        parse(remaining, prev + currentTokenArray[k]);
                            }
                        }

                        if (s.length > 1)
                            parse(s.substring(1), prev + s.substring(0, 1));
                        else {
                            matches.push(prev + s);
                        }
                    }

                    var match = "";
                    if (words[i] !== "") {
                        parse(words[i].toLowerCase(), "");

                        //check the dictionary
                        if (matches.length === 1)
                            match = matches[0];
                        else {
                            var shortlist = [];
                            for (var j in matches) {
                                //check dictionary. allow for a full stop at the end of the word
                                var isInDict = IsInDict(matches[j].slice(-1) === "." ? matches[j].substring(0, matches[j].length - 1) : matches[j]);
                                if (isInDict) {
                                    shortlist.push(matches[j]);
                                }
                            }

                            if (shortlist.length > 0)
                                match = shortlist[0];
                            else
                                match = matches[0];
                        }
                        if (result === "") {
                            match = cap(match);
                        }
                        if (result.slice(-1) === ".") {
                            match = cap(match);
                        }
                    }
                    result += " " + match;

                    if (exclamations !== "")
                        result += exclamations;
                }

                return result.trim();
            }

            function cap(string) {
                return string.charAt(0).toUpperCase() + string.slice(1);
            }

```

**Test results:**

* |-|3 15 $|\_|(# @ n00b ====\> He is such a newbie
* @1//4Y5 p0$+ ur n3VV qu35710nz 1n teh $&80x ====\> Always post your new questions in the sandbox
* !!!1!!1 ====\> !!!!!!!
* !!!one! ====\> !!!!!
* !eleven ====\> !!!
* teh!!!1!!1 ====\> The!!!!!!!
* teh!!!one! ====\> The!!!!!
* teh!eleven ====\> The!!!
* teh !!!1!!1 ====\> The !!!!!!!
* qu35710nz!1! ====\> Questions!!!
* +357 +357. 735+ ====\> Test test. Test
* & 31!73 #4(KER$ WR0+3 83773R L!K3 +#!5 7#@N 2D@Y ====\> And elite hackers wrote better like this than today

**Notes:**

The dictionary is a seperate javascript file with an object called W containing all of the words. This just contains the words I needed for running the relevant tests.
> 12 votes

# Answer
# Haskell - Score 1.421421421 : (37 items + (21 bonuses (capitalization) * 5)) * 10 / (999 bytes)

This is my final answer.

```
import System.Environment
import Text.Parsec
import Text.Parsec.String
s=string
r=return
t=try
o=oneOf
(>|)=(<|>)
a p l u=b[p]l u
b (p:q) l u=e(foldl(>|)(s p)$map(s)q)l u
c p l u=e(o p)l u
d p q=t$s p>>r q
e p l u=t$do{p;r l}>|do{s". ";p;r$". "++u}
f p q=t$do{between(t$s" ")(t$s" ")(o p);r q}
g::Parser String
g=do{s<-many$c"$5""s""S">|c"@4^""a""A">|c"3""e""E">|c"7+""t""T">|c"#""h""H">|d"teh""the">|d"'d""ed">|d"pwnd""pwned">|d"pwnt""pwned">|c"kK""ok""OK">|d"kk""OK">|d"n00b""newbie">|f"yY""why">|d"4""for">|d"txt""text">|d"dafuq""what the f**k">|b["\\/\\/","vv","VV"]"w""W">|a"/\\""a""A">|d"d00d""dude">|c"0""o""O">|a"\\/""v""V">|c"8""b""B">|a"|_|""u""U">|a"|-|""h""H">|c"Я""r""R">|b["j00","joo"]"you""you">|d"tomoz""tomorrow">|a"|<""k""K">|b["[)","|)"]"d""D">|d"<3""love">|a"><""x""X">|c"1!""i""I">|d"10100111001""leet">|c"2""too""to">|d"ur""your">|d"UR""you're">|f"uU""you">|c"xX""ks""cks">|d"&""and">|do{c<-anyChar;return [c]};return$concat s}
main=getArgs>>=putStrLn.show.(parse g"").concat

```

# Tests

When the program is compiled to a file named `min-lt`, you can write the following shell script

```
#!/bin/bash
./min-lt "|-|3 15 $|_|(# @ n00b"
./min-lt "\$#!+"
./min-lt "\/\/ 1 |< 1 P 3 [) 1 A"
./min-lt "H4X0R"
./min-lt "@1\/\/4Y5 p0$+ ur n3VV qu35710nz 1n teh $&80x"
./min-lt "+357 +357. 735+"

```

which will print this

```
Right "he is su(h a newbie"
Right "shit"
Right "w i k i P e d i A"
Right "HaksoR"
Right "aiwaYs post your new questionz in the sandboks"
Right "test test. Test"

```
> 7 votes

# Answer
# Extended BrainFuck : 0.6757

```
{a[-])&d}{c(-(-}{d)$t(-}:r:i:t$t,(-$i+$r+)$i($t 6+(-$i 5--)+$i 3+(--&c-(--
(3-(5-&c&c&c-&c--5-((-&d)$r.&d|"A"&a|"B"&a|"T"&a|"S"&a|"A"&a|"E"&a|"TO"&a
|"L"&a|"O"&a|"T"&a|"C"&a|"AND"&a|"S"&a|"H"&a|"I"(-))$i(-)$r(-)$t,(-$i+$r+))

```

So this does 15 translations "$(5@437+#0821!&" , no bonuses and it has 222 bytes (uneccesary linefeeds not included). 15\*10/222 = 0.6757

Usage:

```
%> beef ebf.bf < leet.ebf > leet.bf
%> echo '& 31337 #4(KER$ WR0+3 83773R L!K3 +#!5 7#@N 2D@Y' | beef  leet.bf
AND ELEET HACKERS WROTE BETTER LIKE THIS THAN TODAY
%>

```

EBF isn't really made for golfing but it's rle feature, macros and print string feature makes it somewhat easier to compress than BrainFuck. The end compiled BrainFuck binary looks like this:

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

```
> 7 votes

# Answer
# Java : 1.236

```
import java.util.*;public class L{static H<String,String>c;static H<String,String>w;static{c=new H();c.p("1","i");c.p("!","i");c.p("$","s");c.p("5","s");c.p("@","a");c.p("4","a");c.p("3","e");c.p("7","t");c.p("+","t");c.p("#","h");c.p("'d","ed");c.p("0","o");c.p("zero","o");c.p("\\/\\/","w");c.p("/\\","a");c.p("\\/","v");c.p("|<","k");c.p("[)","d");c.p("8","b");c.p("|_|","u");c.p("|-|","h");c.p("Я","r");c.p("(","c");c.p("VV","w");c.p("&","and");c.p("2","to");w=new H();w.p("@","a");w.p("teh","the");w.p("pwnd","pwned");w.p("pwnt","pwned");w.p("k","ok");w.p("kk","ok");w.p("y","why");w.p("Y","why");w.p("4","for");w.p("txt","text");w.p("dafuq","what the f**k");w.p("d00d","dude");w.p("n00b","newbie");w.p("j00","you");w.p("joo","you");}public static void main(String[]a){System.out.println(new L().C(a));}String C(String[]o){String x=T(o);for(String d:o){if(w.containsKey(d))x=x.replace(d,w.get(d));else{String r=d;for(String y:c.keySet()){if(d.contains(y))r=r.replace(y,c.get(y));}x=x.replace(d,r);}}return x;}String T(String[]l){String s="";for(String w:l)s+=" "+w;return s;}}class H<T1,T2>extends LinkedHashMap<T1,T2>{T2 p(T1 k,T2 v){return super.put(k,v);}}

```

So it does the following transformations

```
+357 +357. 735+
test test. test
|-|3 15 $|_|(# @ n00b
he is such a newbie
$#!+
shit
\/\/ 1 |< 1 P 3 [) 1 A
w i k i P e d i A
@1\/\/4Y5 p0$+ ur n3VV qu35710nz 1n teh $&80x
aiwaYs post ur new questionz in the sandbox
& 31337 #4(KER$ WR0+3 83773R L!K3 +#!5 7#@N 2D@Y
and eieet hacKERs WRote betteR LiKe this thaN toDaY

```

The score calculation is tricky

* (leet items + bonuses) * 10 / (code length)
* code length = 1165 leet
* leet items = 39 (unique)
* bonus = 21 (do not know how to calculate so copied MomemtumMori) (Please advise)

((39 + (21\*5)) * 10) / 1165 = 1.236

Un-Golfed code :

```
import java.util.*;

public class L {
    static H<String, String> c;
    static H<String, String> w;

    static {
        c = new H();
        c.p("1", "i");
        c.p("!", "i");
        c.p("$", "s");
        c.p("5", "s");
        c.p("@", "a");
        c.p("4", "a");
        c.p("3", "e");
        c.p("7", "t");
        c.p("+", "t");
        c.p("#", "h");
        c.p("'d", "ed");
        c.p("0", "o");
        c.p("zero", "o");
        c.p("\\/\\/", "w");
        c.p("/\\", "a");
        c.p("\\/", "v");
        c.p("|<", "k");
        c.p("[)", "d");
        c.p("8", "b");
        c.p("|_|", "u");
        c.p("|-|", "h");
        c.p("Я", "r");
        c.p("(", "c");
        c.p("VV", "w");
        c.p("&", "and");
        c.p("2", "to");
        w = new H();
        w.p("@", "a");
        w.p("teh", "the");
        w.p("pwnd", "pwned");
        w.p("pwnt", "pwned");
        w.p("k", "ok");
        w.p("kk", "ok");
        w.p("y", "why");
        w.p("Y", "why");
        w.p("4", "for");
        w.p("txt", "text");
        w.p("dafuq", "what the f**k");
        w.p("d00d", "dude");
        w.p("n00b", "newbie");
        w.p("j00", "you");
        w.p("joo", "you");
    }

    public static void main(String[] a) {
        System.out.println(new L().C(a));
    }

    String C(String[] o) {
        String x = T(o);
        for (String d : o) {
            if (w.containsKey(d)) x = x.replace(d, w.get(d));
            else {
                String r = d;
                for (String y : c.keySet()) {
                    if (d.contains(y)) r = r.replace(y, c.get(y));
                }
                x = x.replace(d, r);
            }
        }
        return x;
    }

    String T(String[] l) {
        String s = "";
        for (String w : l) s += " " + w;
        return s;
    }
}

class H<T1, T2> extends LinkedHashMap<T1, T2> {
    T2 p(T1 k, T2 v) {
        return super.put(k, v);
    }
}

```
> 3 votes

# Answer
## C# score 45\*10/2556=0.176

Program can output almost all lower and upper case letters. Since I'm not using a english word list the first key found in the Dictionary is used. E.g \\/\\/ becomes vav. If char is first letter of a word ToUpper is applied.

```
using System;
using System.Collections.Generic;
class L
{
Dictionary<string, string> D;
public L()
{
D = new Dictionary<string, string>();
M();
}
public void M()
{
D.Add("$", "s,S");
D.Add("(", "c,C");
D.Add("5", "s,S");
D.Add("@", "a,A");
D.Add("4", "a,A,for");
D.Add("3", "e,E");
D.Add("7", "t,T,and,anned,ant");
D.Add("+", "t,T");
D.Add("#", "h,H");
D.Add("teh", "the");
D.Add("'d", "ed");
D.Add("pwnd", "pwned");
D.Add("pwnt", "pwned");
D.Add("k", "OK");
D.Add("K", "OK");
D.Add("kk", "OK");
D.Add("0", "o,O");
D.Add("y", "why");
D.Add("Y", "why");
D.Add("txt", "text");
D.Add("dafuq", "what the f**k");
D.Add("\\/\\/", "w,W");
D.Add("/\\", "a,A");
D.Add("^", "a,A");
D.Add("\\/", "v,V");
D.Add("d00d", "dude");
D.Add("n00b", "newbie");
D.Add("8", "b,B,ate,8");
D.Add("|_|", "u,U");
D.Add("|-|", "h,H");
D.Add("j00", "you");
//Я      -> r,R
D.Add("joo", "you");
D.Add("vv", "w,W");
D.Add("VV", "w,W");
D.Add("tomoz", "tomorrow");
D.Add("|<", "k,K");
D.Add("[)", "d,D");
D.Add("|)", "d,D");
D.Add("<3", "love");
D.Add("><", "x,X");
D.Add("2", "to,too");
//10100111001       -> leet (binary representation of 1337)
D.Add("ur", "your,you're");
D.Add("UR", "your,you're");
D.Add("u", "you");
D.Add("U", "you");
D.Add("x", "ks,cks");
D.Add("X", "ks,cks");
D.Add("z", "s,S");
D.Add("Z", "s,S");
D.Add("1", "i,I,l,L");
D.Add("!", "i,I,!");
D.Add("c", "see,C,sea");
D.Add("C", "see,C,sea");
D.Add("b", "be,B,bee");
D.Add("B", "be,B,bee");
//[accented letter] -> [non-accented form] (score 1 per accented letter supported)
D.Add("&", "and,anned,ant");
}

int P(string K, out List<string> V)
{
V = new List<string>();
string v,comma=",";
if(D.TryGetValue(K,out v))
{
string[] vv = v.Split(comma.ToCharArray());
foreach(string s in vv)
{
V.Add(s);
}
}
return V.Count;
}

public string E(string X)
{
string e ="";
string S = " ",t,k="";
string[] W = X.Split(S.ToCharArray());
int n = 0,x=0,m=0;
List<string> V=new List<string>();
bool F = false;
foreach(string s in W)
{
n = s.Length;
F = false;
for (int i = 0; i < n; i++)
{
m = 0;
for (int j = 1; j < n - i+1; j++)
{
k = s.Substring(i, j);
x = P(k, out V);
if (x > 0)
{
t = V[0];
if (t.Length == 1 && i == 0)
t = t.ToUpper();
e += t;
m = t.Length;
F = true;
break;
}
}
if (m > 0) i += (m - 1);
}
e += S;
}
return e;
}
static void Main(string[] a)
{
string t = Console.ReadLine();
L x = new L();
t = x.E(t);
Console.WriteLine(t);
Console.ReadLine();
}
}

```

Here's my test output:

```
$ -> S
( -> C
5 -> S
@ -> A
4 -> A
3 -> E
7 -> T
+ -> T
# -> H
teh -> the
'd -> ed
pwnd -> pwned
pwnt -> pwned
k -> OK
K -> OK
0 -> O
y -> why
Y -> why
4 -> A
txt -> text
dafuq -> what the f**k
/\ -> A
^ -> A
\/ -> V
d00d -> dude
n00b -> newbie
\/\/ -> Vav
8 -> B
|_| -> U
|-| -> H
j00 -> you
joo -> you
vv -> W
VV -> W
tomoz -> tomorrow
|< -> K
[) -> D
|) -> D
<3 -> love
>< -> X
2 -> to
ur -> you
UR -> you
u -> you
U -> you
8 -> B
x -> ks
X -> ks
z -> S
Z -> S
1 -> I
! -> I
c -> see
C -> see
b -> be
B -> be

```
> 1 votes

---
Tags: code-challenge, string, natural-language
---


title: Implement a reversi engine

text:
# Question
Title: Implement a reversi engine
Your job, for this golf, is to write a program that will take moves of a game of reversi (othello) and display the result to the user.

### Input

A string of numbers taken from the range \[0-7\]. Each pair of numbers represent first the X coordinate, then the Y coordinate. Any characters not in that range should be ignored.

### Output

A visual representation of the result of the game, including who is leading when the input ends. This may be graphical or keystroke output, but it must be a visual grid of the game, with a distinct character/graphical symbol for black, white, and empty.

Additionally, your code should output an error message and stop when an illegal move is entered (the same square more than once, or a square that will not flip any tiles).

**Skips** should be handled gracefully. A skip occurs when one color has no legal move, their turn is skipped and the other player gets to play.

Black always goes first.

### Examples

```
23
........
........
........
..bbb...
...bw...
........
........
........
b

232425140504032627
........
........
........
b.bbb...
bbbww...
b.b.....
..b.....
..b.....
b

2324322513
........
........
........
..bbb...
..www...
........
........
........
e

23242555
........
........
........
..bbb...
..bbw...
..b.....
........
........
e

```

# Answer
> 2 votes
# Haskell - 1493 bytes

In this version, there are no detailed error messages and the output is much more basic. The major change was replacing `Either String a` with `Maybe a` and since they are both monads, this was acheived by simply swapping `Right a` with `Just a` and `Left String` with `Nothing`.

```
{-# LANGUAGE OverloadedStrings #-}
import Prelude hiding ((>>=),concatMap,filter,foldl,head,last,map,null,replicate)
import Control.Applicative hiding (empty)
import Control.Monad hiding (replicateM)
import Data.Vector hiding ((++),concat,foldM,reverse,zip)
main=getLine>>= \s->h$t<$>(zip$cycle[w,v])<$>b s>>= \m->u(\b(c,x)->case d b x c of r@(Just _)->r;Nothing->if not$null$findIndices(\y->e$d b y c)$t[(x,y)|x<-[0..7],y<-[0..7]];then é;else d b x$not c)k$n m
 where b(x:y:s)=(:)(read [x],read [y])<$>b s;b(_:_)=é;b[]=è[];d b z c=let d=join$m(f b z c)$m(\v->(head v,last v))$replicateM 2$t[-1,0,1];in if null d;then Nothing;else u(\b (x,y)->case b!?y of Just r->(case r!?x of Just _->è$b//[(y,r//[(x,è c)])];Nothing->é);Nothing->é)b$n$d`snoc`z;e(Nothing)=w;e(Just _)=v;f b(x,y)c z@(u,v)=let r=x+u;s=y+v;t=(r,s);in (case g b t of Just(Just d)->if d==c;then l;else (case g b (r+u,s+v) of Just(Just _)->t`cons`f b t c z;_->l);Just(Nothing)->l;Nothing->l);g b(x,y)=(case b!?y of Just col->col!?x;Nothing->é);h(Just b)=p$(o$n$m(\r->o(n$m(\c->case c of Just False->"B";Just True->"W";Nothing->".")r)++"\n")b)++i(q(\(w,b)(rw,rb)->(w+rw,b+rb))(0,0)$m(\r->q(\s@(w,b)c->case c of Just True->(w+1,b);Just False->(w,b+1);_->s)(0,0)r)b);h Nothing=p"e";i(w,b)|w>b="W"++s w|b>w="B"++s b|v="N"++s(w+b);j=r 8 é;k=r 8 j//[(3,j//[(3,è v),(4,è w)]),(4,j//[(3,è w),(4,è v)])];l=empty;m=map;n=toList;o=concat;p=putStrLn;q=foldl;r=replicate;s=show;t=fromList;u=foldM;v=True;w=False;é=Nothing;è=Just

```

```
$ printf "232425140504032627" | ./nano-rve
........
........
........
B.BBB...
BBBWW...
B.B.....
..B.....
..B.....
B11

```

# Original version - 4533 bytes

I will golf when there will be competition! **edit** It has arrived

```
{-# LANGUAGE OverloadedStrings #-}
import Prelude hiding ((>>=),concatMap,filter,foldl,map,null,replicate)
import Control.Applicative hiding (empty)
import Control.Monad
import Data.Either
import Data.Vector hiding ((++),concat,foldM,reverse,zip)

type Case = Maybe Bool
type Board = Vector (Vector Case)
type Coord = (Int,Int)

-- fmap (toList) $ replicateM 2 [-1,0,1] -- minus (0,0)
directions :: Vector Coord
directions = fromList [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]

--  [(x,y) | x <- [0..7], y <- [0..7]]
allCoords :: Vector Coord
allCoords = fromList [(0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7),(1,0),(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(2,0),(2,1),(2,2),(2,3),(2,4),(2,5),(2,6),(2,7),(3,0),(3,1),(3,2),(3,3),(3,4),(3,5),(3,6),(3,7),(4,0),(4,1),(4,2),(4,3),(4,4),(4,5),(4,6),(4,7),(5,0),(5,1),(5,2),(5,3),(5,4),(5,5),(5,6),(5,7),(6,0),(6,1),(6,2),(6,3),(6,4),(6,5),(6,6),(6,7),(7,0),(7,1),(7,2),(7,3),(7,4),(7,5),(7,6),(7,7)]

initBoard :: Board
initBoard = vs // [(3,v1),(4,v2)]
    where va = replicate 8 Nothing
          v1 = va // [(3,Just True),(4,Just False)]
          v2 = va // [(3,Just False),(4,Just True)]
          vs = replicate 8 va

showBoard :: Board -> String
showBoard b = (concat $ toList $ map (showRow) b) ++ (showScore b)
    where showCase :: Case -> String
          showCase c = case c of
              Just False -> "░B"
              Just True -> "▓W"
              Nothing -> "██"
          showRow :: Vector Case -> String
          showRow r = concat (toList $ map (showCase) r) ++ "\n"

showScore :: Board -> String
showScore b = winner score ++ "\n"
    where scoreCase :: (Int,Int) -> (Maybe Bool) -> (Int,Int)
          scoreCase (w,b) (Just True) = (w+1,b)
          scoreCase (w,b) (Just False) = (w,b+1)
          scoreCase s _ = s
          scoreRow :: Vector Case -> (Int,Int)
          scoreRow r = foldl (scoreCase) (0,0) r
          score :: (Int,Int)
          score = foldl (\(w,b) (rw,rb) -> (w+rw,b+rb)) (0,0) $ map (scoreRow) b
          winner :: (Int,Int) -> String
          winner (w,b) | w > b = "White with " ++ show w ++ " against Black with " ++ show b ++ "."
                       | b > w = "Black with " ++ show b ++ " against White with " ++ show w ++ "."
                       | otherwise = "Nobody with " ++ show (w+b) ++ "."

printBoard :: Board -> IO ()
printBoard b = putStrLn $ showBoard b
pm :: Either String Board -> IO ()
pm (Right b) = printBoard b
pm (Left s)  = putStrLn s

lookupBoard :: Board -> Coord -> Either String Case
lookupBoard b (x,y) = case b !? y of
    Just col -> case col !? x of
        Just c -> Right c
        Nothing -> Left "x is out of bounds"
    Nothing -> Left "y is out of bounds"

updateBoard :: Board -> Coord -> Bool -> Either String Board
updateBoard b (x,y) c = case b !? y of
    Just r -> case r !? x of
        Just _ -> Right $ b // [(y,r // [(x,Just c)])]
        Nothing -> Left "x is out of bounds"
    Nothing -> Left "y is out of bounds"

makePath :: Board -> Coord -> Bool -> Coord -> Vector Coord
makePath b (x,y) c (px,py) = case lookupBoard b (nx,ny) of
        Right (Just pc) -> if pc == c
            then empty
            else case lookupBoard b (nx+px,ny+py) of
                Right (Just _) -> (nx,ny) `cons` makePath b (nx,ny) c (px,py)
                _ -> empty
        Right (Nothing) -> empty
        Left _ -> empty
    where nx = x+px
          ny = y+py

makeMove :: Board -> Coord -> Bool -> Either String Board
makeMove b xy@(x,y) c = if null cases
        then Left $ "impossible move " ++ show xy ++ "."
        else foldM (\ob (cx,cy) -> updateBoard ob (cx,cy) c) b $ toList $ cases `snoc` (x,y)
    where cases = join $ map (makePath b (x,y) c) directions

makeMoves :: Board -> Vector (Bool,Coord) -> Either String Board
makeMoves b ms = foldM (\ob (c,xy) -> case makeMove ob xy c of
    rb@(Right _) -> rb
    Left _ -> if not $ null $ findIndices (\xy -> isRight $ makeMove ob xy c) allCoords
        then Left $ "wrong move " ++ show xy ++ "."
        else makeMove ob xy (not c)) b $ toList ms

movesFromString :: String -> Either String (Vector (Bool,Coord))
movesFromString cs = fromList <$> (zip $ cycle [False,True]) <$> coords cs
    where coords (x:y:cs) = (:) (read [x],read [y]) <$> coords cs
          coords (_:cs) = Left "invalid coordinates string"
          coords [] = Right []

isRight :: Either a b -> Bool
isRight (Left _) = False
isRight (Right _) = True

main=getLine>>= \s->pm$movesFromString s>>=makeMoves initBoard

```

Note : Your second example should be 2324251**4**0504032627.

# Tests

With screenshots to prevent eye burns.

```
$ printf "232425140504032627" | ./rve

```

```
$ printf "2324" | ./rve

```

```
$ printf "1" | ./rve
invalid coordinates string

```

```
$ printf "24" | ./rve
wrong move (2,4).

```

Is is possible to get `impossible move (x,y)` when you use innardics (functions from the innards of the program and that you should not use) and `x/y is out of bounds`.

# Answer
> 1 votes
# Javascript (E6) 399 ~~412 450~~

Edit: board display shorter and nicer, cut some char

```
V=(p,b)=>b[p]==(r=0)&&[1,8,9,10].map(d=>r|=(A=(p,d,c=0)=>b[p+=d]==-v?A(p,d,1)&&(b[p]=v):c&b[p]==v)(p,d)|A(p,-d))|r&&(b[p]=v)
L=console.log
l=prompt().replace(/[^0-7]/g,'')
for(i=B=[];++i<73;)B[i]=i%9?i-31&&i-41?i-32&&i-40?0:1:-1:-B
for(v=i=1;l[i];i+=2,v=-v)V(p=l[i]*9+-~l[i-1],B)||!B.some((x,i)=>V(i,[...B]))&&(V(p,B,v=-v))||L(l='Err')
t=0,L(B.map(x=>(t+=~~x,'\nO ☻'[x+2|0]))+(t?t<0?'O':'☻'+t:'='))

```

**Ungolfed**

```
V = (p, b) =>      // Verify a move and if it is legal, apply the move to the board
b[p]==(r=0) &&     // check if empty cell and init accumulator r
[1,8,9,10].map(d=> // Execute flip check for each of 4 positive direction (and 4 negative too)
  r |= (
  A=(p,d,c=0) =>   // Recursive function for flip check, if find it valid modify the board during return phase
  b[p+=d] == -v    // If position contains a disk of other color
   ? A(p,d,1) && (b[p]=v) // recursive call. Then if returns true, set the cell in the flip sequence
   : c & b[p]==v   // at end of check, if find the righe disk and if not the first call, return true
  )                // Definition of A function ends here
  (p,d)|A(p,-d)    // Call A 2 times with d and -2 to get all 8 directions
) | r              // now, r is true if any of the 8 flip checks has gone well
&& (b[p]=v);       // if true, set the verified cell too

L=console.log;

l=prompt().replace(/[^0-7]/g,'');            // Get input & discard invalid chars

for (i=B=[];++i<73;) // Create empty board as a single dimension array, NaN mark a row end
  B[i] = i%9
    ? i-31 && i-41
      ? i-32 && i-40
        ? 0: 1: -1: -B //starting values at center, -B evaluate to NaN

for(v=i=1;    // v is the disk color, init to 1 == black
  l[i];       // repeat while inside input string
  i+=2, v=-v) // to char of input at time, set color to opposite
    V( p=l[i]*9+-~l[i-1], B)      // calc position in p from the input, and call Verify
    ||                            // if not valid, could be Error or Skip
      !B.some((x,i)=>V(i,[...B])) // Check if there are no moves for the current color, for each cell call V on a copy of the board
      &&
      (V(p,B,v=-v)) // If no moves found, try to apply the move for the opposite color
    ||
      L(l='Err');   // If failed, it is Error. Change variable l to end the loop

t=0, // Display the board while counting disk difference into 't'
L(
  B.map(x=>(t+=~~x,'\nO ☻'[x+2|0])) // map array elements to suitable chars, then auto conversion to string give a nice effect
  + (t?t<0?'O':'☻'+t:'=')
) // Display leading and count difference or '='

```

**Test**

Test in javascript console (FireFox): `232425140504032627` `, , , , , , , , ,
, , , , , , , , ,
, , , , , , , , ,
,☻, ,☻,☻,☻, , , ,
,☻,☻,☻,O,O, , , ,
,☻, ,☻, , , , , ,
, , ,☻, , , , , ,
, , ,☻, , , , , ,
☻9`

---
Tags: code-golf, board-game
---


# Question
Title: Determine stability of a system using the Routh-Hurwitz stability criterion
The Routh-Hurwitz is a criteria which serves to prove or disprove the stability of an electric control system.

# Idea

Given a system which has an equation of the form `P(s)/Q(s)` where `P(s)` and `Q(s)` are polynomials of any degree, it is said to be stable if all the roots of the polynomial `Q(s)` are in the left half of the complex plane, which means the real part of the root is negative.

For polynomials of degree less than or equal to 2, it is trivial to determine the roots and notice whether or not the system is stable. For polynomials `Q(s)` of higher degrees, the Routh–Hurwitz theorem can be useful to determine whether the system is Hurwitz-stable or not.

# Process

One of the methods to apply this theorem for any degree is described on Wikipedia that consists of performing operations on rows of a table, then counting the number of sign changes in the first column of the table. It goes as follows:

* Fill the first two rows with the coefficients of the polynomial, in the following pattern: 1st row consists of the even coefficients `s^n`, `s^n-2`, ..., `s^2`, `s^0`; 2nd row consists of the odd coefficients `s^n-1`, `s^n-3`, ..., `s^3`, `s^1`;
* Keep calculating the following rows by calculating the determinant of the matrix (last 2 rows of the first column, last 2 rows of the next column) divided by (the value of the first column on the row above); it is detailed in this part of the Wikipedia article.
* If you encounter a row full of zeros, set it to the derivative of the polynomial that the row above it represents. Depending on the row it is on, the number on each cell represents a coefficient. It is illustrated in the example later.
* If you encounter a zero with other non-zero values, the system is not stable: you can stop there. (You could continue but you'll get the same result). A zero on the first column would mean a root of real value 0, which renders the system unstable.
* Otherwise, continue until the end. Then, if not all the values in the first column are of the same sign, the system is not stable.

# Examples

Here are some examples of that process:

```
# Polynomial: 1 3 6 12 8.00

s^4  1 6  8
s^3  3 12 0
s^2  2 8  0
s^1--0-0--0-- < Row of zero - replace it by:
s^1  4 0  0   < Derivative 2*s^2 + 8*s^0 = 4*s^1
                 (between each 2 columns the power of s is lowered by 2)
s^0  8 0  0   < Continue normally

# Sign Changes: 0 (equivalent to no root in the right half plane)
# Stable: Yes

```

Another one:

```
s^2   1  -2
s^1   1   0
s^0  -2   0

# Sign Changes: 1 (equivalent to 1 root in the right half plane)
# Stable: No

```

# Rules

* The program will keep reading polynomials from standard input until a blank line, and output `0`/`1` for stable/non-stable respectively for each polynomial on a new line.
* The program can read the polynomial coefficients in any form. It could be `1 3 6 12 8` for the first example (it suits this problem better, but it doesn't really matter in the end).
* It has to handle cases where `0` in the first column, or `0` in the following columns, or a row full of `0` is encountered properly. (Note: just in case, no need to see how many roots are in rhp/lhp/jw axis).
* It can short-circuit the process at any time if a condition is met, there is no need to show the RH table in the end.
* You do not have to use this method. Any method which will determine whether or not a system is Hurwitz-stable can do the job.
* It doesn't matter which language you chose to do it with, as long as it's not done in one single built-in function call. I did mine in Python, I'll post it soon.
* This is a code golf. The shortest code wins.

Here's a sample input/output (given in the above mentioned way) to test your program with:

```
#input:
1 12 6 10 10 6 14
1 1 -2
1 2 1 2
1 3 1 3 16
1 2 3 6 2 1
1 2 14 88 200 800
1 2 3 6 2 1
1 3 6 12 8
1 4 5 2 4 16 20 8

#output:
0
0
1
0
0
0
0
1
0

```

If you need more clarifications, let me know, I'll do my best to clarify.

# Answer
## Haskell - 264 bytes

```
p(a:b:s)=(a,b):p s
p[a]=[(a,0)]
p[]=[]
s((a:w),m@(b:v))=a:s(m,m%zipWith(\c d->(b*c-a*d)/b)w v)
s((a:_),_)=[a]
m%(0:v)|all(==0)v=fst$foldr(\b(d,p)->(b*p:d,2+p))([],0)m
m%v=v
q(a:s)|all((>0).(a*))s="1\n"
q _="0\n"
main=interact$(>>=q.s.unzip.p.map read.words).lines

```

Running the sample inputs:

```
& runhaskell 11847-Stability.hs
1 12 6 10 10 6 14
1 1 -2
1 2 1 2
1 3 1 3 16
1 2 3 6 2 1
1 2 14 88 200 800
1 2 3 6 2 1
1 3 6 12 8
1 4 5 2 4 16 20 8
0
0
1
0
0
0
0
1
0

```

(The output is interleaved with the input if you type it one line at a time, as per spec. If you bulk paste, you see all the output after the input.)
> 1 votes

# Answer
# Python (645 bytes)

That's what I managed to do (and golf):

```
from decimal import*
R=xrange
def s(p):
 d=len(p)
 if 0 in p:return 0
 elif sum(1 for c in p if c>0) not in (0,d):return 0
 p=p+[0] if d%2 else p[:]
 r=[[0 for j in R(len(p)//2)] for i in R(d)]
 r[:2]=[[v for v in p[i::2]] for i in (0,1)]
 for i in R(2,len(r)):
  a,h,b = 1,0,0
  for k in R(len(r[i])-1):
   v=(r[i-1][0]*r[i-2][k+1]-r[i-2][0]*r[i-1][k+1])/r[i-1][0]
   r[i][k],a,h,b=v,a and v==0,h or v==0,b or (h and v!=0)
  if a:r[i]=[v*max(0,d-i-2*k) for k,v in enumerate(r[i-1])]
  elif b:return False
 return sum(1 for v in r if v[0]>0) in (0,d)
while 1:
 r=raw_input()
 if not r:break
 print 1 if s([Decimal(x) for x in r.split()]) else 0

```

It takes as input the coefficients of the polynomials in decreasing order (highest power of s to lowest 0).
> 0 votes

---
Tags: code-golf, calculus
---


title: Solving a "Ubongo"-puzzle

text:
# Question
Title: Solving a "Ubongo"-puzzle
Some time ago I came across a game called Ubongo. The player got four shapes and has to put them together in a way, that the shapes form the shape of the board. One example is this:

Note that the shapes can be turned or rotated. Your goal is to write a programm that takes the board and the 4 shapes as parameter (command line or user input, handle it your way) and prints the solution (a graphical solution or a **human-readable** solution).

**Example (same as above):**
Input (board size, board information (0 for nothing, 1 for board field), 4x shape size and shape information (same as board information)):

```
>myprogram
5 5
11000
11000
11101
11111
00111
2 4
10
10
11
10
1 2
1
1
2 3
01
11
01
2 3
01
11
11

```

Output:

```
12000
12000
11304
13344
00344

```

(0 stands for nothing, 1 for the first shape given in the input, 2 for the second shape etc.)
Note that the choice of input and output is completely free, it should just be easy to understand.

The winner will be crowned two weeks from when the question was posted. The winner will be the person with the least code length.

**EDIT :**
You can assume that there is a solution to the given board and pieces. If there is no solution, your program does not have to work (but it would be nice if it prints an error message). For those, who need more tests, I found solutions to several puzzles with several boards and pieces here.

# Answer
> 1 votes
### GolfScript, 210 characters

```
n%{(~\;/(\[]:f*}5*;].,,]zip{~{.!+`\1`/*n*~]}+%}%(:b{,:^1,*}%]({^,{[^1,*:e.@<\]`{\*^<}+1$%:a;b,:h,{[[e]h*.@<\]a*h<}/}%{.zip{.-1%.zip}3*}%.&`{{[[f*1$f*]zip{~+}%b f*]zip{~*}%^/}%~}+@%{1$f*0-.@f*@0={=}+,=},\;}/0=n*

```

This is a first attempt using GolfScript. Input must be given on STDIN in the same format as the example in the question. The output format results from an implementation error (using ascii values instead of numerics) but I left it in this form because it is short and looks nice.

```
☺☻
☺☻
☺☺♥ ♦
☺♥♥♦♦
  ♥♦♦

```

# Answer
> 2 votes
# Python 2.x - 679 543 443 417 406 383 372 361 bytes

I'm actually pretty sad about this one. I am sure I missed something obvious. I'll be looking at this again later. Starting to feel good about this one.

```
543 - Edit 1: Discarding efficiency in favor of code length.
443 - Edit 2: Made the algorithm a lot simpler, fixed it (it couldn't handle flips) and
              removed ungolfed code because it wasn't relevant anymore.
417 - Edit 3: Rotate was only being used once anymore. Inlined it. Something else too.
406 - Edit 4: Made it accept only four shapes, as the spec says. Also reduced efficiency again.
383 - Edit 5: Ultimate abuse of exec. Shorter code and longer execution time!
372 - Edit 6: Every recursion now makes a copy of the current board, which is removed if
              the pieces don't fit. No more master board and no more emptying placed pieces.
361 - Edit 7: Removed unnecessary stuff. Also added the byte counts to changelog.

```

---

```
(q,g),O,s=input()
O=[x*6for x in sum(O,[])]
A='z,k=s[i];'+('z,k=z[::-1],zip(*k[::-1]);r=r or c(i+1,z,k,O);'*4+'k=map(reversed,k);')*2
def c(i,(w,h),p,o,r=0):
 for x in range(g*q):O=o[:];f=1;I=0;exec"P=x+I/w*q+I%w;exec('f=0','O[P]=i')[g*q>P>=0and O[P]>4]*p[I/w][I%w];I+=1;"*w*h;exec(i<4*f)*A;r=O*(i*f>3)or r
 return r
i=r=0;exec A+'print`r[i:i+q]`[1::3];i+=q;'*g

```

It takes the input in an array format. Example:

```
In:  [5,5],[[1,1,0,0,0],[1,1,0,0,0],[1,1,1,0,1],[1,1,1,1,1],[0,0,1,1,1]],[[[2,4],[[1,0],[1,0],[1,1],[1,0]]],[[1,2],[[1],[1]]],[[2,3],[[0,1],[1,1],[0,1]]],[[2,3],[[0,1],[1,1],[1,1]]]]
Out: 12000
     12000
     11304
     13344
     00344

In:  [6,5],[[0,1,1,1,1,0],[1,1,1,1,1,0],[1,1,1,1,1,0],[0,1,1,1,1,0],[0,0,1,1,1,1]],[[[2,4],[[1,0],[1,0],[1,1],[1,1]]],[[3,3],[[1,1,0],[0,1,1],[0,1,1]]],[[3,3],[[0,0,1],[1,1,1],[1,0,0]]],[[2,4],[[0,1],[1,1],[0,1],[0,1]]]]
Out: 033110
     223110
     223310
     022410
     004444 (thanks, edc65)

```

Quick explanation, if you can't read it. The function checks every possible position for a piece. Whenever the piece fits, it recursively checks that all other pieces fit too. When all pieces fit, the board is filled (pieces are placed on the board when checking) and it can be outputted straight away.

# Answer
> 1 votes
# Javascript (E6) 316 ~~350 392 487 537 590~~

Board size limited to 6x6 to save runtime. With the same character count the limit could be 9x9. Any number of pieces

```
    F=(d,b,h)=>{R=s=>[...s].reverse(),Q=(n,i,k)=>{h[n]&&[t=h[n][1],t[0].map((c,i)=>t.map(r=>r[i]))].map(e=>[e,R(e),e.map(R),R(e).map(R)].map(s=>{for(i=36;i--;)k=b.map(x=>[...x]),s.some((u,q)=>!(w=b[~~(i/6)+q])||u.some((v,p)=>(c=i%6+p,v&&!(v=w[c]!=1)&&!(w[c]=n+2)||v)))||Q(n+1),b=k}))||console.log(b.join('\n'))},Q(0)}

```

---

**History**

*316* \- Slooower! The board is copied again for each recursive call. (Ab)using slower functions chosen for shorter names. The main loop on board rows and colums coalesced into one for. Also put a limit for board size up to 6x6 (not for short code, but for acceptable runtime)
*350* \- Golfed using more array traversing function and less loops
*392* \- Algorithm not changed: try to place a piece, if ok try next, recursive, but use arrays only and not strings and use a single global board and not copy it during recursion (so it must be able to put a piece AND to remove it)
...

**Ungolfed** a bit

```
F = (d,b,h)=>{
  R = s => [...s].reverse(), // ... instead of slice that is faster
  Q = (n,i,k) => // Recursive function, fake param i to avoid vars
  {
    h[n] && // If there is still a piece to place, try to place it
    [t=h[n][1], t[0].map((c,i) => t.map(r => r[i]))]
      .map(e => // for e in :piece, transposed piece
        [e, R(e), e.map(R), R(e).map(R)]
        .map(s =>
          { // for s in : base piece, reversed, mirrored, diagonal
            for(i = 36; i--;) // 6x6: could be higher but slows down
              k = b.map(x=>[...x]), // save copy of board (again ... instead of slice)
              s.some( (u,q) => // traverse with 'some' to exit early if invalid position
                !(w=b[~~(i/6)+q])
                || u.some((v,p) => (c=i%6+p, v && !(v=w[c]!=1) && !(w[c]=n+2)||v))
              ) || Q(n+1), // if piece place, recurse
              b=k // recover the board from the copy
          }
      )) // if no more pieces, output result
    || console.log(b.join('\n' /** ,Q=_=>0 **/)) // remove comment to stop at first solution found
  },
  Q(0) // First call
}

```

**Usage**

Test in javascript console (Firefox) Input parameters as array.

Time to finish is 50 sec on my PC, so Firefox will complain...

```
F(
[5,5],
[[1,1,0,0,0],[1,1,0,0,0],[1,1,1,0,1],[1,1,1,1,1],[0,0,1,1,1]],
[
 [[2,4],[[1,0],[1,0],[1,1],[1,0]]],
 [[1,2],[[1],[1]]],
 [[2,3],[[0,1],[1,1],[0,1]]],
 [[2,3],[[0,1],[1,1],[1,1]]]
])

```

Another test case:

```
F(
 [6,5],
 [[0,1,1,1,1,0],[1,1,1,1,1,0],[1,1,1,1,1,0],[0,1,1,1,1,0],[0,0,1,1,1,1]],
 [
  [[2,4],[[1,0],[1,0],[1,1],[1,1]]],
  [[3,3],[[1,1,0],[0,1,1],[0,1,1]]],
  [[3,3],[[0,0,1],[1,1,1],[1,0,0]]],
  [[2,4],[[0,1],[1,1],[0,1],[0,1]]]
 ]
)

```

Output / 2+2 solutions found, firefox console skip repeated console output

```
0,2,2,2,2,0
3,3,4,2,2,0
3,3,4,4,4,0
0,3,3,5,4,0
0,0,5,5,5,5

```

---

```
0,4,4,2,2,0
3,3,4,2,2,0
3,3,4,4,2,0
0,3,3,5,2,0
0,0,5,5,5,5

```

---
Tags: code-golf, board-game
---


title: Throw a null-pointer exception

text:
# Question
Title: Throw a null-pointer exception
Your task is to generate a null-pointer exception. That is, your program must accept a value which it expects to be non-null, and throw an exception/error or crash because the value is null.

Furthermore, it can't be obvious from reading the code that the value is null. Your goal is to make it seem clear to the reader that the value is not null, even though it actually is.

* Instead of null, you can use nil, none, nothing, or whatever the equivalent is in your language. You can also use undefined, uninitialized, and so on.
* The problem with your code must be that the variable is (surprisingly) null where the program expects a non-null variable.
* Your program can respond to the null by throwing an exception, throwing an error, crashing, or whatever it normally does when an unexpected null is encountered.

This is a popularity contest, so be clever!

# Answer
# Java

Let's calculate the absolute value of a number. Java has Math.abs for this purpose, however the number we're using could be null sometimes. So we need a helper method to deal with that case:

```
public class NPE {
    public static Integer abs(final Integer x) {
        return x == null ? x : Math.abs(x);
    }

    public static void main(final String... args) {
        System.out.println(abs(null));
    }
}

```

If x is null, return null, else use Math.abs().
The code is very simple and clear, and should work fine... right?

By the way, using this line instead:

```
return x == null ? null : Math.abs(x);

```

works correctly. I thought about making this a spoiler, but.. I think it's just as puzzling :)

Ok, an explanation:

> First, Math.abs does not take an Integer, but an int (there are also overloaded methods for other numeric types) and also returns an int. In java, int is a primitive type (and can not be null) and Integer is its corresponding class (and can be null). Since java version 5, a conversion between int and Integer is performed automatically when needed. So Math.abs can take x, automatically converted to int, and return an int.
> Now the weird part: when the ternary operator (?:) has to deal with 2 expressions where one has a primitive type and the other one has its corresponding class (such as int and Integer), one would expect that java would convert the primitive to the class (aka "boxing"), especially when the type it needs (here for returning from the method) is the reference (class) type, and the first expression is also of the reference type. But java does exactly the opposite: it converts the reference type to the primitive type (aka "unboxing"). So in our case, it would try to convert x to int, but int can not be null, thus it throws a NPE.
> If you compile this code using Eclipse, you will actually get a warning: "Null pointer access: This expression of type Integer is null but requires auto-unboxing"
> Also see:
> https://stackoverflow.com/questions/7811608/java-npe-in-ternary-operator-with-autoboxing
> https://stackoverflow.com/questions/12763983/nullpointerexception-through-auto-boxing-behavior-of-java-ternary-operator
> 34 votes

# Answer
## C

Every C programmer made this error, at least once.

```
#include <stdio.h>

int main(void) {
    int n=0;
    printf("Type a number : ");
    scanf("%d",n);
    printf("Next number is : %d",n+1);
    return 0;
}

```

Reason :

> `scanf` takes a pointer (`int *`) in argument, here `0` is passed (NULL-pointer)

Fix:

> `scanf("%d",&n);`

http://ideone.com/MbQhMM
> 23 votes

# Answer
## PHP

This one has bitten me a few times.

```
<?php

class Foo {
  private $bar;

  function init() {
    $this->bar = new Bar();
  }

  function foo() {
    $this->bar->display_greeting(); // Line 11
  }
}

class Bar {
  function display_greeting() {
    echo "Hello, World!";
  }
}

$foo_instance = new Foo();
$foo_instance->init();
$foo_instance->foo();

```

Expected result:

```
Hello, World!

```

Actual result:

```
Fatal error: Call to a member function display_greeting() on a non-object on line 11

```

a.k.a. NullPointerException

Reason:

> By default, constructor syntax is backwards compatible with PHP 4.x, and as such, the function `foo` is a valid constructor for the class `Foo`, and thus overrides the default empty constructor. This sort of error can be avoided by adding a namespace to your project.
> 14 votes

# Answer
# CoffeeScript (on Node.js)

In CoffeeScript, `?` is existential operator. If the variable exists, it's used, otherwise right hand side is being used. We all know that it's hard to write portable programs. Case in point, printing in JavaScript is under specified. Browsers use `alert` (or `document.write`), SpiderMonkey shell uses `print`, and Node.js uses `console.log`. This is crazy, but the CoffeeScript helps with this issue.

```
# Portable printer of "Hello, world!" for CoffeeScript

printingFunction = alert ? print ? console.log
printingFunction "Hello, world!"

```

Let's run this under Node.js. After all, we want to make sure our script works.

```
ReferenceError: print is not defined
  at Object.<anonymous> (printer.coffee:3:1)
  at Object.<anonymous> (printer.coffee:3:1)
  at Module._compile (module.js:456:26)

```

Uhm, why would you complain about that, when `alert` is also not defined?

> For some reason, in CoffeeScript, `?` is left associative, which means it ignores undefined variables only for the left side. It's unfixed, because apparently some developers may depend on ? being left associative.
> 9 votes

# Answer
# Ruby

Find awk in the PATH of a Unix clone.

```
p = ENV['PATH'].split ':'

# Find an executable in PATH.
def find_exec(name)
  p.find {|d| File.executable? File.join(d, name)}
end

printf "%s is %s\n", 'awk', find_exec('awk')

```

Oops!

```
$ ruby21 find-awk.rb
find-awk.rb:5:in `find_exec': undefined method `find' for nil:NilClass (NoMethodError)
        from find-awk.rb:8:in `<main>'

```

From the error, we know that `p.find` called `nil.find`, so `p` must be `nil`. How did this happen?

In Ruby, `def` has its own scope for local variables, and never takes local variables from the outer scope. Thus the assignment `p = ENV['PATH'].split ':'` is not in scope.

An undefined variable usually causes `NameError`, but `p` is a special case. Ruby has a global method named `p`. So `p.find { ... }` becomes a method call, like `p().find { ... }`. When `p` has no arguments, it returns `nil`. (Code golfers use `p` as a shortcut for `nil`.) Then `nil.find { ... }` raises `NoMethodError`.

I fix it by rewriting the program in Python.

```
import os
import os.path

p = os.environ['PATH'].split(':')

def find_exec(name):
    """Find an executable in PATH."""
    for d in p:
        if os.access(os.path.join(d, name), os.X_OK,
                     effective_ids=True):
            return d
    return None

print("%s is %s" % ('awk', find_exec('awk')))

```

It works!

```
$ python3.3 find-awk.py
awk is /usr/bin

```

I probably want it to print `awk is /usr/bin/awk`, but that is a different bug.
> 8 votes

# Answer
# C#

`With()` is an extension method to the `string` object, which is essentially just an alias for `string.Format()`.

```
using System;

namespace CodeGolf
{
    internal static class Program
    {
        private static void Main()
        {
            Console.WriteLine( "Hello, {0}!".With( "World" ) );
        }

        private static string With( this string format, params object[] args )
        {
            Type str = Type.GetType( "System.string" );
            MethodInfo fmt = str.GetMethod( "Format", new[] { typeof( string ), typeof( object[] ) } );

            return fmt.Invoke( null, new object[] { format, args } ) as string;
        }
    }
}

```

Looks good, right? Wrong.

> `Type.GetType()` requires a fully-qualified, case-sensitive type name. The problem is that `System.string` doesn't exist; `string` is just an alias for the *actual* type: `System.String`. It looks like it should work, but `str.GetMethod()` will throw the exception because `str == null`.

Most people who know a bit about the internal specifics of the language will probably be able to spot the problem fairly quickly, but it's still something that's easily missed at a glance.
> 7 votes

# Answer
# Unity3D

```
public GameObject asset;

```

Then you forget to drag&drop the asset there and BOOM, Unity explodes. Happens all the time.
> 4 votes

# Answer
# Ruby

Just some simple code to take the product of an array.

```
number_array = [2,3,9,17,8,11,14]
product = 1
for i in 0..number_array.length do
  product *= number_array[i]
end
puts product

```

> Two things here. One is that the `..` range operator is *inclusive*. So `0..x` has *x+1* elements and includes x. This means that the we exceed the bounds of the array. The other thing is that when you do this in Ruby, it just gives you a `nil` back. This is a lot of fun when, say, your program throws an `except` ten lines *after* the bug.
> 4 votes

# Answer
# Android

I see this happen too often. A person passes a message to the next activity (maybe a status code, map data, whatever), and ends up pulling a null from the `Intent`.

At first glance it seems pretty reasonable. Just:

* make sure the message isn't null
* pack it into the intent
* start new activity
* get intent in new activity
* extract message by tag

In `MenuActivity.java`:

```
private void startNextActivity(String message){
    // don't pass a null!
    if(message == null)
        message = "not null";

    // put message in bundle with tag "message"
    Bundle msgBundle = new Bundle();
    msgBundle.putString("message", message);

    // pack it into a new intent
    Intent intent = new Intent(this, NextActivity.class);
    intent.putExtras(msgBundle);
    startActivity(intent);
}

```

In `NextActivity.java`:

```
private void handleMessage(){
    // get Intent
    Intent received = getIntent();
    if(received == null){
        Log.d("myAppTag","no intent? how does this even happen?");
        finish();
    }
    // get String with tag "message" we added in other activity
    String message = received.getStringExtra("message");
    if(message.length() > 10){
        Log.d("myAppTag", "my message is too long! abort!");
        finish();
    }
    // handle message here, etc
    // ...
    // too bad we never GET here!
}

```

FWIW, the JavaDoc *does* say that `Intent.getStringExtra(String)` may return `null`, but only if the tag wasn't found. *Clearly* I'm using the same tag, so it must be something else...
> 3 votes

# Answer
# C

Just a quick read from the buffer, where the programmer has even been kind enough to document the potential danger!

```
char* buffer;
int main( void )
{
    ///!!WARNING: User name MUST NOT exceed 1024 characters!!\\\
    buffer = (char*) malloc( 1024 );
    printf("Please Input Your Name:");
    scanf("%s", buffer);
}

```

> Very simple and obvious trick if you're expecting malicious code. The comment ending '\\' escapes the newline, so the buffer is never allocated memory. It will then fail the scanf, as buffer will be NULL (as file scope variables are zero initialised in C).
> 3 votes

# Answer
# Nimrod

```
type TProc = proc (a, b: int): int

proc func1(a, b: int): int=a+b
proc func2(a, b: int): int=a-b

proc make_func(arg: int, target: var TProc)=
  if arg == 1:
    target = func1
  elif arg == 2:
    target = func2
  else:
    raise newException(EIO, "abc")

var f, f2: TProc

try:
  make_func(2, f)
  make_func(3, f2)
except EIO:
  discard

echo f(1, 2)
echo f2(3, 4)

```

> What's happening here is a little complicated. In Nimrod, procedures are default initialized to `nil`. In the first `make_func` call, it succeeds. The second, however, throws an exception and leaves `f2` uninitialized. It is then called, causing an error.
> 0 votes

# Answer
# C#

This is classical. The *very* useful method `FindStringRepresentationOf` will create a new instance of the specified type parameter, then find the string representation of that instance.

Surely it will be wasteful to check for `null` immediately after having created a new instance, so I haven't done that...

```
static void Main()
{
  FindStringRepresentationOf<DateTime>();  // OK, "01/01/0001 00:00:00" or similar
  FindStringRepresentationOf<DateTime?>(); // Bang!
}

static string FindStringRepresentationOf<TNewable>() where TNewable : new()
{
  object goodInstance = new TNewable();
  return goodInstance.ToString();
}

```

> Changing `object` in the local variable declaration into `TNewable` or into `var` (C# 3 and later) makes the problem go away. **Hint:** Boxing of `Nullable<T>` (a.k.a. `T?`) is anomalous in the .NET Framework.

After having fixed the issue as described in the invisible text above, aslo try `goodInstance.GetType()` (the difference being that `GetType()`, unlike `ToString()`, is non-virtual, so they could not `override` it in the type `Nullable<>`).
> 0 votes

# Answer
C++:

```
#include <iostream>
#include <cstring>
#include <vector>
#include <conio.h>
#include <string>

using namespace std;

class A
{
public:
    string string1;
    A()
    {
        string1 = "Hello World!";
    }
};
A *a_ptr;

void init()
{
    A a1;
    a_ptr = &a1;
}

int main()
{
    init();
    cout<<a_ptr->string1;
    _getch();
    return 0;
}

```

What you would expect is "Hello World!" to be printed. But you will see only garbage on the screen.

Here the a1 is destroyed when the scope init() is finished. So a\_ptr, as it points to a1, will produce garbage.
> 0 votes

# Answer
# C

```
#define ONE 0 + 1

int main(void) {
    printf("1 / 1 = %d\n", 1 / ONE);
    return 0;
}

```

## Explanation

> The preprocessor doesn't actually calculate `0 + 1`, so `ONE` is literally defined as `0 + 1`, resulting in `1 / 0 + 1`, which is a division by zero, and results in a floating point exception.
> 0 votes

---
Tags: popularity-contest, underhanded
---


title: What a wonderful world

text:
# Question
Title: What a wonderful world
The challenge is programming a program that prints following lyrics of Louis Armstrong's *What A Wonderful World* with as few characters as possible. The key is obviously kind of a 'compression'. I encourage to use and enhance ideas of previous answers, but please declare if you do so!

**Rules**: No information can be stored externally, everything must be contained in the code itself. Only ASCII characters allwed in the code. The text must be reproduced exactly. Output to console or text file.

```
I see trees of green, red roses, too,
I see them bloom, for me and you
And I think to myself
What a wonderful world.

I see skies of blue, and clouds of white,
The bright blessed day, the dark sacred night
And I think to myself
What a wonderful world.

The colors of the rainbow, so pretty in the sky,
Are also on the faces of people going by.
I see friends shaking hands, sayin', "How do you do?"
They're really sayin', "I love you."

I hear babies cryin'. I watch them grow.
They'll learn much more than I'll ever know
And I think to myself
What a wonderful world

Yes, I think to myself
What a wonderful world

```

PS: Why I think this is different to other encoded songs: Longer text; ASCII-only; a lot of repeating text/similar text.

EDIT: FEWEST of course. Ending will be 22th of June!

# Answer
> 2 votes
# Cobra - 585

Still many improvements to be made

```
class P
    def main
        i='I see '
        f='s of '
        w=' I think to myself\nWhat a wonderful world'
        a='\nAnd[w]'
        t=' the '
        s=' sayin\', "'
        print "[i]trees of green, red roses, too,\n[i]them bloom, for me and you[a].\n\n[i]skie[f]blue, and cloud[f]white,\nThe bright blessed day,[t]dark sacred night[a].\n\nThe colors of[t]rainbow, so pretty in[t]sky,\n are also on[t]face[f]people going by.\n[i]friends shaking hands,[s]How do you do?\"\nThey're really[s]I love you.\"\n\nI hear babies cryin'. I watch them grow.\nThey'll learn much more than I'll ever know\nAnd[w]\n\nYes,[w]"

```

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