在 Ruby 中创建二维数组并访问子数组 [英] Create two-dimensional arrays and access sub-arrays in Ruby

查看:19
本文介绍了在 Ruby 中创建二维数组并访问子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能创建一个二维数组并快速访问其中的任何水平或垂直子数组?

I wonder if there's a possibility to create a two dimensional array and to quickly access any horizontal or vertical sub array in it?

我相信我们可以在以下情况下访问水平子数组:

I believe we can access a horizontal sub array in the following case:

x = Array.new(10) { Array.new(20) }

x[6][3..8] = 'something'

但据我所知,我们无法像这样访问它:

But as far as I understand, we cannot access it like this:

x[3..8][6]

如何避免或破解此限制?

How can I avoid or hack this limit?

推荐答案

二维 Arrays 的实现方式存在一些问题.

There are some problems with 2 dimensional Arrays the way you implement them.

a= [[1,2],[3,4]]
a[0][2]= 5 # works
a[2][0]= 6 # error

Hash 作为 Array

我更喜欢将 Hashes 用于多维 Arrays

a= Hash.new
a[[1,2]]= 23
a[[5,6]]= 42

这样做的好处是,您不必手动创建列或行.插入哈希几乎是O(1),所以这里没有缺点,只要因为您的 Hash 不会变得太大.

This has the advantage, that you don't have to manually create columns or rows. Inserting into hashes is almost O(1), so there is no drawback here, as long as your Hash does not become too big.

您甚至可以为所有未指定的元素设置默认值

You can even set a default value for all not specified elements

a= Hash.new(0)

那么现在关于如何获取子数组

So now about how to get subarrays

(3..5).to_a.product([2]).collect { |index| a[index] }
[2].product((3..5).to_a).collect { |index| a[index] }

(a..b).to_a 在 O(n) 中运行.从 Hash 中检索元素几乎是 O(1),因此收集运行几乎是 O(n).没有办法让它比 O(n) 更快,因为复制 n 个元素总是 O(n).

(a..b).to_a runs in O(n). Retrieving an element from an Hash is almost O(1), so the collect runs in almost O(n). There is no way to make it faster than O(n), as copying n elements always is O(n).

Hashes 当它们变得太大时会出现问题.因此,如果我知道我的数据量越来越大,我会在实现这样的多维 Array 时三思而后行.

Hashes can have problems when they are getting too big. So I would think twice about implementing a multidimensional Array like this, if I knew my amount of data is getting big.

这篇关于在 Ruby 中创建二维数组并访问子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