Last active
December 20, 2015 19:58
-
-
Save rampantmonkey/6186600 to your computer and use it in GitHub Desktop.
Project Euler problem #28
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class Spiral | |
def initialize | |
@diagonal_values = [] | |
@current = 0 | |
@spiral_count = 1 | |
recompute_diagonals | |
end | |
def step | |
@current += 1 | |
if diagonal? | |
@diagonal_values << @current | |
if @current == area | |
@spiral_count += 1 | |
recompute_diagonals | |
end | |
end | |
end | |
def total | |
@diagonal_values.inject(0,:+) | |
end | |
private | |
def area | |
width**2 | |
end | |
def width | |
2 * @spiral_count - 1 | |
end | |
def diagonal? | |
@diagonals.include? @current | |
end | |
def recompute_diagonals | |
@diagonals = [ | |
area, | |
area + 1 - width, | |
area + 2 * (1 - width), | |
area + 3 * (1 - width) | |
] | |
end | |
end | |
n = ARGV.first.to_i | |
s = Spiral.new | |
(n**2).times do | |
s.step | |
end | |
puts s.total |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That conditional was driving me nuts. Much faster to start in the middle and not have to worry about 1 every time.
Got it to where I think this is the fastest possible solution without having to worry about stack overflow:
And a wee bit more refined: