0

I have four arrays(named array1,2,3,4) each with 8 objects and want to sort them into 8 empty arrays that will consist of 4 objects each, i.e place each object from array 1 into an empty array.

?? << array1.shift until array.empty?

I'm not sure how to iterate over the 8 empty arrays so that each of them recieves an object from array1

e.g

array1 = clubs1-8

array2 = spades1-8

array3 = hearts1-8

array4 = diamonds1-8

8 empty arrays or players, each player is dealt a card from array1,then 1 card from array2 etc.

Thanks for the answers but I wanted to add the objects iteratively so I could add conditions based on what objects had already been added to each array

e.g

distribute array1 among 8 empty arrays

distribute array2 among the 8 arrays but check before that no array contains the same card number (it can't have both the 2 of hearts and the 2 of diamonds)

1
  • 2
    Could you post a sample input and output? Commented Jul 25, 2011 at 16:51

3 Answers 3

2

Did you mean something like this?

require "matrix"

a1 = (0..7).to_a
a2 = (8..15).to_a
a3 = (16..23).to_a
a4 = (24..31).to_a

Matrix[a1, a2, a3, a4].transpose.to_a #=> [[0, 8, 16, 24], [1, 9, 17, 25], [2, 10, 18, 26], [3, 11, 19, 27], [4, 12, 20, 28], [5, 13, 21, 29], [6, 14, 22, 30], [7, 15, 23, 31]]

Added:

In fact it is even more trivial:

a1.zip(a2, a3, a4) #=> [[0, 8, 16, 24], [1, 9, 17, 25], [2, 10, 18, 26], [3, 11, 19, 27], [4, 12, 20, 28], [5, 13, 21, 29], [6, 14, 22, 30], [7, 15, 23, 31]]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, is there a way to do this with arguments, choosing which element to add depending on which items are in the array, e.g for the card example - not having a card of the same n.o in each array
1

Iteration is not the only way. Try this (assuming a1..a8 are your 8 empty arrays):

a1, a2, a3, a4, a5, a6, a7, a8 = array1.zip(array2, array3, array4)

Comments

0
irb(main):001:0> ar1 = [1,2,3,4,5,6,7,8]
=> [1, 2, 3, 4, 5, 6, 7, 8]
irb(main):002:0> ar2 = [2,3,4,1,2,3,2,1]
=> [2, 3, 4, 1, 2, 3, 2, 1]
irb(main):003:0> ar3 = [4,3,5,6,3,3,4,5]
=> [4, 3, 5, 6, 3, 3, 4, 5]
irb(main):004:0> ar4 = [5,2,5,6,7,2,2,5]
=> [5, 2, 5, 6, 7, 2, 2, 5]
irb(main):005:0> ar1.zip(ar2,ar3,ar4)
=> [[1, 2, 4, 5], [2, 3, 3, 2], [3, 4, 5, 5], [4, 1, 6, 6], [5, 2, 3, 7], [6, 3, 3, 2], [7, 2, 4, 2], [8, 1, 5, 5]]

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.