-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path315.rb
More file actions
52 lines (43 loc) · 959 Bytes
/
315.rb
File metadata and controls
52 lines (43 loc) · 959 Bytes
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
load 'euler.rb'
def digital_roots_of(n)
if n < 10
[n]
else
[n] + digital_roots_of(digits_sum(n))
end
end
layout = [
[1, 1, 1, 0, 1, 1, 1],
[0, 0, 1, 0, 0, 1, 0],
[1, 0, 1, 1, 1, 0, 1],
[1, 0, 1, 1, 0, 1, 1],
[0, 1, 1, 1, 0, 1, 0],
[1, 1, 0, 1, 0, 1, 1],
[1, 1, 0, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 1, 0],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 1, 1]
]
diff = Array.new(10) { Array.new(10, 0) }
for i in 0..9
for j in 0..9
for k in 0..6
diff[i][j] += 2 * layout[i][k] * layout[j][k]
end
end
end
primes = primes_under(2e6).select { |n| n > 1e6 }
power_cost_diff = 0
primes.each do |p|
digit_roots = digital_roots_of(p)
number_digits = digit_roots.map { |n| digits(n) }
(digit_roots.size - 1).times do |i|
longer = number_digits[i]
shorter = number_digits[i + 1]
offset = longer.size - shorter.size
shorter.size.times do |j|
power_cost_diff += diff[ shorter[j] ][ longer[offset + j] ]
end
end
end
p power_cost_diff