justhechi
justhechi

Reputation: 13

4x4 Matrix in Python

Im trying to code a 4x4 matrix in python with random integers 1-4. Thats easy enough my problem is i want for each row and each column only one time uses of each digit 1-4

example

1 2 3 4

2 3 4 1

3 4 1 2

4 1 2 3

my code does it like 33% of the time in my loop there happens somthing like this

2 1 4 3

3 4 2 1

1 3 X <-------- because of this the programm cant contiune and I end up in an infinity loop could someone helb how can i get out? my code below

""" Programm for playing the game skyline """
from random import randrange

row1 = [] 
row2 = []
row3 = []
row4 = []
allrows = [row1, row2, row3, row4]

column1 = []
column2 = []
column3 = []
column4 = []
allcolumns = [column1, column2, column3, column4]

def board():
    for i in range(4):
        j = 0
        while len(allrows[i]) != 4:
            x = randrange(1,5)
            print(i, j)
            if x not in allrows[i] and x not in allcolumns[j]: 
                allrows[i].append(x)
                allcolumns[j].append(x)
                j += 1

            else:
                continue

board()

Upvotes: 1

Views: 7895

Answers (3)

ganta sagarreddy
ganta sagarreddy

Reputation: 1

I have tried this using for, if and elif; for ranges more than 4 it is working.

x=int(input("enter your range"))
for i in range(x+1):
if i+1<x+1:
print(i+1,end='')
if(i+2<x+1):
   print(i+2,end='')
   if(i+3<x+1):
    print(i+3,end='')
    if(i+4<x+1):
     print(i+4)
    elif(i!=0 and i+4>=x+1):
      print(i)
   elif(i!=0 and i+3>=x+1):
    print(i-1,end='')
    print(i)
elif(i!=0 and i+2>=x+1):
  print(i-2,end='')
  print(i-1,end='')
  print(i)

Upvotes: 0

zipa
zipa

Reputation: 27879

You seem to be looking for permutations, and here is how to get them:

from itertools import permutations
a = list(permutations([1,2,3,4]))

Now to get random 4 lists:

import random

from itertools import permutations
a = list(permutations([1,2,3,4]))

for _ in range(4):
    print a[random.randint(0,len(a)-1)]

EDIT is this the one you were looking for:

import random
import numpy as np

from itertools import permutations
a = list(permutations([1,2,3,4]))

i = 0
result = [a[random.randint(0,len(a)-1)]]
a.remove(result[0])
print result
while i < 3:
     b = a[random.randint(0,len(a)-1)]
     if not any([any(np.equal(b,x)) for x in result]):
         result.append(b)
         i +=1
     a.remove(b)

print result

Upvotes: 1

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Basically, what you do is put the numbers you want to select from in a list. Randomly pick an index, use and remove it. Next time through, you pick one of the remaining ones.

Upvotes: 1

Related Questions