从两个范围创建Ruby数组

4

I was looking for a way to create an array like:

[[1,1], [1,2], [1,3]
[2,1], [2,2], [2,3]
[3,1], [3,2], [3,3]]

目前我想到的解决方案是:

w=3 # or any int
h=3 # or any int
array = []
iw=1
while iw<=w do
  ih=1
  while ih <=h do
    array<<[iw, ih]
    ih+=1
  end#do
  iw+=1
end#do

但是,我相信一定有更快的方法吧..? 这需要1.107秒... (w=1900; h=1080) 祝好

编辑: 我应该注意到我被困在了1.8.6中..


1
这段代码不可能需要超过一秒钟的时间。你一定是测试有误了! - Marc-André Lafortune
1
抱歉,w=1900; h=1080。 - KenGey
3个回答

6

使用 productrepeated_permutation

[1, 2, 3].product([1, 2, 3]) # => [[1, 1], ...
# or
[1, 2, 3].repeated_permutation(2) # => [[1, 1], ...

product 是在 Ruby 1.8.7+ 中存在的(在 1.9.2+ 中可以接受一个块),而 repeated_permutation 则是在 1.9.2+ 中才有的。对于其他版本的 Ruby,你可以使用我的backports gem,并且包含 include 'backports/1.9.2/array/repeated_permutation' 或者 include 'backports/1.8.7/array/product'


2
@user1130886 那你一定要看看 backports。它可以让你基本上达到 1.8.7 的水平,并拥有许多 1.9 的好东西,再过几周我还会启用一些 2.0 的功能。 - Marc-André Lafortune

4
这与@nicooga的答案类似,但我会使用范围而不是手动创建数组(即对于更大的数组,您不必输入每个数字)。
range = (1..3).to_a
range.product(range)
#=> [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]

3

有一种更快的方法:

> [1,2,3].product([1,2,3])
=> [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接