-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathulam_spiral.rb
61 lines (52 loc) · 1.31 KB
/
ulam_spiral.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
50
51
52
53
54
55
56
57
58
59
60
61
class UlamSpiral
def initialize length
@length = length.to_i
@root = Math.sqrt(@length).to_i
@spiral = [[1]]
end
def square?
@root ** 2 == @length
end
def build
unless square?
puts "Output: #{@length} is not a perfect square"
exit
end
(2..@root).each do |step|
if step.even?
add_right_top step
else
add_left_bottom step
end
end
@spiral
end
protected
def add_right_top step
addition = addition(step)
first_part = addition.shift(addition.length / 2)
@spiral = @spiral.transpose << first_part.reverse
@spiral = @spiral.transpose.unshift addition.reverse
end
def add_left_bottom step
addition = addition(step)
first_part = addition.shift(addition.length / 2)
@spiral = @spiral.transpose.unshift first_part
@spiral = @spiral.transpose << addition
end
def addition(step)
(((step - 1) ** 2 + 1)..(step ** 2)).to_a
end
end
length = ARGV.first.to_i
if length > 0
puts "Input: #{length}"
spiral = UlamSpiral.new length
matrix = spiral.build
puts "Output: #{matrix.shift.map {|el| el.to_s.center(length.to_s.length + 1)}.join}"
matrix.each do |line|
puts " #{line.map {|el| el.to_s.center(length.to_s.length + 1)}.join}"
end
else
puts "Put square length as parameter"
end