Skip to content

Instantly share code, notes, and snippets.

@shinokada
Created April 30, 2014 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shinokada/11441112 to your computer and use it in GitHub Desktop.
Save shinokada/11441112 to your computer and use it in GitHub Desktop.
# http://stackoverflow.com/questions/23382474/is-there-any-way-to-create-2-x-2-array-matrix-from-a-larger-array-matrix
require 'matrix'
def find_in_matrix(arr,sub)
sub_nrows = sub.size
sub_ncols = sub.first.size
rows = Array(0..(arr.size - sub_nrows))
cols = Array(0..(arr.first.size - sub_ncols))
arr_m = Matrix[*arr]
sub_m = Matrix[*sub]
rows.product(cols).select { |i,j| arr_m.minor(i,sub_nrows,j,sub_ncols)==sub_m }
end
arr = [['J','O','I','J','O'],
['I','J','O','J','O'],
['I','I','J','I','J']]
sub = [['J', 'O'],
['I', 'J']]
p find_in_matrix(arr,sub)
#=> [[0, 0], [1, 1], [1, 3]]
# Notes
# sub_nrows = sub.size #=> 2
# sub_ncols = sub.first.size #=> 2
# rows = Array[*0..(arr.size-sub_nrows)] #=> [0, 1]
# cols = Array[*0..(arr.first.size-sub_ncols)] #=> [0, 1, 2, 3]
# arr_m = Matrix[*arr]
# #=> Matrix[["J", "O", "I", "J", "O"], ["I", "J", "O", "J", "O"],
# # ["I", "I", "J", "I", "J"]]
# sub_m = Matrix[*sub]
# #=> Matrix[["J", "O"], ["I", "J"]]
#
# a = rows.product(cols)
# #=> [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3]]
# a.select {|i,j| arr_m.minor(i,sub_nrows,j,sub_ncols)==sub_m}
# #=> [[0, 0], [1, 1], [1, 3]]
# Consider the first element of a that select passes into the block: [0, 0] (i.e., the block variables i and j are both assigned the value zero). We therefore compute:
#
# arr_m.minor(i,sub_nrows,j,sub_ncols) #=> arr_m.minor(0,2,0,2)
# #=> Matrix[["J", "O"], ["I", "J"]]
# As
# arr_m.minor(0,2,0,2) == sub_m
# [0, 0] is selected. On the other hand, for the element [1, 2] of a, i => 1, j => 2, so:
#
# arr_m.minor(i,sub_nrows,j,sub_ncols) #=> arr_m.minor(1,2,2,2)
# #=> Matrix[["O", "J"], ["J", "I"]]
# which does not equal sub_m, so the element [1, 2] is not selected.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment