Ruby array of two ranges

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

      

So far I came up with this solution:

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

      

But, I'm sure there must be a faster way ...? It takes 1.107 seconds ... (w = 1900; h = 1080) Relationship

EDIT: I should have noticed that I am stuck with 1.8.6 ..

+3


source to share


3 answers


This is similar to @nicooga's answer, but I would use a range instead of manually creating the array (i.e. you don't have to enter every number for large arrays).



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

      

+2


source


Use product

orrepeated_permutation

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

      



product

is in Ruby 1.8.7+ (takes a block in 1.9.2+) and repeated_permutation

in 1.9.2+. For other Ruby versions, you can use my backports

gem and include 'backports/1.9.2/array/repeated_permutation'

or include 'backports/1.8.7/array/product'

.

+4


source


There is a faster way:

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

      

+2


source







All Articles