-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadventofcode2016-day1.rb
111 lines (96 loc) · 2.89 KB
/
adventofcode2016-day1.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
# 616112-20191025-4ee1e5ac
instructions = ""
File.open("day1-instructions.txt").each do |line|
instructions = line
end
directions = instructions.split(',')
facing = "NORTH"
coord_x = 0
coord_y = 0
visited_locations = Hash.new(0)
def update_hash(hash, x, y)
key = x.to_s + ',' + y.to_s
hash[key] += 1
if hash[key] > 1
# we've been here once before!
print "We've been to (" + x.to_s + ',' + y.to_s + ") before! "
#blocks = x.abs + y.abs
puts "Distance to Easter Bunny HQ is #{x.abs + y.abs}"
return true
end
return false
end
found = false
directions.each do |direction|
turn, distance = direction.strip.split(//, 2)
if turn != "R" && turn != "L"
puts "unknown turn '#{turn}'"
break
end
num_blocks = distance.to_i
if facing == "NORTH"
if turn == "R"
facing = "EAST"
num_blocks.times do
coord_x += 1
break if found = update_hash(visited_locations, coord_x, coord_y)
end
else # turn == "L"
facing = "WEST"
num_blocks.times do
coord_x -= 1
break if found = update_hash(visited_locations, coord_x, coord_y)
end
end
elsif facing == "SOUTH"
if turn == "R"
facing = "WEST"
num_blocks.times do
coord_x -= 1
break if found = update_hash(visited_locations, coord_x, coord_y)
end
else # turn == "L"
facing = "EAST"
num_blocks.times do
coord_x += 1
break if found = update_hash(visited_locations, coord_x, coord_y)
end
end
elsif facing == "EAST"
if turn == "R"
facing = "SOUTH"
num_blocks.times do
coord_y -= 1
break if found = update_hash(visited_locations, coord_x, coord_y)
end
else # turn == "L"
facing = "NORTH"
num_blocks.times do
coord_y += 1
break if found = update_hash(visited_locations, coord_x, coord_y)
end
end
elsif facing == "WEST"
if turn == "R"
facing = "NORTH"
num_blocks.times do
coord_y += 1
break if found = update_hash(visited_locations, coord_x, coord_y)
end
else # turn == "L"
facing = "SOUTH"
num_blocks.times do
coord_y -= 1
break if found = update_hash(visited_locations, coord_x, coord_y)
end
end
else
puts "something went very wrong!"
end
print turn + distance.to_s + " => ("
puts coord_x.to_s + ',' + coord_y.to_s + ")"
break if found
end
# puts visited_locations
#blocks = coord_y.abs + coord_x.abs
#puts "distance to Easter Bunny HQ is #{blocks}"