0

I'm trying to make an array with 30 integer elements between 0 and 2 randomly chosen. When some number is chosen 10 times, i can't append it anymore. In the end, I need an array with 30 elements with 10 numbers 0, 10 numbers 1 and 10 numbers 2. Here's what i'm trying:

import random
array_size = 30
number = 3
counter = [0, 0, 0]
solution = []

for i in range(array_size):
    number = random.randrange(number) #generates numbers between 0 and 2

    while counter[number] > 10:
        number = random.randrange(number)

    counter[number] += 1
    solution.append(number)

As result, i have more than 10 elements of the same number. I believe the problem is in the random number that i put in the while is not changed even if i change it inside the loop. Someone know how to do this?

Thanks

1
  • 2
    random.shuffle([0]*10 + [1]*10 + [2]*10) Commented Aug 8, 2016 at 23:30

2 Answers 2

2

Just change

while number[counter] > 10:

to

while number[counter] >= 10:

Originally your code would only stop appending a certain number only if there were more than 10 instances of it within your array. By changing it to a >=, the program will stop appending the number the moment it adds it for a tenth time.

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

Comments

1
import math
import random

number = 3
size = 30

steps = math.ceil(size / number)

solution = []
for x in range(steps):
    for n in range(number):
        solution.append(n)

random.shuffle(solution)
print(solution)

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.