Error in exchange for elements in the matrix

Asked

Viewed 275 times

-1

I’m trying to exchange two position elements in this matrix. After some changes, the elements begin to exchange among themselves in an apparently random pattern. Could someone identify me the mistake please?

def trocamatrizDess(matrizDes,seguradoX, seguradoY, xis, ips):

    auxRes = matrizDes[seguradoX][seguradoY]

    matrizDes[seguradoX][seguradoY] = matrizDes[xis][ips]

    matrizDes[xis][ips] = auxRes

#Matriz inicial:
     -97   -298  -198   1
     -200  -98   -297 -199
     -197  -100  -299 -300
     -99     3     2    0

#Matriz solução:
0 -100 -200 -300
1 -99 -199 -299
2 -98 -198 -298
3 -97 -197 -297

#Exemplo minimo completo e verificavel:



"""
A matrizResDesenho é uma matriz de inteiros que identificam sprites que formam uma imagem
embaralhada, o objetivo é formar a imagem original. Se um sprite deveria estar na
posição (3,0) para a imagem original estar correta o valor na matrizResDesenho[x][y] dele é
 calculado por -100*x + y, nesse caso seria -300 , tendo x e y como a posição atual dele.

A condiçãoPrimaria é True se o mouse estiver sobre um dos sprites dessa matriz e clicar 
nele. O x e y do momento identificam a posição do sprite, e assim segurando se torna True,
 pois é como se estivesse segurando o sprite.

Ao clicar em outro sprite já tendo um segurado, ambos elementos da matriz devem trocar de 
posição e agora segurando é false.

Os sprites também mudam de posição, mas isto não vem ao caso pois essa parte esta 
funcionando bem, só essa matriz de inteiros que da erro.

"""
         for x in range(4):
            for y in range(4):
                if (condicaoPrimaria):
                        if(not segurando):
                            cordX, cordY = x, y
                            segurando = True
                        else:
                            trocamatrizDess(matrizResDesenho, cordX, cordY, x, y)
                            segurando = False
  • It depends a lot on how you are calling this function and how you are setting the positions that will be exchanged. The behavior you cited does not appear to be caused by an error in this function.

  • I basically call it within two loop for, one that iterates the variable x and the other a y. if it happens again calls this function passing the insured and insured X, and the current x and y.

  • Exactly these two ties that may be causing the problem. Elaborate a [mcve] demonstrating the problem to facilitate our understanding.

  • Edited publication with the example included. What most intrigues me is that it is apparently correct in everything I look at in the code.

  • To be a [mcve] you will need to add the matrix you are using and describe what would be the expected result. It is also essential to explain what is condicaoPrimaria and segurando used in the code.

  • I hope I have not complicated the understanding too much. I edited once again

Show 1 more comment

1 answer

0

The problem there must be in how you create this data structure that you call "matrix" -

In fact, you have a list of lists - that could be used the way the snippet of code you present wants to do without problems.

But in Python there are no native multidimensional matrices - and there are right ways and wrong ways to create "list lists". If you create the wrong way, it will happen that a reference to the same list "column" - ie if you insert an element in the position [0][0] and its column [0] is the same object that is in other positions, will see the number placed there too:

In [1]: a = [0,0,0,0]                                                                                                                                  

In [2]: b = [a, a,a,a]                                                                                                                                 

In [3]: b                                                                                                                                              
Out[3]: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

In [4]: b[0][0] = 23                                                                                                                                   

In [5]: b                                                                                                                                              
Out[5]: [[23, 0, 0, 0], [23, 0, 0, 0], [23, 0, 0, 0], [23, 0, 0, 0]]

The ideal is either to use numpy, which actually has multidimensional array objects, or to create a well thought-out class to store your data by implementing the methods __getitem__ and __setitem__ to treat row and column references at once.

In [6]: import numpy as np                                                                                                                             

In [7]: c = np.zeros((4, 4))                                                                                                                           

In [8]: c                                                                                                                                              
Out[8]: 
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])

In [9]: c[0,0] = 23                                                                                                                                    

In [10]: c                                                                                                                                             
Out[10]: 
array([[23.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

(and no, your "minimum complete and verifiable" example is far from that - not only did not include the creation of your matrix, nor is Python valid - identation is not "toy" in Python - you get the first for in an arbitrary column - this is a syntax error. On line 3 you test a variable that did not appear before in your listing, as this is a "full example"???.

Tip: Always using 4 spaces, not trying to align your code with any position on the top line)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.