# [Tutor] Filling an array - with a twist

Alan Gauld alan.gauld at yahoo.co.uk
Wed Nov 11 04:45:19 EST 2020

```On 11/11/2020 06:30, Phil wrote:

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

You might need to write it out longhand with a function that
tracks the previous 2 results. There was a recent thread
discussing ways to do this (One of Manprits I think?)

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

Depending on what you need it for you could try generating smaller
lists then concatenating them. So for 8 items generate 2 lists
of 4 using sample. In the general case create n=(N/6)+1 lists each
of length N/n. Or just slice the final list to length N.
But that may not meet your definition of random...

Much slower is the manual method:

Lst = []
while len(Lst) < N:
item = randint(1,6)
if item == Lst[-1] and item == Lst[-2]:
continue
else: Lst.append(item)

But that only addresses a single row.

Checking that columns don't repeat is a whole extra level
of complexity! You need a nested loop and check the current
index against the previous two rows at the same position.
I'd definitely hide that in a function...

def validate(item, row, index, theList)

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

```