Created
September 7, 2016 21:48
-
-
Save MiroslavCsonka/201d519145b513ebfa7d44a408ab1b2d to your computer and use it in GitHub Desktop.
Generate a matrix with a diagonal pattern
This file contains hidden or 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
[ | |
[[0, 0], [1, 0], [2, 0], [3, 0]], | |
[[0, 1], [1, 1], [2, 1], [3, 1]], | |
[[0, 2], [1, 2], [2, 2], [3, 2]], | |
[[0, 3], [1, 3], [2, 3], [3, 3]], | |
] | |
$rows = 4 | |
$columns = 4 | |
def get_next_index(index) | |
x, y = index | |
if (y+1) == $rows # bottom row, jump to right column | |
[y, x + 1] | |
elsif x == 0 # most left column, jump to top line | |
[y + 1, 0] | |
else | |
[x - 1, y + 1] | |
end | |
end | |
def assert(input, output) | |
raise [input, output, get_next_index(input)].inspect unless get_next_index(input) == output | |
end | |
class IndexGenerator | |
include Enumerable | |
def initialize | |
@current = [0, 0] | |
end | |
def each | |
loop do | |
yield @current | |
@current = get_next_index(@current) | |
end | |
end | |
end | |
# left column jumps | |
assert([0, 0], [1, 0]) | |
assert([0, 1], [2, 0]) | |
assert([0, 2], [3, 0]) | |
# bottom row jumps | |
assert([0, 3], [3, 1]) | |
assert([1, 3], [3, 2]) | |
assert([2, 3], [3, 3]) | |
# normal jump | |
assert([1, 0], [0, 1]) | |
assert([2, 0], [1, 1]) | |
assert([1, 1], [0, 2]) | |
elements_to_generate = $rows * $columns | |
p values = (1..elements_to_generate).to_a | |
p indexes = IndexGenerator.new.first(elements_to_generate) | |
matrix = Array.new($rows).map { |row| Array.new($columns) } | |
p matrix | |
indexes.each_with_index do |val, index| | |
x,y = val | |
value = values[index] | |
matrix[y][x] = value | |
end | |
p matrix |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment