# A\* (#98)

**URL:** <https://www.ruby-forum.com/t/a-98/102550>\
**Category:** Ruby\
**Created:** [October 15, 2006, 8:22pm UTC](https://www.ruby-forum.com/t/a-98/102550 "2006-10-15T20:22:58Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![danmcb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/13edae/32.png) [@danmcb](https://www.ruby-forum.com/u/danmcb)\
**Post date:** [October 15, 2006, 8:22pm UTC](https://www.ruby-forum.com/t/a-98/102550/1 "2006-10-15T20:22:58Z")

</div>

Here’s some test code against which you can test your solutions.

Note that if you follow the quiz statement, and pay no heed to my  
correction to the distance formula, you will fail one of the tests.

Adapters can easily be written for solutions that don’t use the same  
interface; for example, Roland S.'s solution can be adapted by  
adding this small chunk of code:

class Astar  
def do\_quiz\_solution(puzzle)  
@m = TileMap::Map.new(puzzle)  
results = TileMap.a\_star\_search(@m)  
out = puzzle.split(/\n/)  
results.each{|r,c| out[r][c] = ?#}  
out.join("\n")  
end  
end

Anyway, here’s the test code:

require ‘test/unit’  
require ‘astar’

class TC\_Astar \< Test::Unit::TestCase  
def setup  
@solver = Astar.new  
end

def assert\_paths\_equal(expected,actual,message=nil)  
actual = actual.sub(/^(\s\*\n)_/, ‘’)  
expected = expected.sub(/^(\s_\n)_/, ‘’)  
actual.sub!(/(\s_\n)_$/, ‘’)  
actual.gsub!(/^\s_/m,’’)  
actual.gsub!(/\s\*$/m,’’)  
expected.sub!(/(\s\*\n)_$/, ‘’)  
expected.gsub!(/^\s_/m,’’)  
expected.gsub!(/\s\*$/m,’’)  
expected.scan(/?/) {|x| expected[$~.begin(0)] =  
actual[$~.begin(0)]}  
assert\_equal(expected,actual,message)  
end

def test\_simple\_horizontal  
map = %q(@…X)  
solution = @solver.do\_quiz\_solution(map)  
assert\_paths\_equal(%q(####), solution)  
end

def test\_simple\_vertical  
map = %q(@…X).split(//).join("\n")  
solution = @solver.do\_quiz\_solution(map)  
assert\_paths\_equal(%Q(#\n#\n#\n#), solution)  
end

def test\_quiz\_statement  
map = %q(@_^^^  
~~_~.  
\*\*…  
^…_~  
~~_~X).sub(/ +/,’’)  
solution = @solver.do\_quiz\_solution(map)  
assert\_paths\_equal(  
%q(##^^^  
~~#~.  
\*\*??.  
^…#~  
~~\*~#), solution, “Didn’t do test solution”)  
end

def test\_bad\_distance  
map = %q(@.\*…  
…~…  
…^.X).sub(/ +/,’’)  
solution = @solver.do\_quiz\_solution(map)  
assert\_paths\_equal(  
%q(#?#…  
.?~#.  
…^.#), solution, “Got tripped up by manhattan distance”)  
end  
end
