# Solution #2

**URL:** <https://www.ruby-forum.com/t/solution-2/81016>\
**Category:** Ruby\
**Created:** [January 3, 2007, 2:00am UTC](https://www.ruby-forum.com/t/solution-2/81016 "2007-01-03T02:00:44Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Alex\_Watt](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/cab0a1/32.png) [@Alex\_Watt](https://www.ruby-forum.com/u/Alex_Watt)\
**Post date:** [January 3, 2007, 2:00am UTC](https://www.ruby-forum.com/t/solution-2/81016/1 "2007-01-03T02:00:44Z")

</div>

This is probably a better solution than my first, but you can be the  
judge  
of that.

class Wordsearch  
DIRECTIONS = [[1,0],[-1,0],[0,1],[0,-1],[1,1],[1,-1],[-1,-1],[-1,1]]  
def initialize(wordsearch,words)  
@words = words  
@rows = wordsearch.split(/\s+/).delete\_if { |row| row == “” }  
@points = {}  
@letterPositions = []  
@rows.each\_with\_index do |row,y|  
row.split(//).each\_with\_index do |letter,x|  
@points[[x,y]] = letter  
end  
end  
end  
def solve  
@words.each { |word| search(word) }  
end  
def printWordsearch  
@rows.each\_with\_index do |row,y|  
row.split(//).each\_with\_index do |letter,x|  
print @letterPositions.include?([x,y]) ? letter : “+”  
end  
puts  
end  
end

private

def search(word)  
points(word[0].chr).each do |point|  
DIRECTIONS.each do |direction|  
possiblePoints = [point]  
point2 = point  
for i in (1…word.length)  
if checkNext(point2,word[i].chr,direction) or word[i].chr ==  
“_"  
or @points[(point2.to\_p + direction.to\_p).to\_a] == "_” # wildcard  
character  
= \*  
possiblePoints.push((point2 = (point2.to\_p +  
direction.to\_p).to\_a))  
end  
end  
@letterPositions += possiblePoints if possiblePoints.length ==  
word.length  
end  
end  
end  
def points(aLetter)  
points = []  
@points.each do |point,letter|  
points.push(point) if aLetter == letter  
end  
points  
end  
def checkNext(point,letter,direction)  
@points[(point.to\_p + direction.to\_p).to\_a] == letter  
end  
end

class Array  
def to\_p  
Point.new(self[0].to\_i,self[1].to\_i)  
end  
end

class Point  
attr\_reader :x,:y  
def initialize(x,y)  
@x,@y = x,y  
end  
def +(point)  
Point.new(@x + point.x,@y + point.y)  
end  
def to\_a  
[@x,@y]  
end  
end

wordsearch = “”  
loop do  
row = gets.chomp  
wordsearch += row + “\n”  
break if row == “”  
end  
words = gets.chomp.split(/\s\*,\s\*/).map { |word|  
word.upcase.gsub(/\s/,"") }  
w = Wordsearch.new(wordsearch.upcase,words)

w.solve  
w.printWordsearch
