-
-
Notifications
You must be signed in to change notification settings - Fork 519
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Example spiral-matrix implementation
- Loading branch information
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
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
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 |