创建在红宝石二维阵列和存取子阵列 [英] Create two-dimensional arrays and access sub-arrays in Ruby

查看:114
本文介绍了创建在红宝石二维阵列和存取子阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有建立一个二维数组可能性,并快速访问任何水平或垂直的子阵列中的呢?

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?

推荐答案

有一些问题,2维阵列您实现它们的方式。

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

哈希阵列

我preFER使用散列的多维阵列

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

这有个好处,那您不必手动创建collumns或行。插入散列几乎 O(1),所以没有缺点在这里,只要你的哈希不会成为太大。

This has the advantage, that you don't have to manually create collumns 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)。从哈希检索元素几乎是O(1),所以几乎为O(n)的collect运行。现在有办法使它比为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 now way to make it faster than O(n), as copying n elements always is O(n).

散列可以有问题时,他们变得​​过于庞大。所以,我觉得两次有关实现多维阵列这样的,如果我知道我的数据量越来越大了。

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.

这篇关于创建在红宝石二维阵列和存取子阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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