-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwords_path.mrb
More file actions
44 lines (37 loc) · 775 Bytes
/
words_path.mrb
File metadata and controls
44 lines (37 loc) · 775 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env ruby
from, to = ARGV
a = Time.now
$words = {}
File.new('/usr/share/dict/words').each do |line|
$words[line.chomp.downcase] = true if line.length == from.length+1
end
def siblings from
Enumerator.new do |enum|
from.length.times do |i|
w = from.dup
('a'..'z').each do |l|
w[i] = l
enum.yield w.dup if $words.delete(w)
end
end
end
end
def bfs from, to
parent = {}
queue = [from]
while !parent[to] and n = queue.shift
siblings(n).each do |child|
parent[child] = n
queue.push(child)
end
end
path = [to]
while parent[to]
path.unshift(parent[to])
to = parent[to]
end
path
end
b = Time.now
puts bfs(from, to).join(' -> ')
puts "load: #{b - a}; search: #{Time.now - b}"