Skip to content

Instantly share code, notes, and snippets.

@ox
Last active December 11, 2015 10:49
Show Gist options
  • Save ox/4589819 to your computer and use it in GitHub Desktop.
Save ox/4589819 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# generates a matrix and display groups (blobs) in the matrix
# without arguments, generates a 5 * 5 matrix
# usage: blobs.rb [cols] [rows]
# example
# generated:
# [0, 0, 1, 0, 1]
# [0, 0, 0, 0, 1]
# [0, 0, 0, 0, 1]
# [0, 1, 1, 0, 1]
# [1, 0, 1, 0, 1]
#
# grouped:
# [0, 0, 2, 0, 3]
# [0, 0, 0, 0, 3]
# [0, 0, 0, 0, 3]
# [0, 4, 4, 0, 3]
# [5, 0, 4, 0, 3]
# generate an n * m length array of 1's and 0's in random order
def generate_matrix(m,n)
Array.new(m*n) {|i| rand.round }
end
# returns a matrix with each group numbered
def find_blobs(matrix, m, n)
group = 2
matrix.each_index do |index|
if matrix[index] == 1
matrix = find_neighbors(matrix, m, n, index, group)
group = group + 1
end
end
return matrix
end
# recursively look on all "sides" of the index'th element in search of neighbors
# neighbors are elements that equal 1, everything else is ignored
def find_neighbors(matrix, m, n, index, group)
return matrix if matrix[index] == 0 or index >= matrix.size
matrix[index] = group
# top
unless index - m < 0 or matrix[index - m] == group
matrix = find_neighbors(matrix, m, n, index - m, group)
end
# bottom
unless index + m > m * n or matrix[index + m] == group
matrix = find_neighbors(matrix, m, n, index + m, group)
end
# left
unless index % m == 0 or index == 0
matrix = find_neighbors(matrix, m, n, index - 1, group) unless matrix[index - 1] == group
end
# right
unless index % m == m - 1 or index == m * n
matrix = find_neighbors(matrix, m, n, index + 1, group) unless matrix[index + 1] == group
end
return matrix
end
def main
m = ARGV[0].to_i
n = ARGV[1].to_i
m = 5 if m == 0
n = 5 if n == 0
puts "generated:"
matrix = generate_matrix(m, n)
matrix.each_slice(m) {|a| p a}
puts "\ngrouped:"
matrix = find_blobs(matrix, m, n)
matrix.each_slice(m) {|a| p a}
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment