[Tutor] Filling an array - with a twist
Mats Wichmann
mats at wichmann.us
Wed Nov 11 11:21:05 EST 2020
On 11/10/20 11:30 PM, Phil wrote:
> Another call on the Brains Trust I'm afraid.
>
> I'd like to fill an 8 x 8 array (list of lists) with random numbers such
> that no column or row repeats the same number more than twice in a
> sequence.
>
> e.g.. [12344562] is OK but [12223456] is not wanted.
>
> Something like the following will give me a row or column that meets the
> requirements but more often than not fails the complete array test.
>
> >>> import random
> >>> r = random.sample(range(0,8),8)
> >>> r
> [6, 2, 4, 5, 3, 0, 1, 7]
>
> Searching through the array trying to repair an errant sequence is not
> the answer. Can anyone suggest an algorithm to do what I need?
>
> To add to the complication I really need numbers between 0 and 6 which
> random.sample() won't allow because, as the value error states, the
> sample is larger than the population.
>
since it's a small array, it should be find to do nested loops where you
count what's been seen, and generate a fresh random integer if one
doesn't fit the constraint (namely: already seen twice).
a collections.defaultdict makes a decent counter - it's a dictionary
which doesn't fail if the key hasn't been seen yet, so you can do
something like "if counter[i] < 2". You'll need one per "column", plus
one for the current "row" to do the complete job.
Might not do it this way if you're after a 100k x 100k array, but it's
small, and sounds like it's probably a one-off.
More information about the Tutor
mailing list