text:
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.

I'm just about done with my solution. Can we assume that there will not be a 3-digit number of boxes in a row or column?

@voidpigeon: 5<=n<=50 is the spec, so there cannot be any 3-digit numbers

After posting this question, I started working on a solution myself. I won't post it yet (as per this meta answer), but I'll post my byte count so you guys have something to strive for: 404 bytes in Python 2.7

Doesn't your first example output contain one more - than it should?

@Ventro You are correct! I knew how I would write a program to do this, but I didn't actually do it until just now, so my sample outputs were by hand. Oops! (I also screwed up the second sample output, but I fixed it before there were any answers.)

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
]\

+1 nice, I've learned quite a few good tricks from this post

I managed to golf it to 123 chars: ~](:k/.zip\]{{1,%{,}%.!,+}%}/{' ':^*}%{.{,}%$-1=}:f~:r{^*\+r~)>'|'n}+%\f{.~)\[^]*@+>{^\+-2>}%}+%zip{r)^*\n}%r^*'+''--'k*n]( (for some reason lettercount.com says 125 chars if you copy it, but I assure you, it is 123 chars). Some parts of the algorithm have been changed, but the majority is still the same. I also changed some variable names (having 9 as a variable is smart, but confusing as well), but you can change them back if you want.

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.

You do print some extra newlines and spaces, but so far in all of my tests they've fit the "0 or more" specification, so you're good. I'm warning you now, though, if I start seeing numbers floating in the air to the left my monitor, I'm going to have to disqualify this answer :)

@undergroundmonorail: The output is printed in such a way that length(leading spaces + numbers to the left) == 2*n and height(leading newlines + numbers at the top) == n ... so as long as your monitor is big enough for 3*n+1 × 2*n+2 characters, you shouldn't have to disqualify me. :)

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]}*""+?|}

How do you run this? I tried ruby $yourprogram <<< $input but got ruby_nanograms:7:in '<main>': undefined method '+' for nil:NilClass (NoMethodError).

@undergroundmonorail ruby nonogram.rb 2 1 0 0 1 for a 2x2

This is a good answer, but you don't print the 0 for the fourth-last column in the second example.

I just noticed that the +------... line is indented by one too many spaces, too.

@undergroundmonorail Fixed both.

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

Small board
Big board

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}/

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 :(

Nice. I tried a Javascript version too but ended with something around 500 bytes and decided I was too big to put it here. Would be good to post ungolfed version with original variables names (if you still have it). Also, how do you run this ? If I copy paste it into chrome console window I get "ReferenceError: Invalid left-hand side in assignment". Is there something to change or to add before running ?

@tigrou sorry the "=>" sintax works only in firefox. Variables: c colunns hints, d dimension, l list of input, o output, i loop variable, q and z temp

-15 bytes :)

@nderscore fiddling around with the code, I got 326. In your code R is not initialized (easy mistake when you try again and again...)

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|

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");
    }
}

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. ¯\_(ツ)_/¯

Umm, I can't find your solution. (sorry, just a terrible joke regarding the character count, don't mind me :) )

@dor Aha! Try making your HTTP error code jokes now! :P


text:
Are the rooms connected?
You are locked in a massive fortress, slowly starving to death. Your guards inform you that there is food in the fortress, and even tell you where it is and provide a map of the building.
However, you are not sure that you can actually reach the food, given that the every door is locked, and every room is its own labyrinth. Are you able to reach the food? If you're in the same room, you should try. If you're not in the same room, then you might as well stay put, preserving your strength in case help from the outside world comes.
Input
Two arrays: 3 coordinates of where you are, and 3 coordinates of where the food is. (Both are 0-based)
:Optional: an array of three numbers, indicating the size of the following fortress in each dimension.
A three dimensional array of the fortress, where each point in the array is either 1/true (if that point is a wall) or 0/false (if the point is empty). The array is a rectangular prism, and there is no guarantee that the structure follows the laws of physics. (Thus, the bottom floor might be completely empty.)
The place where you are and the place where the food is both have a 0/false.
Output
Are the two points in the same room, unseparated by a wall? Note that you can not move through a diagonal.
Format
You may write a program or a function.
The input may be through STDIN, command line or function arguments, or reading from a file. If you choose a text-based input (like STDIN) you may use any delimiters to help your program parse the input.
The output may be through STDOUT or the function result. You can output/return "true"/"false", 0/1, or the like.
Examples
In these examples, I put a Y where you are, and a F where the food is. This is just to help you understand the examples; in the actual input they would be 0/false.
Input
[0 0 1]      // You are at x = 0, y = 0, z = 1
[1 2 2]      // The food is at x = 1, y = 2, z = 2
[[[0 0 0]    // z = 0, y = 0
  [0 0 0]    // z = 0, y = 1
  [1 1 1]]   // z = 0, y = 2
 [[Y 0 0]
  [0 0 0]    // z = 1
  [1 1 1]]
 [[0 0 0]
  [1 1 0]    // z = 2
  [0 F 0]]]

Output
True. (The places are connected. You can move from [0 0 1] > [2 0 1] > [2 0 2] > [2 2 2] > [1 2 2].)
Input
[3 0 1]
[1 1 0]
[4 2 2]         // If you want, you can include this in the input, to indicate the fortress's size
[[[0 1 0 0]     // z = 0, y = 0
  [0 F 1 0]]    // z = 0, y = 1
 [[0 0 1 Y]
  [0 1 0 0]]]

