Ruby Quiz wrote:

> Today's quiz would've been most useful in elementary school, where over half of
> the homework assignments were word search puzzles. The concept of these puzzles
> is simple enough that an elementary school student could understand it:  given a
> box of letters, find a line containing the letters of a specified word in order.
>
> For example, find the words ruby, dan, rocks, and matz in the following text:
>
> 	U E W R T R B H C D
> 	C X G Z U W R Y E R
> 	R O C K S B A U C U
> 	S F K F M T Y S G E
> 	Y S O O U N M Z I M
> 	T C G P R T I D A N
> 	H Z G H Q G W T U V
> 	H Q M N D X Z B S T
> 	N T C L A T N B C E
> 	Y B U R P Z U X M S
>
> The correct answer in the correct output format:
>
> 	+ + + R + + + + + +
> 	+ + + + U + + + + +
> 	R O C K S B + + + +
> 	+ + + + + + Y + + +
> 	+ + + + + + + + + M
> 	+ + + + + + + D A N
> 	+ + + + + + + T + +
> 	+ + + + + + Z + + +
> 	+ + + + + + + + + +
> 	+ + + + + + + + + +

If you don't want snaking, put "--straight" on the command line.

def write ary
  ary.each{|c,row,col|  $out[row][col] = c }
end

def outside y, x
  y<0 or y>=Board.size or x<0 or x>=Board.first.size
end

def snake letters, row, col, directions, placed
  return  if letters[0] != Board[row][col]
  placed << [letters[0],row,col]
  if letters.size == 1
    write placed
    return
  end
  directions.each{|dy,dx|
    y = row + dy ; x = col + dx
    next  if outside( y, x )
    snake letters[1..-1], y, x, directions, placed.dup
  }
end

straight = ARGV.delete '--straight'

puts "Enter grid line by line, followed by blank line."
Board = []
while (line = gets.strip.upcase) != "" do
  Board << line
end

puts "Enter words separated by commas."
words = gets.strip.upcase.split(/\s*,\s*/)

$out = Board.map{|s| "+" * s.size}

all_directions = (-1..1).inject([]){|a,m| (-1..1).each{|n|
  a<<[m,n]}; a}
all_directions.delete [0,0]

Board.each_index{|row|
  Board[0].size.times{|col|
    words.each{|word|
      if straight
        all_directions.each{|direction|
          snake word, row, col, [direction], []
        }
      else
        snake word, row, col, all_directions, []
      end
    }
  }
}

puts "", $out.map{|s| s.split('').join(' ') }