-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3.rb
124 lines (100 loc) · 2.58 KB
/
3.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# PART 1
def find_vector(number)
return [0, 0] if number == 1
current_number = 1
x, y = [0, 0]
dx, dy = [1, 0]
distance = 1
direction_changes = 0
while true
distance.times do
current_number += 1
x += dx
y += dy
if current_number == number
return [x, y]
end
end
# change direction
direction_changes += 1
dx, dy = if [dx, dy] == [1, 0]
[0, 1]
elsif [dx, dy] == [0, 1]
[-1, 0]
elsif [dx, dy] == [-1, 0]
[0, -1]
elsif [dx, dy] == [0, -1]
[1, 0]
end
# every two changes of direction the distance increases
if direction_changes % 2 == 0
distance += 1
end
end
end
def manhattan_distance(origin, destination)
origin_vector = find_vector(origin)
destination_vector = find_vector(destination)
(origin_vector.first - destination_vector.first).abs + (origin_vector.last - destination_vector.last).abs
end
puts "Distance to 1"
puts manhattan_distance(1, 1)
puts "Distance to 12"
puts manhattan_distance(12, 1)
puts "Distance to 23"
puts manhattan_distance(23, 1)
puts "Distance to 1024"
puts manhattan_distance(1024, 1)
puts "Distance to 368078"
puts manhattan_distance(368078, 1)
## PART 2
def first_larger_number_than(number)
current_number = 1
x, y = [0, 0]
dx, dy = [1, 0]
values = {
[x, y] => current_number
}
distance = 1
direction_changes = 0
while true
distance.times do
x += dx
y += dy
current_number =
values[[x - 1, y]].to_i +
values[[x, y - 1]].to_i +
values[[x + 1, y]].to_i +
values[[x, y + 1]].to_i +
values[[x + 1, y + 1]].to_i +
values[[x - 1, y - 1]].to_i +
values[[x - 1, y + 1]].to_i +
values[[x + 1, y - 1]].to_i
values[[x, y]] = current_number
if current_number > number
return current_number
end
end
# change direction
direction_changes += 1
dx, dy = if [dx, dy] == [1, 0]
[0, 1]
elsif [dx, dy] == [0, 1]
[-1, 0]
elsif [dx, dy] == [-1, 0]
[0, -1]
elsif [dx, dy] == [0, -1]
[1, 0]
end
# every two changes of direction the distance increases
if direction_changes % 2 == 0
distance += 1
end
end
end
puts "First larger number than 10"
puts first_larger_number_than(10)
puts "First larger number than 142"
puts first_larger_number_than(142)
puts "First larger number than 368078"
puts first_larger_number_than(368078)