Output
False. (There are two rooms. Your room includes [2 0 0], [2 1 1], [3 0 0], [3 0 1], [3 0 1], and [3 1 1]. The food's room includes the other empty spaces. Note that a wall of 1's divides the fortress in half.
Winning criterion
Code golf. Shortest code for your function/program wins.

What is the maximum size of the array? And how does the program know the size of the array? Is that input too? or is it given by carriage returns or EOF markers in the input?

@steveverrill I edited to allow an optional line for the size. Note that this isn't necessary in many languages (like Java).

Can you move up or down whenever the target direction is empty?

"...you may use any delimiters to help your program parse the input." I'm not 100% sure how much freedom I have here. Is [0,0,1],[1,2,2],[[[0,0,0],[0,0,0],[1,1,1]],[[0,0,0],[0,0,0],[1,1,1]],[[0,0,0],[1,1,0],[0,0,0]]] a valid way to format your first example?

@undergroundmonorail Yes, that would be okay.

Do I have to use 0-based indices if my language doesn't?

Similarly, am I free to take the positions in the same order as the indexing works? With your format, I get the last index first and the first index last.

Is [0,0,1],[1,2,2],[3,3,3],[0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0] a valid input?

Aaaand another questions: do I have to output the same truth/false value? Or could I output 0 for true and any positive integer for false (which might change between different problems).

and ... some more test case?

This challenge could use a graphical image in the description to make it clearer.

GolfScript, 93 characters
~[[]]@{,`{{1$+}%\;~}+%}/:A[\{{~}/}%]zip{~!*}%:S;]1/~{{3,{)1$/.())+\+\()(+\+}%{[]*}/}%S&}A,*&,

The code expects the input as specified above (including the fortress' dimensions) on STDIN. The result is 1 if food is reachable and 0 otherwise.
Try the code online.

Python 2.x - 177 168 167 bytes
Basic flood fill to kick the game going. Requires the dungeon size.
f,(a,b,c),(w,h,d),p=input()
def l(x,y,z):
 if w>x>-1<y<h>0<=z<d and p[z][y][x]<1:p[z][y][x]=2;[(l(x+i,y,z),l(x,y+i,z),l(x,y,z+i))for i in-1,1]
l(*f)
print p[c][b][a]>1

Examples:
Input:  [0,0,1],[1,2,2],[3,3,3],[[[0,0,0],[0,0,0],[1,1,1]],[[0,0,0],[0,0,0],[1,1,1]],[[0,0,0],[1,1,0],[0,0,0]]]
Output: True

Input:  [3,0,1],[1,1,0],[4,2,2],[[[0,1,0,0],[0,0,1,0]],[[0,0,1,0],[0,1,0,0]]]
Output: False

Ungolfed code:
(e,f,g),(a,b,c),(w,h,d),field=input()

def fill(x,y,z):
    if 0<=x<w and 0<=y<h and 0<=z<d and field[z][y][x]<1:
        field[z][y][x]=2
        fill(x+1,y,z)
        fill(x-1,y,z)
        fill(x,y-1,z)
        fill(x,y+1,z)
        fill(x,y,z-1)
        fill(x,y,z+1)

fill(e,f,g)
print field[c][b][a]==2

Mathematica, 173 bytes
f=(v=#;(v=ReplacePart[v,Reverse[#+1]->#2])&@@@{{#3,2},{#4,3}};VertexConnectivity[VertexDelete[GridGraph[#2],Join@@(l=Flatten@v)~(s=Position)~1],(h=s[l,#][[1,1]]&)@2,h@3]>0)&

This defines a function f which can be called like
f[{{{0,1,0,0},...}, {4,2,2}, {3,0,1}, {1,1,0}]

using your second example.
Ungolfed:
f = (
   v = #;
   (v = ReplacePart[v, Reverse[# + 1] -> #2]) & @@@ {{#3, 2}, {#4, 3}};
   VertexConnectivity[
    VertexDelete[
     GridGraph[#2],
     Join @@ (l = Flatten@v )~(s = Position)~1
     ],
    (h = s[l, #][[1, 1]] &)@2,
    h@3] > 0
   ) &

I'm simply creating a grid graph for the entire building, then delete all walls (and their adjacent edges) from the graph and then check that the two vertices are connected.

+1 Nice idea. Also, coming this close to Mathematica is awesome.

@TheRare Thanks! :) Once the OP answers our questions, I might be able to shave off up to 15 bytes, I think. ;)

And for now, I have beaten you. Mwah.

Javascript (E6) 123 128 132 140 167 286 344
First try. Simple fill, not recursive, fortress size not needed. Must simplify multidimensional array handling (90 chars!!).
Edit Recursive fill, no need to know the fortress dimensions, should work even for irregular shapes.
Edit Tips by TheRare to shorten the recursive call & golf more
Edit Contribution by MT0, cut same () and use exact equal
Edit Contribution by nderscore, multidimensional array handling (learned sth new again)
Edit With a clever trick, nderscore bring the food check back inside the loop, where it belongs. Now returning a boolean, 'some' is more fit than 'map' (and shorter)
A=(Y,F,M)=>(S=(x,y,z)=>(t=(M[z]||0)[y]||0)[x]-1&&[x,y,z]+''==F|[-1,t[x]=1].some(d=>S(x+d,y,z)|S(x,y+d,z)|S(x,y,z+d)))(...Y)

Usage
A([0,0,1],[1,2,2],
  [[[0,0,0],[0,0,0],[1,1,1]],
  [[0,0,0],[0,0,0],[1,1,1]],
  [[0,0,0],[1,1,0],[0,0,0]]])

Return 1
A([3,0,1],[1,1,0],
  [[[0,1,0,0],[0,0,1,0]],[[0,0,1,0],[0,1,0,0]]])

Return 0
Ungolfed
A=(Y,F,M)=>
  (S=(x,y,z)=>
     (t=(M[z]||0)[y]||0)[x]-1 // NaN==out,-1==open,0==wall or visited
     && [x,y,z]+''==F // compare with food position converting to string
     | [-1,t[x]=1] // mark as visited, then recurse popping out the return value if true
       .some(d=>S(x+d,y,z)|S(x,y+d,z)|S(x,y,z+d))
  )(...Y)

I would recommend the same trick I used in my Python answer, as this looks a lot like it (hint hint). That is, for(i as [-1,1]){S(x+i,y,z),S(x,y+i,z),S(x,y,z+i)} I'm not sure if this is legit ES6, but I'm sure you got the idea.

@TheRare 'a fill is a fill is a fill'... I borrowed the check for food found from your solution, mine was faster but yours was shorter. Next edit, i'll give a try to your hint.

I wasn't saying you copied or stole anything. Just gave the tip because it seemed like you had shown some interest to my answer.

@TheRare Good tip, thx

That was a neat way to implement it.

You could also set M[z][y] to a variable and substitute it to M[z][y], M[z][y][x]>1 and M[z][y][x]=2

F=(Y,F,M)=>(S=(x,y,z)=>M[z]&&(X=M[z][y])&&X[x]===0&&(X[x]=2,[-1,1].map(d=>S(x+d,y,z)&S(x,y+d,z)&S(x,y,z+d))))(...Y)&&M[F[0]][F[1]][F[2]]

Forgot the >1 on the end...

No...indeed it's a good idea, using === I can mark with -1 instead of 2, and it is an acceptable synonym of true.

I need to stop messing up this paste. 130 byte solution: http://pastie.org/9262556 Returns 1 for true, 0 for false.

128: A=(s,f,m)=>(F=(x,y,z)=>(M=(m[z]||0)[y]||0)[x]-1&&[-1,M[x]=1].map(a=>F(x+a,y,z)|F(x,y+a,z)|F(x,y,z+a)))(...s)|m[f[2]][f[1]][f[0]]

Sometimes I envy javascript golfers. In Python, negative indexes are legit and too big indexes throw an index error. Thus, checking the coordinates takes a lot.

@TheRare feel free to come to the dark side :)

@nderscore Python is my baby. Javascript (CoffeeScript) is my friend.

127: A=(s,f,m)=>(F=(x,y,z)=>(M=(m[z]||0)[y]||0)[x]-1&&[x,y,z]+[]==f|[-1,M[x]=1].map(a=>s|=F(x+a,y,z)|F(x,y+a,z)|F(x,y,z+a))|s)(...s)

asymptotically approaching 125 :)

Wow, it keeps getting smaller :)

Typo: ! should be |

@nderscore fixed thanks. 30 chars less and we compete against GolfScripters

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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.

Can I use nilable booleans instead of numbers?

yes, edited the question too: any kind of elements

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

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.

You did not use goto, therefore there is no bug. (Referring to all the people who said the bug would never have happened if Apple didn't use goto)

Congratulations, you have won this challenge by having the most votes (8 votes after 7 days). In addition, I really like your answer because you used a real life bug.

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.

Congratulations, you have placed second with 6 votes after 7 days. Thank you for your submission.

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.

Thank you for your submission. You have placed 3rd. Congratulation!

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.

Thank you for your submission. You have placed 3rd. Congratulation!

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

Which language do u use?

Java, sorry forgot to mention that (edited).

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.

Well Perl looks like a bug anyway for me...

authors: กำลัง'งง พิม'มมม

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Create an object whose state changes on assignment
I find it deeply weird that this is possible in Ruby (I won't immediately say how):
obj = #code redacted

print obj.state # Some value.

LValue = obj

print obj.state # Different value!

Your challenge is to create code roughly of this form. Create an object and assign it to a variable. It should have some defined attribute (or deterministic, idempotent method) like state above, that changes after the object is assigned to a new identifier (LValue above), even if you still use the old identifier (obj above) to refer to it.
Edit for emphasis: state or the equivalent must be idempotent, so creating an accessor that modifies the value, or for any other reason returns different results when called several times in a row, isn't a valid solution. Or, more simply, it has to be the assignment that changes the state.
Any language with assignment is eligible, although there are probably some where there's no fully legitimate solution. I'll post my Ruby answer if nobody else gets it after a few days, and accept highest-voted answers on a rolling basis.

Must the LValue = obj line be required for state to actually change? (I could just make a property in C# that increments every time you get it)

Yes, that's what I intended by saying the method needed to be idempotent. I'll edit to make that clearer.

Ok, thanks. I must've glossed over that part.

Would simply returning the refcount of the object work?

Would destructive alterations to the object itself? EmacsLisp: (setq a (list "val")) (setq b (nconc a "val2")) for example.  a ends up evaluating as ("val" . "val2") at that point.

It's a popularity contest, but to me returning the refcount is in the spirit of the challenge, but putting a destructive operation on the right hand side is not -- in your example, it's the nconc that's performing the mutation, not the setq (if I understand correctly).

C++
This is trivial using the right tools.

#include <iostream>

using namespace std;

class Obj {
public:
   int state;

   Obj& operator= (Obj& foo) {
      foo.state++;
      this->state = foo.state - 2;
      return *this;
   }
};

int main() {
   Obj a, b, c, d;
   a.state = 3;
   b.state = 4;

   cout << a.state << " " << b.state << "\n";

   c = a;
   d = b;

   cout << a.state << " " << b.state << " " << c.state << " " << d.state << "\n";

   return 0;
}

Output:
3 4
4 5 2 3

The moment I saw the title, I knew someone would do operator overloading. It's the obvious way. Have an upvote.

PHP (debug build, >= 5.4)
We use refcount of the object in a getter. (So, by the assignment, refcount increases and value changes)
class State {
    public function __get($arg) {
        ob_start();
        debug_zval_dump($this); // e.g. "object(State)#1 (0) refcount(6)"
        return ob_get_clean()[29];
    }
}

$obj = new State;
var_dump($obj->state);
$a = $obj;
var_dump($obj->state);

C#
Two simple options:
class Obj
{
    public int state;
    public static implicit operator int(Obj o)
    {
        return o.state++;
    }
}

static int LValueI;
static Obj LValueM { set { value.state++; } }
static void Main()
{
    var obj = new Obj { state = 1 };
    LValueI = obj;
    Console.WriteLine(obj.state); //2, caused by the implicit cast.

    LValueM = obj;
    Console.WriteLine(obj.state); //3, caused by the property setter.
    Console.ReadLine();
}

Or we could simply write to the same memory:
[StructLayoutAttribute(LayoutKind.Explicit)]
class Program
{
    [FieldOffset(0)]
    int state = 1;
    [FieldOffset(1)]
    int LValue;

    void Test()
    {
        var obj = this;

        Console.WriteLine(state);  //1
        LValue = state;
        Console.WriteLine(state);  //257
        Console.ReadLine();
    }
    static void Main() { new Program().Test(); }
}

TeX, much shorter than other answers here
\setbox0=\hbox{Hello world!} % Put stuff in the box 0.
\message{\the\wd0}           % Print the width of the box => non-zero
\setbox2=\box0               % Put the box instead in box 2.
\message{\the\wd0}           % Now box 0 is void, hence has zero width.

As a typesetting system, TeX has a "box" type, which contains typeset material.  Since the most common use case is to move this material around, split it, etc, rather than making copies of it, boxes are normally deleted when used (or rather, "box" variables are pointers and only one pointer at a time can point to an actual box in memory).  No need for any magic.

C++11 (So you guys have forgotten about unique_ptr/shared_ptr :-) )
#include <iostream>
#include <memory>
using namespace std;
int main() {
    std::unique_ptr<int> u1(new int(0)), u2;
    std::shared_ptr<int> s1 = std::make_shared<int>(0), s2;
    std::cout<<u1.get()<<" "<<u2.get()<<" "<<std::endl;
    std::cout<<s1.use_count()<<" "<<s2.use_count()<<" "<<std::endl;
    u2 = std::move(u1);
    s2 = s1;
    std::cout<<u1.get()<<" "<<u2.get()<<" "<<std::endl;
    std::cout<<s1.use_count()<<" "<<s2.use_count()<<" "<<std::endl;
   return 0;
}

Fortran 03
This is somewhat similar to Hugo's D answer, but is a little more hidden (partly because who the #$%^ knows Object Oriented Fortran)?
module objects
   implicit none

   type ObjDef
      integer :: state
    contains
      procedure :: initObject
      procedure :: printObject
      procedure :: setNew
   end type
 contains
   subroutine initObject(this)
     class(ObjDef) :: this
     this%state = this%state + 1
   end subroutine initObject

   subroutine printObject(this)
     class(ObjDef) :: this
     print '(a,i0)',"this%state = ",this%state
   end subroutine printObject

   subroutine setNew(this,that)
     class(ObjDef) :: this,that
     that%state = this%state
   end subroutine setNew

end module objects

program objectChange
   use objects
   type(ObjDef) :: a,b

   call initObject(a)
   call printObject(a)
   call b%setNew(a)
   call printObject(a)
end program objectChange

The output is
this%state = 1
this%state = 0

If you can figure out what happened, bonus points to you! If not:

 When calling the procedure setNew in the form call b%setNew(a), b is implicitly the first argument, not the second.

PowerShell
This creates an object whose state property is the names of the variables that point to the object.
$a = @{}| Add-Member -MemberType:16 -PassThru state -Value {
        (gv|?{$this -eq $_.Value}|%{$_.Name}) -join ','}

'Before: ' + $a.state
$b = $a
'After: ' + $a.state

Output
Before: a,this
After: a,b,this

Note: This doesn't work if the assignment happens in a child scope.
'Before: ' + $a.state
&{$b = $a}
'After: ' + $a.state

Outputs
Before: a,this
After: a,this

Get-Variable is smart!

Perl 5
Here's one way to do it in Perl:
package Magic {
    sub new { bless {state => 1} }
    use overload '""' => sub { $_[0]{state}++ };
}
use feature 'say';

my $obj = new Magic;
say $obj->{state};
substr($_, 0) = $obj;
say $obj->{state};

This outputs:
1
2

Explanation:
This is a straightforward application of overloading.  Specifically, I overload the string conversion operator "", which gets called when the overloaded object is assigned to substr() (which, yes, is a legal lvalue in Perl).
There are also plenty of special variables in Perl which stringify anything assigned to them.  For example, the following also works:
my $obj = new Magic;
say $obj->{state};
$0 = $obj;
say $obj->{state};

Alternative solution
Here's another way to it:
package Magic {
    use Devel::Peek 'SvREFCNT';
    sub new { bless \my $foo }
    sub state { SvREFCNT ${$_[0]} }
}
use feature 'say';

my $obj = new Magic;
say $obj->state;
my $other = $obj;
say $obj->state;

Here, state is a method (we could make it an attribute with further tie / overload shenanigans, but that would complicate things) that literally counts the number of references to the object.  Thus, unlike in the first solution, you actually have to assign $obj to a normal variable that can hold an object reference to make the state change.

 JavaScript
Ok, so i made a shorter version that works as SSCCE, but does no longer try to parse JavaScript properly, so the reference counting might not work when put inside a more complex script.
(function run () {
    var lineOne = getLine (1), a, b, x, y, z;
    var x = {
        get state () {
            var x=/([a-z]+)\s*=\s*([a-z]+)/,c;
            return 1 + Object.keys (c = run.toString ().split ('\n').slice (0,getLine (2)).filter (function (a) {return (x.test (a))}).reduce (function (a,b,c,d) {var r=b.match (x),t=r[2];while (a[t]){t=a[t]};a[r[1]]=t;return a}, {v:0})).reduce (function (a,b) {return (c[b]=="x"?1:0) + a},0)
        }
    };
    console.log (x.state);  //1
    console.log (x.state);  //1
    y = x;
    console.log (x.state);  //2
    z = y;
    console.log (x.state);  //3
    a = z;
    b = a;
    console.log (x.state);  //5
    a = null;
    console.log (x.state);  //4
    b = null;
    console.log (x.state);  //3
})() //1 1 2 3 5 4 3

function getLine(n) {
   try {
      to
   } catch (dat) {
      var stack = dat.stack.split('\n');
       for (var i = 0; i < stack.length; i++) {
           if (~stack[i].indexOf ('getLine')) break;
       }
      return dat.stack.split ('\n')[i + ~~n].match (/:(\d+)/)[1] - ~~window.hasOwnProperty ('__commandLineAPI')
   }
}

Care to explain what your doing?

... what in the world is this? O_o

@Doorknob A getter that returns the result, of calling a function, which counts how often an identifiername is being referenced as rval, in an assignment expression, within a given sourcetext up to a given line, passing its enclosing functions source and the line the getter got called from as arguments. Everything else is a messy provisorical tokenizer. --- I don't know how else i should call it.  In other words. In other words: The getter counts the number of assignments of references to x up to the line it got called from, the rest is a not finished tokenizer.

But hey :D It matches the requirements

Could you write an explanation in your answer, I feel too stupid trying to comprehend your answer :(

@Braiam Nah, that's my fault. I'm rather.. not good at explaining stuff :/ Sure, I'll try to add a more comprehensible explanation to the Answer, later. I gotta go now

Maybe i should golf it a bit

This is longest code I have seen on this site !

The longest …and the widest !

@NicolasBarbulesco I made it shorter

Python
It's cheating a little, but how about:
import gc
class A(object):
    @property
    def state(self):
        return len(gc.get_referrers(self))

a = A()
print a.state
b = {"x": a}
print a.state
a.y = a
print a.state
del a
print b["x"].state

C++11
though this can be extended for other languages that supports implicit / explicit destrucors
#include <iostream>
using namespace std;

class Foo {
    int *ptr;
public:
    Foo() {
        ptr = new int(0);
    }
    int state() {
        return *ptr;
    }
    ~Foo() {
        (*ptr)++;
    }
};
int main() {
    Foo a, b;
    cout << a.state() << " " << b.state() << "\n";
    {
        Foo c, d;
        c = a;
        d = b;
    }
   cout << a.state() << " " << b.state()  << "\n";

   return 0;
}

 The default assignment operator performs a shallow copy. So the receiving object still owns the pointer and any change implicitly affects the original object;

Yeah, a new without a single delete in the program. Although, for this task it's good enough I think :)

What are the outputs ?

From what I understand (C++ is far away…), here the assignment does not change the state. Otherwise, move the cout line up before the } and tell whether that works. :-)

Scala
Implicit conversions let you accomplish this while assigning to a normal local variable:
import scala.language.implicitConversions

class Obj {
  var counter = 0
}

implicit def o2s(x: Obj): String = {
  x.counter += 1
  x.toString
}

val obj = new Obj
println(obj.counter)
val s: String = obj
println(obj.counter)

You can accomplish that with inferred types, too:
var s = ""
s = obj

You can also use a custom setter method, though that requires the L-value to be a field:
object L {
  var _value = new Obj
  def value = _value
  def value_=(x: Obj): Unit = {
    _value = x
    x.counter += 1
  }
}

val obj = new Obj
println(obj.counter)
L.value = obj
println(obj.counter)

D
struct Obj {
    int state;

    void opAssign (ref Obj other) {
        ++other.state;
    }
}

void main () {
    import std.stdio;

    Obj obj, lvalue;
    writeln(obj);
    lvalue = obj;
    writeln(obj);
}

Output:
Obj(0)
Obj(1)

C++
This behavior is actually specified in the standard (and that's why it was deprecated).
#include<iostream>
#include<memory>
int main()
{
    std::auto_ptr<int> a(new int(0));
    std::cout<<a.get()<<'\n';
    std::auto_ptr<int> b = a;
    std::cout<<a.get()<<'\n';
}

Output
some address
0

The process that causes this is the same as Abhijit's answer but without requiring a std::move and the same as marinus' answer but using a standard class instead of defining it myself.
Edit: I'm adding some explanation. In the output, "some address" will actually be a hex value for the address of the allocated integer.  std::auto_ptr releases its stores pointer when assigned to another auto_ptr and sets its internal pointer to 0. Calling get() retrieves access to the stores pointer.

I suspect that the "output" here is not the real output.

Can you explain what this is supposed to do ? Especially the method get() ? Why would it return 0 at the end ?

@Nicholas yep. This output is not the true output, but a more general output (I also didn't have access to a compiler so I didn't have an example of a valid address at the time).

Hm, this fails to compile on gcc 4.8.

I fixed the compilation errors. There are still warnings if you are compiling for c++11 because auto_ptr is deprecated.

In Java
I thought this was impossible in Java. But…
Main class :
public class MyAppOfCats {

  public static void main(String[] args) {
    Cat tom = new Cat();
    System.out.println(tom.state());
    // Output : NOT-BEST-CAT
    Cat.bestCat = tom;
    System.out.println(tom.state());
    // Output : BEST-CAT
  }

}

Class Cat :
public class Cat {

  static Cat bestCat;

  public Cat() {
    super();
  }

  public String state() {
      return ((this == Cat.bestCat) ? "BEST-CAT" : "NOT-BEST-CAT");
  }

}

I have been inspired by @tbodt.

I know it's not code-golf, but you realize you can just remove the constructor and it's still the same, right?

This isn't "an object whose state changes on assignment". This is you manipulating a global value and then printing something based on it. It's no different from Cat.x = 2 and then printing Cat.x.

@Chris — The object state is based on a “global value”. So the object state changes on assignment. The question states ;-) that the state may be a deterministic, idempotent method. My method state() is such a method.

No, the object state changes on this particular assignment. If I did Cat otherCat = tom the state wouldn't have changed at all. I have a hard time believing this meets the letter or spirit of the rules.

@Chris — Of course the object changes on this assignment ! The question asks for an object whose state be changed by the assignment. Not for an object whose state be changed by any assignment.

Ruby
As promised, here's the answer that inspired the question.
obj = Class.new { def self.state; to_s[/</] ? "Has not been assigned\n" : "Assigned to #{to_s}"; end }

print obj.state

LValue = obj

print obj.state

Class.new creates an anonymous class. Calling to_s on an anonymous class gives the default string representation of objects, which looks like #<Class:0x007fe3b38ed958>. However, once the class has been assigned to a constant, to_s becomes that constant. In Ruby, a constant is a variable that begins with an uppercase letter, so obj is a reference to the class that allows it to stay anonymous.
My code wraps to_s in a state method, so the output becomes
Has not been assigned
Assigned to LValue

Unlike most of the solutions here, this only works once: assigning obj to another constant won't change its string representation, and neither will assigning a new value to LValue.

Python
import sys
class K:state = property(sys.getrefcount)

Python 2.x
I couldn't find a proper way to do this without defining an extra class.
class State(object):
    def __init__(self):
        self.state = 0
    def __set__(self, obj, other):
        # Keep different references
        other.state += 1
        self.state += 2

class Program(object):
    obj, value = State(), State() # Create two State-objects
    def __init__(self):
        print "Before assignment:", self.obj.state, self.value.state # 0 0
        self.value = self.obj # Set value to obj (supposedly)
        print "After  assignment:", self.obj.state, self.value.state # 1 2
        self.value = self.obj
        print "2nd    assignment:", self.obj.state, self.value.state # 2 4

Program()

Java
All the other solutions use their language's form of operator overloading. Java doesn't have operator overloading, so I thought I was stuck. But I came up with something.
Here's the main class:
public class Program {
    public static void main(String[] args) {
        Thing thing = new Thing(0);
        System.out.println(thing.getState());
        Thing.otherThing = thing;
        Thread.sleep(1);
        System.out.println(thing.getState());
    }
}

There are a few suspicious lines, but they wouldn't do anything if the Thing class was completely normal. It isn't:
public class Thing {
    private int state;

    public Thing(int state) {
        this.state = state;
    }

    public int getState() {
        return state;
    }

    // Please do your best to ignore the rest of this class.
    public static volatile Thing otherThing;
    static {
        Thread t = new Thread() {
            public void run() {
                Thing t = otherThing;
                while (true)
                    if (t != otherThing) {
                        t = otherThing;
                        t.state++;
                    }
            }
        };
        t.setDaemon(true);
        t.start();
    }
}

It's not guaranteed to work because of the threads, but I tested it on JDK 1.8u5, and it works there.

http://meta.codegolf.stackexchange.com/a/1657/11376

@KyleKanos Got rid of all unicode chars >U+00FF

Common Lisp
I define state as the number of special variables bound to a vector. So, assignment to a special variable changes the state.
(defgeneric state (object)
  (:documentation "Get the state of this object."))

(defmethod state ((object vector))
  ;; The state of a vector is the number of symbols bound to it.
  (let ((count 0))
    ;; Iterate each SYM, return COUNT.
    (do-all-symbols (sym count)
      ;; When SYM is bound to this vector, increment COUNT.
      (when (and (boundp sym) (eq (symbol-value sym) object))
    (incf count)))))

(defparameter *a* #(this is a vector))
(defparameter *b* nil)
(defparameter *c* nil)

(print (state *a*))
(setf *b* *a*)
(print (state *a*))
(print (state *a*))
(setf *c* *a*)
(print (state *a*))

Output:
1
2
2
3

It only works with assignments to special variables, not to lexical variables, nor to slots within an object.
Beware that do-all-symbols looks in all packages, so it misses variables that have no package. It might double-count symbols that exist in more than one package (when one package imported the symbol from another package).
Ruby
Ruby is almost the same, but I define state as the number of constants referring to an array.
class Array
  # Get the state of this object.
  def state
    # The state of an array is the number of constants in modules
    # where the constants refer to this array.
    ObjectSpace.each_object(Module).inject(0) {|count, mod|
      count + mod.constants(false).count {|sym|
        begin
          mod.const_get(sym, false).equal?(self)
        rescue NameError
          false
        end
      }
    }
  end
end

A = %i[this is an array]
puts A.state
B = A
puts A.state
puts A.state
C = A
puts A.state

Output:
state-assign.rb:9:in `const_get': Use RbConfig instead of obsolete and deprecated Config.
1
2
2
3

This is a generalization of histocrat's answer to Ruby objects that are not classes or modules. The warning appears because the Config constant autoloads some code that made the warning.

C++
The result may differ in different platforms. Tested on ideone.
#include <iostream>
#include <cassert>
// File format: [ciiiiciiii...] a char (1 byte) followed by its state (4 bytes)
// Each group takes 5 bytes
char Buffer[30]; // 5*6, six groups

struct Group {
    char c;
    int state;
};

int main(void) {
    assert(sizeof(char) == 1);
    assert(sizeof(int) == 4);

    Group& first_group = *(Group*)(&Buffer[0]); // Group 1 is at 0
    Group& second_group = *(Group*)(&Buffer[5]); // Group 2 is at 5

    first_group.c = '2';
    first_group.state = 1234;

    std::cout << first_group.state << std::endl;

    second_group = first_group;

    std::cout << first_group.state << std::endl;

    return 0;
}

Output:
1234
13010

C#
class A
{
    public int N { get; set; }
    public override string ToString() { return N.ToString(); }
}
class B
{
    public int N { get; set; }
    public override string ToString() { return N.ToString(); }
    public static implicit operator A(B b) { b.N = -b.N; return new A { N = b.N }; }
}
public static void Test()
{
    A a = new A { N = 1 };
    B b = new B { N = 2 };
    Console.WriteLine("a is {0}, b is {1}", a, b);
    Console.WriteLine("a is {0}, b is {1}", a, b);
    a = b;
    Console.WriteLine("a is {0}, b is {1}", a, b);
    Console.WriteLine("a is {0}, b is {1}", a, b);
}

Output:
a is 1, b is 2
a is 1, b is 2
a is -2, b is -2
a is -2, b is -2

What does this do ? Is this overloading the operator = ?

@Nicolas Not exactly. It's when casting from a B to an A, because the implicit operator A(B b) has side-effects.


text:
Hello world with a twist
Your goal: to write a piece of code that will result in the classic result of "Hello, world!" being printed to STDOUT or equivalent.
Rules: Code must be entirely in printing ASCII. All code must be functional - removal of any single counting character must change the result or cause the code to not function. All variables must be used after assignment. Character and String literals must be necessary to the output - that is, replacement of any character literal or any character within a string literal with another character must be capable of changing the result (and not via the effect of escape sequence - replacing character with backslash or equivalent)
(NOTE: Final rule was edited in)
Scoring: This is where it gets interesting. Highest score wins as determined by number of characters, as per typical code-bowling rules. But repeated use of characters will result in point deductions. Specifically...

Repeated use of any alphanumeric character (a-z, A-Z, 0-9) will result in a deduction of 3 points per repeat (first use does not result in a deduction).
Repeated use of basic punctuation ([!?.-,":';]) - including the brackets - will result in a deduction of 2 points per repeat.
Repeated use of other ASCII characters {`~@#$%^&*_+=|\/><} - including the curly brackets - will result in a deduction of 4 points per repeat.
Repeated use of spaces, tabs, and newlines will result in a deduction of 1 point per repeat. That is, only the first use of a space, tab, or newline will count towards your total.

Note: comments do not count towards total, although the characters marking the start/end of a comment do. For instance, in C/C++, If you have /* This is a comment */, then it will count two slashes and two asterisks, but nothing between them.
Some examples (note: using Julia as sample language)...
print("Hello, world!");

Total visible characters: 22
Contains Space: +1
Repeated alphanumerics: -12 for llor
Repeated punctuation: -2 for "
Final score: 22+1-12-2 = 9
print("Hel",char(108),"o, wor",0x108,"d!"); # 0x108 makes a Uint8 that prints as ASCII

Total characters: 43 (does not count any characters after #, which is the comment character)
Contains Space: +1
Repeated alphanumerics: -18 for rr1008
Repeated punctuation: -24 for ()""""",,,,,
Final score: 43+1-24-18 = 2
xy=STDOUT
m="Hello, world!"
print(xy,m);

Total visible characters: 37
Contains Newline: +1
Contains Space: +1
Repeated alphanumerics: -18 for xyllor
Repeated punctuation: -4 for ",
Repeated other ASCII: -4 for =
Final score: 37+1+1-18-4-4 = 13
A couple of invalid pieces of code...
x=2;print("Hello,world!")

Problem: x is assigned, but not used.
print("Hello,"*" world!")

Problem: * is unnecessary, result will be the same without it.
k=1
if k>0
  print("Hello, world!")
else
  print("abcghjmquvxyzABCDEFGIJKLMNOPQRSTUVWXYZ_+*-&|")
end

Problem: The second print command will not run. Also, removing characters in quote in second print command will not change output.
x="Hello, world!";
print(x)

Problem: removal of newline will not change result or cause error (in Julia, semicolon is only necessary if multiple commands are on the same line, otherwise just suppresses return value).
print("Hellos\b, world!")

Problem: s character does not affect result, as it gets erased by \b. This is acceptable if done through code ("Hello",char(100),"\b, world!"), but cannot be done via string literals or character literals.
Convenient score-calculator - http://jsfiddle.net/4t7qG/2/ - thanks to Doorknob

I think you may just have fixed code bowling. I'm really curious how this plays out (i.e. if you'll get answers that still find loopholes to exploit), but at least this sounds like the best code bowling specification I've seen so far.

Seems awfully close to http://codegolf.stackexchange.com/questions/19477/golf-with-a-bowling-ball-hello-world-with-high-complexity-yet-short-code?rq=1 and http://codegolf.stackexchange.com/questions/18721/hello-world-with-limited-character-repetition?rq=1

Isn't it mostly print hello world with most distinct characters?

@KyleKanos While I agree, I think we should give this a try in the interest of attempting to save code bowling.

@KyleKanos - this is more than just a character restriction or complexity challenge. It's a game where, to maximise your score, sometimes you'll take a hit along the way. Two steps forward, one step back. And the score is both objective (as opposed to that popularity-contest) and direct (as opposed to the complexity one). You're not trying to impress people with your clever code, you're not trying to obfuscate or overcomplicate it. That's what makes this different.

@GlenO: This seems to be a combination of the two puzzles I linked to but with a new win tag, so it's not really any different than the first link is to the second.

@KyleKanos - well obviously - they all involve Hello World. Much like this one: http://codegolf.stackexchange.com/questions/307/obfuscated-hello-world - it's the win condition that changes the whole game.

This seems relevant to your discussion http://meta.codegolf.stackexchange.com/questions/777/are-two-questions-duplicates-if-they-have-different-scoring-rules

@GlenO: I disagree that the win condition changes the puzzle (as suggested by m.buettner's link). Mind you, I'm only not close-voting as duplicates because m.buettner points out that this is to save code-bowling, which I'm okay with.

@m.buettner - better?

I created a JSFiddle where you can put your code and it will automatically figure out your score. Would you be okay with me editing a link to it it in to the post?

@Doorknob: Ha nice I had just made a python script to do just that.

Can/should the output contain a final newline?

@Dennis - if your program produces a newline because of the command, no problem (for instance, println in Julia prints and then adds a newline on the end). But it shouldn't be part of the string.

@Doorknob - thanks, I've edited it in and credited you with it.

Stupid question, is something like println("Hello, World") valid?

So the goal is to write the longest program, not the shortest, right?

@Knerd - it's almost valid (it should be "Hello, world!" rather than "Hello, World"), but it's not particularly helpful - it has a score of just 3, which is pretty low.

@ACarter - basically, yes. But the restrictions and the deductions make it non-trivial.

@GlenO, thanks for the reply, yeah thats true. I just asked because I had the idea to use a typdef, but it is probably the worst version :D

Can we take input if it counts toward the score?

Perl - 96
(Pretty good, given the theoretical max 97 score)
s{}[Hel0o, w3$=d!];y<"#%&'*.124578:?@BCDEFGIJKLMNOQ/-9>(
    6PRSTUVWXYZ^_`abfghjmqvxz|~\cAk-u)+print

(Note that second line starts with an actual \t tab character)
The code is 98 characters long and contains every ascii char exactly once, plus an extra -.
98 - 2 = 96
There are no string literals here, but removal of any single character breaks the program.
Deobfuscation
There are 3 statements in this program (well, actually 2 but I abused + as some kind of statement separator)

s{}[Hel0o, w3$=d!]
This is a very stretched case of the sed operator. It is more commonly written as s/a/b/, or s:a:b:, but perl allows much more fantasy here: s(a)(b) s(a)^b^ s(a)[b], and even s qaqbq.
It replaces an empty string (inside {}) with Hel0o w360d! (inside []) ($= interpolates to 60 by default). Because of the lack of an ~= operator, it operates on $_.

y<"#%&'*.124578:?@BCDEFGIJKLMNOQ/-9>(\n\t6PRSTUVWXYZ^_`abfghjmqvxz|~\cAk-u)
This is also a very stretched case, but of a tr operator, which is also called y (y< >( )).
Let's look at the replacement table:
" # %&'*.124578:?@BCDEFGIJKLMNOQ    /-9
\n\t6PRSTUVWXYZ^_`abfghjmqvxz|~\cA  k-u
I have moved some characters around so that existing string is not broken. The only actually working part here is /-9 -> k-u. It replaces 0 with l, 3 with o, and 6 with r.
Again because of lack of the ~= operator, it operates on $_
So now we have the complete phrase in the $_ variable.

print
Lack of arguments makes it print just the $_ variable.

I don't know Perl enough to comment on this - what is the set of characters between the < and + doing?

@GlenO Only /-9 and k-u are actually used to transform the string. The rest is an equally sized garbage. If you remove just one char, the sets will misalign and the program won't output "Hello, world!" anymore.

In that case, in what way is the "garbage" being executed? That is, in what way is it functional? If it's just filler that gets jumped over by the code, then it's equivalent to non-running code within a conditional.

@GlenO It's not. To the spec: <...> removal of any single counting character must change the result or cause the code to not function. Removal of 1 character anywhere breaks it. You can make it work by removing 2 characters, but that's not in the rules.

All code must be functional. You're clearly bending the rules, at the very least. I'm not saying "it breaks the rules" outright, but it's definitely questionable.

One of the rules is replacement of any character literal or any character within a string literal with another character must be capable of changing the result, so if only a few characters of your y|tr arguments are required, does this mean you can substitute other characters?

@YiminRong y/// is not a string literal, it's a substitution literal.

@mniip - I think the intent is any literal, including numbers, not mentioned either.

+1, creative bending of the rules is the entire point of code golf

This answer was created before adding of the rule about string literals and does not participate in the contest.
#include <iostream>
int main(){std::cout<<56+"  !$%^&*?12347890-_QWERTYUIOPASDFGJKLZXVBNM,.qypfghjk:zvbHel\x6Co, world!";}

It's completely legit. :P
If you remove any character from that string, it will print ello, world!.

Please include the score of your code in your answer.

Also it won't change your score, but the the spaces around << need to be removed.

Hmmm... while I do applaud your answer, it has primarily revealed a minor hole in my restrictions. I'm going to give you an upvote, and I'm happy for others to do the same if they like it, but I'll be editing in an additional restriction.

OK, further to my previous comment, I've now added a restriction stating that string and character literals must be relevant - replacement of characters within them must be able to change the result. This allows if 'x'>'w' techniques, but blocks "k\bH" to result in "H", for instance. Feel free to contribute a second answer following the added restriction.

CJam, 94
{'H"EJO, WoRLD!"el96A+c/~_-3=0$@}"#
`&^<>|;:?.()[]\1aBCdfFgGhiIjkKmMnNpPqQrsStTuUvVwxXyYzZ"254b87%*

Try it online! Note that there should be a tabulator right before the linefeed. SE doesn't like tabulators, so you'll have to insert it manually.

100 characters long
repeated alnum:       -0 ()
repeated punctuation: -6 (""")
repeated other:       -0 ()
repeated whitespace:  -0 ()

Total score: 94
I've used the following code to check that none of the characters inside the string can be removed:
"#
`&^<>|;:?.()[]\1aBCdfFgGhiIjkKmMnNpPqQrsStTuUvVwxXyYzZ"
:A,,{_A\<A@)>+254b87%}%`

It prints an array showing the number of times Hello, world! would get printed if the character corresponding to the index were removed.

When I run it in your link, it produces "Hello, world!" six times in a row. Also, what is the string of characters doing?

I'm guessing the newline is the mistake - removing it makes it work.

Copy-paste issue. There should be a tabulator right before the LF. It looks like SE won't let me do that... The string is considered a base-254 number (254b). The final result modulus 7 should be 1, so the previous code block is executed once. I'll need a modulus to make each character necessary.

Well, after adding in the missing tab (which does "fix" the code), removing the Z, the T, or probably a few other characters doesn't change the result.

I had horribly misinterpreted a part of your question. It's fixed now.

Befunge-98, 97 points!
"v!dlrow ,h
B[CDEFGIJkLMNOPH
$<QRSTUV@|5cg1fe':-%\64*ab+7_/89}{0  j2
WXYZK`.=#>]
s()impq	n 3~
Atuxz&;y^ ?

Try it online!
The tab is between the q and the n.
Uses a similar trick to the previous Befunge answer to pad the lines with the leftover characters, but avoids using duplicate characters in the executing section. Removing any of the non-executing characters results in the executing parts being out of place, usually ending up in infinite loops or printing the wrong output.
How It Works
Really, the only executing part looks like:
"v!dlrow ,h
         k     H
$<      @|5cg1fe':-%\64*ab+7
         >]
        ^ ?

First it uses a wrapping string literal to add , world! to the stack. This avoids two "s.
$<      @|5cg1fe':-%\64*ab+7

This adds Hello to the stack using a variety of methods to avoid duplicate characters. $ pops the excess space caused by the wrapping string literal.
7+ adds 7 to the h from the end of the string literal to create the o
.
ba*46\%: calculates 111, the ascii value of l and duplicates it.
'e adds e to the stack.
f1g gets the character at 1,15 which is the H
It then reuses the , in the string to print out the whole Hello, world!. The rest is just direction changes to navigate to the ending @.

Ruby, 28 41
Just to start off the answers with a solution in the spirit of the question:
print"He#{?l*2}o, "+'world!'if[$`&(9<=>6)^7|~8-5/3.1%0x4]

Scoring (I think I got this right):

57 characters long
repeated alnum:       -12 (orli)
repeated punctuation: -4 ("')
repeated other:       -0
repeated whitespace:  -0

Looks fine to me, scoring-wise. No need to include penalties that don't apply, but no harm in including them.

The . in 3.1 can be removed without issue.  As can the x in 0x4 or the - in 8-5.

PHP, 1 (yes, one point!)
Using magic characters to generate a checksum, which in binary form matches "Hell", "o, w", "orld", and "!   ".
Usually I like to find loopholes, but this time I decided to play by the spirit and intent of the contest. Every character and its position is essential to the output. The only places you can substitute are variable names which are not literal values, the whitespace between php and foreach which PHP treats as equivalent, and use of ' vs " which PHP treats as similar.
<?php foreach(array('_MC:`~+V4@SbHR/l[J','dN#UB`5!Rv^NG@D}','9gm6L&-kuD','8OM97g.q]XQ0')as$j)print(hash("crc32",$j,1))?>

FYI, these are some other magic strings and hashes of interest:
E.D}S:  Hell
9UDIRQ: Hell
N\7&*`%:    orld
UWX[E^O:    orld
mAHzDEb:    !
uLJ7Ck&:    Hell
B+bG5mYJ:   Hell
:OvMzuOR:   !
TgYR9g!6k:  o, w
NkFN`!8mI:  o, w
N#VA\j~}J[: Hell
vEl*]@0XQ5: o, w
9gm6L&-kuD: orld
*}{Xg@HN`\: !
Pj@Y44uA6YJ:    Hell
|7OX0VF8gv}:    !
DLRJAjgMj}\:    !
!0bT*D}O4Lw:    orld
YGN97^v7ZY`:    Hell
++~bL/kP:|]W:   o, w
8OM97g.q]XQ0:   !
l^m-DqZ^g[&+:   !
Ewu]Rv~*DHQ7:   Hell
JIqjgF|S!\`8l:  Hell
b4l!MEG7vTu6/:  Hell
+B:zEq*J\k-Cm:  !
_}E7wZD76^`Y9AU:    orld
q:Nq-~+_S7~N9Hz:    !

The code still functions if I remove the \t, \n, or  the space. Not a PHP expert, but ; seems optional as well.

@mniip - Edits made. I was not aware the semicolon was optional in some cases.

Ruby, 78
More rules abuse, I feel like, not sure exactly what the patch'd be. Takes a long string and checks the sum of the result, so any deletion or change will cause the program to fail. Could probably be optimized a little to remove duplication of some letters and get whitespace in there.
puts('Hello, world!')if%["\#$&*+-/:;<>?@ABCDEFGIJKLMNOPQRSTUVWXYZ^_`abcghjknqvxyz{|}~123].sum==4980

The problem is, everything after and including the if can be removed.

@TheRare - nothing wrong with that, so long as the if does actually function and the stuff after it still obeys the rules.

@GlenO But isn't it counted as "removable code"? Just puts('Hello, world!') would work. I think the rules need clarifying if this is legit.

@TheRare - in hindsight, I probably should have used a sweeping "a subset of the code should not be capable of producing the same output", but I don't think I should continue to change the rules. As they stand, as long as the code is functional and non-arbitrary, and follows the other rules, it's legitimate. At the very least, this method of solution isn't achievable in most languages (the edit I did make closed a loophole that works in most languages).

@GlenO You're the judge. Just ask me to delete these comments if you feel they're unnecessary.

I made an even-higher-scoring submission in befunge.

PHP, 2257
Loophole: the backslash was omitted from the specifications and the score calculator!
This code counts the number of occurrences of backslashes in each string and prints an ASCII equivalent. Replacing any backslash with another character, or deleting a backslash, either causes a parse error or changes the result.
A neat feature about backslashes and PHP is that they need to be escaped, so that doubles the score automatically! You can re-double, triple, etc., the score by multiplying the number of backslashes, but didn't want to be greedy, and I think it might exceed the limits of what you can enter.
<?php foreach(array('\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\','\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\')as$x)print(chr(substr_count($x,"\\")))?>

It's clearly nothing more than a typo in the description, not a loophole. What's more, you knew that already. The description does explicitly say "other ASCII characters". By the time you read this, it'll have been edited to include it.

In particular, backslash was in the source of the question, but I hadn't realised that it had treated it as an escape sequence.

This isn't a change in rules, it's correcting a minor typo. The backslash was in the rules, it just wasn't displaying (to see this for yourself, click on the "edited" button, then click on "side-by-side markdown"). And the others aren't exploiting loopholes, they're exploiting features of their languages.

Befunge - 87
"dlrow ,olleH"bk,                                                                   v
!#$%&'()*+-./0123456789:;  <=>?ABCDEFGIJKLMNOPQRSTUVWXYZ[\]^_`acfghijmnpqstuvxyz{|}~@

The first line is worth four points due to all the repetition, but there are no duplicated characters on the second line. The only string literal in this code is dlrow ,olleH, which gets reversed and printed as output. Removing any one character will disconnect the v at the end of the first line from the @ at the end of the second, causing the program to never terminate. If the v itself is removed, then the code will go in to an infinite loop printing the correct output.

Acc!!, -138 (and yes that's negative 138)
While this may not exactly be the best score I've ever gotten in PPCG, I doubt it can get any higher than this in Acc!!
108
Write 72
Write 101
Count i while i-2 {
	Write _
}
Write _+3
Write 44
Write 32
Write 119
Write 111
Write 114
Write _
Write 100
Write 33

Try it online!

Aceto, 3
Finally managed to get a positive score!
"Hello, "-J' sJ"world!"∑-JUJpn

Try it online!

∑ isn't in printing ASCII

Pascal, 17
One of the few occasions on this site a verbose case-insensitive language is “useful”.
This is a program adhering to ISO standard 7185 “Pascal”:
PROGrAM{}Z(oUTput);BEgIN
WRiTe('Hello, world!':1*82-75+6)EnD.

authors: Кирилл Маевский

authors: Ярослав Тавченков

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/