1

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] 
4
  • 2
    What exactly are you trying to achieve? Commented Dec 1, 2014 at 9:52
  • Make a new smaller 3x3 array. Commented Dec 1, 2014 at 9:53
  • Do you, perchance, look to find a submatrix from a 2D array? Commented Dec 1, 2014 at 9:54
  • 1
    Why the rush to select an answer? For one, it's a discourtesy to others who are still preparing answers. Commented Dec 1, 2014 at 10:20

3 Answers 3

2
arr[2, 3].map { |row| row[1, 3] }
# => [[4, 4, 4], [4, 8, 4], [4, 4, 4]]

Get three rows starting from the second, for each row get three elements starting from the first (0-based).

Sign up to request clarification or add additional context in comments.

Comments

1

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]]

Comments

0

Another option:

arr[2..-1].map { |a| a[1..-1] }
# => [[4, 4, 4], [4, 8, 4], [4, 4, 4]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.