Skip to content

Instantly share code, notes, and snippets.

@O-I
Created Oct 2, 2014
Embed
What would you like to do?
Ulam spiral
require 'prime'
def ulam_spiral(n)
matrix = Array.new(n) { Array.new(n) }
path = [*1..n*n].reverse
padding = (n*n).to_s.size
layer = 0
until path.empty?
matrix[layer].map! { |l| l || path.shift }
matrix = matrix.transpose.reverse
layer += 1 unless matrix[layer].include?(nil)
end
matrix = matrix.transpose.reverse until matrix[0][0] == n*n
matrix.transpose.each do |row|
row.each do |l|
if l.prime?
print "%0#{padding}d" % l, ' '
else
print ' ' * (padding + 1)
end
end
puts
end
end
ulam_spiral(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment