Skip to content

Commit

Permalink
Example spiral-matrix implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
ccadden committed Feb 13, 2024
1 parent 39163d7 commit a5a30d6
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions exercises/practice/spiral-matrix/.meta/example.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class SpiralMatrix
private
attr_reader :counter, :dx, :dy, :x, :y

def initialize_matrix
Array.new(size) { Array.new(size, 0) }
end

def generate_matrix
while matrix_includes_zeroes?
@matrix[y][x] = counter

@dy, @dx = @dx, -@dy if next_step_invalid?

@x += dx
@y += dy

@counter += 1
end
end

def next_step_invalid?
@y + @dy == @size ||
(@y + @dy).negative? ||
@x + @dx == @size ||
(@x + @dx).negative? ||
!(@matrix[@y + @dy][@x + @dx]).zero?
end

def matrix_includes_zeroes?
@matrix.any? { |row| row.any?(0) }
end

public
attr_reader :size, :matrix

def initialize(size)
@size = size
@matrix = initialize_matrix
@dx = 1
@dy = 0
@y = 0
@x = 0
@counter = 1

generate_matrix
end
end

0 comments on commit a5a30d6

Please sign in to comment.