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
|
#!/usr/bin/env ruby
@letters = {}
data = File.read("data.txt")
data = data.split("\n")
data = data.map(&:chars)
data.each_with_index do |row, y|
row.each_with_index do |letter, x|
@letters[[x,y]] = letter
end
end
PREFIX = "X"
SUFIX = %w(M A S)
found = 0
def find_with_vector(start_x, start_y, x, y)
word = (1..3).map do |iter|
@letters[[start_x + (iter * x), start_y + (iter * y)]]
end
true if word.to_a == SUFIX
end
potential_starts = @letters.select{|key, val| val == PREFIX }
potential_starts.each do |key, value|
found+= 1 if find_with_vector(key[0], key[1], 0, 1)
found+= 1 if find_with_vector(key[0], key[1], 1, 0)
found+= 1 if find_with_vector(key[0], key[1], 0, -1)
found+= 1 if find_with_vector(key[0], key[1], -1, 0)
found+= 1 if find_with_vector(key[0], key[1], 1, 1)
found+= 1 if find_with_vector(key[0], key[1], -1, 1)
found+= 1 if find_with_vector(key[0], key[1], 1, -1)
found+= 1 if find_with_vector(key[0], key[1], -1, -1)
end
p found
exit
def find_with_vector(start_y, start_x, y, x)
word = (1..3).map do |offset|
tested_row = @data[ start_x + offset* x ]
return false unless tested_row
letter = tested_row[ start_y + offset * y ]
return unless SUFIX.include? letter
letter
end
p [word, start_x, start_y, x, y] if word == SUFIX
true if word == SUFIX
end
found_count = 0
@data.each_with_index do |row, y|
row.each_with_index do |letter, x|
next unless letter == "X"
found_count += 1 if find_with_vector(x,y, 0, 1)
found_count += 1 if find_with_vector(x,y, 1, 0)
found_count += 1 if find_with_vector(x,y, 0, -1)
found_count += 1 if find_with_vector(x,y, -1, 0)
found_count += 1 if find_with_vector(x,y, 1, 1)
found_count += 1 if find_with_vector(x,y, -1, 1)
found_count += 1 if find_with_vector(x,y, 1, -1)
found_count += 1 if find_with_vector(x,y, -1, -1)
end
end
p found_count
|