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

For now 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 quicker way..? This takes 1.107 seconds... (w=1900; h=1080) Regards

EDIT: I should've noticed that I'm stuck with 1.8.6..

2
  • 1
    There is no way this exact code takes over a second. You must have benchmarked it wrong! Commented Jan 31, 2013 at 17:13
  • 1
    Sorry, was with w=1900; h=1080 Commented Feb 1, 2013 at 8:01

3 Answers 3

6

Use either product or repeated_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+ (accepts a block in 1.9.2+) while repeated_permutation in 1.9.2+. For other versions of Ruby, you can use include my backports gem and include 'backports/1.9.2/array/repeated_permutation' or include 'backports/1.8.7/array/product'.

Sign up to request clarification or add additional context in comments.

1 Comment

@user1130886 Then definitely checkout backports. You'll be at basically at the level of 1.8.7 with a lot of goodies of 1.9, and in a few weeks I'm enabling some features of 2.0 too
4

This is similar to @nicooga's answer, but I would use a range instead of manually creating the array (ie so you do not have to type each number for larger 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]]

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.