I have 2d array
arr = [[1, 2, 1, 1],
[1, 1, 1, 1],
[1, 4, 4, 4],
[1, 4, 8, 4],
[1, 4, 4, 4]]
What is the best way to extract that array with lots of 4s when I know only the top left corner indexes?
arr[1][2]
I have 2d array
arr = [[1, 2, 1, 1],
[1, 1, 1, 1],
[1, 4, 4, 4],
[1, 4, 8, 4],
[1, 4, 4, 4]]
What is the best way to extract that array with lots of 4s when I know only the top left corner indexes?
arr[1][2]
The method Matrix#minor is taylor-made for this.
Code
require 'matrix'
def pull_subarray(arr, row_range, col_range)
Matrix[*arr].minor(row_range, col_range).to_a
end
Examples
pull_subarray(arr, 1..-1, 2..-1)
#=> [[1, 1],
# [4, 4],
# [8, 4],
# [4, 4]]
pull_subarray(arr, 1..2, 2..3)
#=> [[1, 1],
# [4, 4]]