0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

rubyで二次元配列を4分割する方法

Last updated at Posted at 2020-12-26

諸事情あり誰得なメソッドを作成しました。
文字だとさっぱりだと思うので、絵を書きました!

例えばこういう任意の二次元配列があるとします。
スクリーンショット 2020-12-26 14.20.49 2 2.png

以下のように(1,1)のように任意の座標を指定し、4分割したいです。
スクリーンショット 2020-12-26 14.20.49.png

コードはこちらです。

def divide_2d_array(array, x, y)
    temp1 = []
    temp2 = []
    array.each do |a|
        temp1 << a[0..y]
        temp2 << a[(y+1)..-1]
    end
    a,c = temp1[0..x], temp1[(x+1)..-1]
    b,d = temp2[0..x], temp2[(x+1)..-1]
    return a,b,c,d
end

# 実行してみます
arr = [[1,2,3],
       [4,5,6],
       [7,8,9]]

p divide_2d_array(arr, 1, 1)
# =>[[[1, 2], [4, 5]], [[3], [6]], [[7, 8]], [[9]]]

できていますね!!!
もっといい方法あったら教えて下さい!

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?