Class: UlamSpiral
- Inherits:
-
Object
- Object
- UlamSpiral
- Defined in:
- lib/ulam_spiral.rb,
lib/ulam_spiral/version.rb
Constant Summary collapse
- VERSION =
"0.0.2"
Instance Attribute Summary collapse
-
#spiral ⇒ Object
readonly
Returns the value of attribute spiral.
Instance Method Summary collapse
-
#generate_spiral ⇒ Object
generate ulam spiral.
-
#initialize(params = {}) ⇒ UlamSpiral
constructor
A new instance of UlamSpiral.
-
#show ⇒ Object
Show on console spiral.
Constructor Details
#initialize(params = {}) ⇒ UlamSpiral
Returns a new instance of UlamSpiral.
9 10 11 12 13 14 15 16 |
# File 'lib/ulam_spiral.rb', line 9 def initialize(params = {}) @first_number = params[:first_number] || 1 @last_number = params[:last_number] || 100 @spiral = (0...square_length).to_a.map{ [nil] * (square_length) } @row = (square_length / 2.0).floor @column = ((square_length - 1) / 2.0).floor @spiral[@row][@column] = @first_number end |
Instance Attribute Details
#spiral ⇒ Object (readonly)
Returns the value of attribute spiral.
7 8 9 |
# File 'lib/ulam_spiral.rb', line 7 def spiral @spiral end |
Instance Method Details
#generate_spiral ⇒ Object
generate ulam spiral
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/ulam_spiral.rb', line 19 def generate_spiral direct = 2 ((@first_number + 1)..@last_number).each do |number| @row, @column = get_position(direct) if Prime.prime?(number) @spiral[@row][@column] = number if Prime.prime?(number) else @spiral[@row][@column] = "" end x, y = get_position(direct + 1) direct = (direct + 1) % 4 if @spiral[x][y].nil? end string_to_nil end |
#show ⇒ Object
Show on console spiral
36 37 38 39 40 41 42 |
# File 'lib/ulam_spiral.rb', line 36 def show length = @last_number.to_s.length + 1 @spiral.each do |row| puts "\n" puts row.map { |element| element.nil? ? " " * length : element.to_s.rjust(length, " ") }.join(" ") end end |