I'm another newbie to the ruby-quiz. This is a dirt-simple BFS. it
takes 8 seconds on my machine to do solve(22,999); i make sure no path
hits upon a number a previous path had ever hit upon, and i discovered
it'd run slightly faster by simply checking to see if my path is
halving right after doubling or doubling right after halving, and
*then* checking the entire list of numbers passed. (hope that made
sense)
i had toyed around with other optimizations but none seemed elegant
and time-saving enough to be worth it. what i was hoping for was a
nice way to identify when certain paths are careening insanely
off-path and clearly won't be the correct answer...i have yet to see
the solution that can do things like solve(222,9999) in
milliseconds...i am anxiously awaiting one...or did i miss it?
here is mine:
--------------------------------
def solve(start, finish)
paths = [[start, start+2], [start, start*2]];
paths.push([start, start/2]) if (start%2 == 0);
allNum = paths.flatten.uniq;
loop {
newP = Array.new();
paths.each{ |path|
curN = path.last;
unless(allNum.include?(curN+2))
return path.push(curN+2) if (curN+2 == finish);
allNum.push(curN+2);
newP.push(path.clone.push(curN+2));
end
unless (allNum.include?(curN*2))
return path.push(curN*2) if (curN*2 == finish);
allNum.push(curN*2);
newP.push(path.clone.push(curN*2));
end
if (curN%2 == 0 and not allNum.include?(curN/2))
return path.push(curN/2) if (curN/2 == finish);
allNum.push(curN/2);
newP.push(path.clone.push(curN/2));
end
}
paths = newP;
}
end