11
\$\begingroup\$

It has been a very long time since I've used Python.

What I'm looking for: I would like to create a 6-by-6 random matrix where each component is either 1 or 2, so that there are 18 ones and 18 twos.

Attempt:

import numpy
import random
array = numpy.zeros((6, 6))
while (array == 1).sum() != 18 or (array == 2).sum() != 18: 
 for i in range(0, 6):
 for j in range(0, 6):
 array[i][j] = random.randint(1, 2) 
print array 

Sure, this works. But this seems to me to be extremely inefficient, as the code is literally having to insert new matrix values until the number of ones/twos is 18. How can I make this more efficient?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Sep 16, 2015 at 2:56
\$\endgroup\$

1 Answer 1

13
\$\begingroup\$

Just create a list of 18 ones and 18 twos, shuffle it, then reshape to 6x6:

from random import shuffle
from numpy import reshape
nums = [1]*18 + [2]*18
shuffle(nums)
arr = reshape(nums, (6, 6))

Produces (for example):

array([[1, 2, 2, 1, 2, 1],
 [2, 2, 2, 2, 2, 1],
 [2, 2, 2, 1, 1, 2],
 [1, 1, 1, 1, 2, 2],
 [2, 1, 1, 2, 1, 1],
 [1, 2, 1, 1, 1, 2]])
answered Sep 16, 2015 at 3:05
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.