A nonogram is a puzzle that provides
numeric clues used to fill in a grid of cells,
establishing for each cell whether it is filled or not.
The puzzle solution is typically a picture of some kind.

Each row and column of a rectangular grid is annotated with the lengths
of its distinct runs of occupied cells.
Using only these lengths you should find one valid configuration
of empty and occupied cells, or show a failure message.

Example
Problem:                 Solution:

. . . . . . . .  3       . # # # . . . .  3
. . . . . . . .  2 1     # # . # . . . .  2 1
. . . . . . . .  3 2     . # # # . . # #  3 2
. . . . . . . .  2 2     . . # # . . # #  2 2
. . . . . . . .  6       . . # # # # # #  6
. . . . . . . .  1 5     # . # # # # # .  1 5
. . . . . . . .  6       # # # # # # . .  6
. . . . . . . .  1       . . . . # . . .  1
. . . . . . . .  2       . . . # # . . .  2
1 3 1 7 5 3 4 3          1 3 1 7 5 3 4 3
2 1 5 1                  2 1 5 1
The problem above could be represented by two lists of lists:

x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]]
y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]]
A more compact representation of the same problem uses strings,
where the letters represent the numbers, A=1, B=2, etc:

x = "C BA CB BB F AE F A B"
y = "AB CA AE GA E C D C"
Task
For this task, try to solve the 4 problems below, read from a “nonogram_problems.txt” file that has this content
(the blank lines are separators):

C BA CB BB F AE F A B
AB CA AE GA E C D C

F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC
D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA

CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC
BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC

E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G
E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM
Extra credit: generate nonograms with unique solutions, of desired height and width.



This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples).




 Related tasks
 Nonoblock.


See also
 Arc Consistency Algorithm
 http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell)
 http://twanvl.nl/blog/haskell/Nonograms (Haskell)
 http://picolisp.com/5000/!wiki?99p98 (PicoLisp)


F gen_row(w, s)
   ‘Create all patterns of a row or col that match given runs.’
   F gen_seg([[Int]] o, Int sp) -> [[Int]]
      I o.empty
         R [[2] * sp]
      [[Int]] r
      L(x) 1 .< sp - o.len + 2
         L(tail) @gen_seg(o[1..], sp - x)
            r [+]= [2] * x [+] o[0] [+] tail
      R r
 
   R gen_seg(s.map(i -> [1] * i), w + 1 - sum(s)).map(x -> x[1..])
 
F deduce(hr, vr)
   ‘Fix inevitable value of cells, and propagate.’
   F allowable(row)
      R row.reduce((a, b) -> zip(a, b).map((x, y) -> x [|] y))
 
   F fits(a, b)
      R all(zip(a, b).map((x, y) -> x [&] y))
 
   V (w, h) = (vr.len, hr.len)
   V rows = hr.map(x -> gen_row(@w, x))
   V cols = vr.map(x -> gen_row(@h, x))
   V can_do = rows.map(allowable)
 
   V mod_rows = Set[Int]()
   V mod_cols = Set(0 .< w)
 
   F fix_col(n)
      ‘See if any value in a given column is fixed;
        if so, mark its corresponding row for future fixup.’
      V c = @can_do.map(x -> x[@n])
      @cols[n] = @cols[n].filter(x -> @@fits(x, @c))
      L(x) @allowable(@cols[n])
         V i = L.index
         I x != @can_do[i][n]
            @mod_rows.add(i)
            @can_do[i][n] [&]= x
 
   F fix_row(n)
      ‘Ditto, for rows.’
      V c = @can_do[n]
      @rows[n] = @rows[n].filter(x -> @@fits(x, @c))
      L(x) @allowable(@rows[n])
         V i = L.index
         I x != @can_do[n][i]
            @mod_cols.add(i)
            @can_do[n][i] [&]= x
 
   F show_gram(m)
      L(x) m
         print(x.map(i -> ‘x#.?’[i]).join(‘ ’))
      print()
 
   L !mod_cols.empty
      L(i) mod_cols
         fix_col(i)
      mod_cols.clear()
      L(i) mod_rows
         fix_row(i)
      mod_rows.clear()
 
   I all(multiloop((0 .< w), (0 .< h), (j, i) -> @can_do[i][j] C (1, 2)))
      print(‘Solution would be unique’)
   E
      print(‘Solution may not be unique, doing exhaustive search:’)
 
   V out = [[Int]()] * h
 
   F try_all(Int n) -> Int
      I n >= @h
         L(j) 0 .< @w
            I @out.map(x -> x[@j]) !C @cols[j]
               R 0
         @show_gram(@out)
         R 1
      V sol = 0
      L(x) @rows[n]
         @out[n] = x
         sol += @try_all(n + 1)
      R sol
 
   V n = try_all(0)
   I n == 0
      print(‘No solution.’)
   E I n == 1
      print(‘Unique solution.’)
   E
      print(n‘ solutions.’)
   print()
 
F solve(p, show_runs = 1B)
   [[[Int]]] s
   L(l) p.split("\n")
      s [+]= l.split(‘ ’).map(w -> w.map(c -> c.code - ‘A’.code + 1))
   I show_runs
      print(‘Horizontal runs: ’s[0])
      print(‘Vertical runs: ’s[1])
   deduce(s[0], s[1])
 
L(p) File(‘nonogram_problems.txt’).read().split("\n\n")
   solve(p)
 
print(‘Extra example not solvable by deduction alone:’)
solve("B B A A\nB B A A")
 
print(‘Extra example where there is no solution:’)
solve("B A A\nA A A")