-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaze.rb
49 lines (42 loc) · 1.07 KB
/
maze.rb
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
45
46
47
48
49
require 'fileutils'
class Maze < Array
def generate
0.upto(self.size - 1) do |i|
self[i] = { :name => i, :value => i, :path => "%0#{size.to_s.length}d" % i }
end
self.each do |current|
break if self.are_all_the_same?
dest = self.pick_one_but_not(current[:value])
current[:value] = dest[:value]
self.update_paths(current, dest[:path] + '/' + current[:path])
end
self
end
def build(root)
self.each do |current|
FileUtils.mkdir_p root + '/' + current[:path]
end
end
protected
def are_all_the_same?
self.all?{|v| v[:value] == self.first[:value]}
end
def pick_one_but_not(i)
tmp = self.reject{|v| v[:value] == i}
self[tmp[(tmp.size * rand).floor][:name]]
end
def update_paths(current, new_path)
self[0..current[:name]].each do |o|
if o[:path].gsub!(current[:path], new_path)
o[:value] = current[:value]
end
end
end
end
size = ARGV[0].to_i
if size > 0
root = ARGV[1] || 'root'
Maze.new(size).generate.build(root)
else
puts 'Size must be greater than 0.'
end