How to swap two points on a 2d array

I have two points on a 2d array that

I want to swap. It uses a custom class, and so far what I am basically doing is:

  Cell temp = cells[x][y+1];
  cells[x][y+1] = new Cell(blah,blah,blah);
  cells[x][y] = temp;

And that appears (I'm not sure) to be causing a problem.

Any help?

Tagged:

Answers

  • edited February 2018

    Your middle line should be:

    cells[x][y]= cells[x][y+1]; // error here

    And then

    cells[x][y+1]=temp;

    Anyway you could need a copy() function in your class that makes a new object with new with its own values. Return type the class.

  • uh, good point. i'm gonna make a copy function. and see if that code works

  • actually temp is cells[x][y+1] sorry

  • so uh, gravity went weird and the particles are growing (i'm making a falling sand game)

  • edited February 2018

    Oh, if those are classes then that might not work because you'll just be setting all the references to each other.

    Does your cell class have setters and getters?

  • ??

    That’s why I proposed copy ()....

  • (bad edit in my last message made it slightly incomprehensible, sorry)

    Chrisir, your first suggestion of changing the middle line just made it the same as the first line!

    But, yes, copy.

  • Although you don't really want three new cells created every time, better to use get and set, reusing the existing objects.

  • This question has no answer really. I have fixed this problem, and the project has ceased development.

  • edited April 2018

    This question has no answer really.

    I'm not sure what that means - it might mislead people with the same problem .

    You wanted to swap the points in two objects of a custom class. The advice from @koogs was to use getters, setters, and reusing the existing objects (C=A, A=B, B=C). That approach does work....

  • Yeah, when you fixed it, post your code or a demonstration for swap

  • gah. what i meant was that this doesn't need an answer. my code probably went something like this:

    Cell temp = new Cell((int)pos.x,(int)pos.y,cells[(int)pos.x+1][(int)pos.y+1].getType(),cells[(int)pos.x+1][(int)pos.y+1].isFlammable(),cells[(int)pos.x+1][(int)pos.y+1].isHot(),cells[(int)pos.x+1][(int)pos.y+1].getState(),cells[(int)pos.x+1][(int)pos.y+1].getWeight(),cells[(int)pos.x+1][(int)pos.y].getVar1()); cells[(int)pos.x+1][(int)pos.y+1] = new Cell((int)pos.x+1,(int)pos.y+1,type,flammable,hot,state,weight,var1); cells[(int)pos.x][(int)pos.y] = temp;

Sign In or Register to comment.