Contents in an ArrayList get modified - java

I have a problem on a program I'm making that I honestly can't find a solution for. It seems the objects contained on a Java ArrayList collection are being modified without me programming such modifications.
The program as a whole is meant to basically create a random connection between two nodes on a 10x10 grid by moving through a path. This path is represented as an ArrayList collection of points in the grid, with the first index containing the first node's location (node A) and the last index containing the second node's location (node B). How I do this is by locating myself on A's location, and then moving randomly to contiguous points in the grid, repeating this in a while loop until B's location is reached.
Everything seems to work except that the "path" collection is altered somehow, such that every point in it ends up being the same as the last point to which I move, which is also B's location.
The method is as follows:
public void generateRandomPath()
{
path = new ArrayList<Point>();
path.add(pInitial);
complete = false;
while(!complete)
{
k = path.get(path.size()-1);
d = selectDirection(k);
GUI.log.append("==== Before the method. ==== \n");
GUI.log.append(Integer.toString(path.get(path.size()-1).getX())+" - "+Integer.toString(path.get(path.size()-1).getY())+"\n");
x = move(k, d);
path.add(x);
if(k.getX() == pEnd.getX() && k.getY() == pEnd.getY())
complete = true;
}
GUI.log.append("Finished. \n");
}
"Point" are simply points, with an X
and Y coordinate represented by
integers.
"pInitial" is the point representing the location of node A.
"pEnd" is the point representing the location of node B.
"d" is the direction on which I'm going to move on this repetition. This can be either up, right, down, or left represented by an integer 1, 2, 3, and 4 respectively.
"k" is the last point in the path, which is the point to which it moved on the previous repetition.
"x" is the new point to which it moved on the current repetition.
So what it basically does is it grabs the last point in the path as reference, chooses a direction, and then moves to the point contiguous on that direction. Each repetition of the while loop should add a new point to path. However what ends up happening is that not only is this new point added, but every other point already in path takes the value of this last point added. By utilizing the log entries show above (GUI.log.append) I managed to see that path is being mysteriously altered inside the step:
x = move(k, d);
Which is the following method:
private Point move(Point n, int y)
{
GUI.log.append("==== Inside the method. ==== \n");
GUI.log.append(Integer.toString(path.get(path.size()-1).getX())+" - "+Integer.toString(path.get(path.size()-1).getY())+"\n");
Point newP = n;
if(y == 1)
newP.setY(n.getY()-1);
if(y == 2)
newP.setX(n.getX()+1);
if(y == 3)
newP.setY(n.getY()+1);
if(y == 4)
newP.setX(n.getX()-1);
GUI.log.append("==== After method. ==== \n");
GUI.log.append(Integer.toString(path.get(path.size()-1).getX())+" - "+Integer.toString(path.get(path.size()-1).getY())+"\n");
return newP;
}
Integer y is the direction as mentioned before. As you can see this method does not alter path in any way, yet the logs show it does. In this example node A was on the point X = 2, Y = 3. The log shows what the coordinates of the last point in path are. As you can see, the coordinates of the last point in path take on the value of the coordinates of the new point, but this new point was not yet added to path.
I honestly don't know how this is happening. If anyone could think of a reason I would appreciate it very much if you could tell me.

Try
Point newP = new Point(n.getX(), n.getY());
instead of
Point newP = n;

Related

Finding nearest point excluding last point LibGDX Java

I am trying to find a way to get a bunch of points to connect via the ShapeRenderer`s method of line(Vector2 first, Vector2 second). So I will explain then show image and code to help.
There is a List of type Vector2 and I need to find the next closest vertice and then exclude the first point. Here is an image of what I mean. I labeled the iterations of the loop in the image.
1st iteration.) it finds the closest point.
2nd iteration.) it sees that the first point is closer but still chooses the third point. This is the core problem, I need to make sure the second point finds the third point even though the first point is the closer one.
Here is the code I have tried to do this.
private void cleanVertices(Array<Vector2> verts){
newVerts = new Array<Vector2>();
Vector2 tmpKey, tmpClose = null;
tmpKey = verts.get(0);
for(int i = 0; i < verts.size; i++){
for(int k = 0; k < (verts.size - 1); k++){
if(k == i)
continue;
//Distance formula
double dist = MathFactory.distance(verts.get(i), verts.get(k));
if(MathFactory.distance(verts.get(i), verts.get(k + 1)) < dist){
tmpClose = verts.get(k + 1);
}else
tmpClose = verts.get(i);
}
tmpKey = tmpClose;
newVerts.add(tmpClose);
}
}'
This does not accomplish what I need, instead, it seems to connect points closest on x-axis. I desperately need help with this. Thanks!
Make a deep copy of the input parameter verts (i.e. a new Array containing the same list of references in verts). Then iterate over that, but remove each point after you choose it as the next "nearest" neighbor.
I'm not familiar with the Array class, but an ArrayList would have the correct behavior when you remove an element. At each point only unvisited points would remain in the list.
since your problem is to find the closest vertex to the second vertex,which is the third in your case, without considering the first one. Make the second for loop starts from the position of the first for loop in every iteration ( k = i). Meaning that the second for loop will not consider the first vertex as point to calculate the distance from.

Connecting nodes in a matrix for a graph

Hi I'm working on this little project which requires me to build a matrix in Java which resembles a chess board. I'm supposed to get the Knight to get from a point to another(In the way Knight moves). So I need to find the shortest way to get there in the end.
My problem is, I can't get to connect the edges to get to that point. I can find out if the vertex is a valid move but I can't seem to find a way to create nodes to get to that point. For Example,
0 XXXXX
1 XXXOX
2 XXXXX
3 XXKXX
4 XXXXX
5 XXXXX
I need to create nodes that connect K to O to find out shortest distance later.
PS. I'll be okay with just hints of how to get there or just some tips. Don't really need the exact code. Thank you very much!
I know it's a bad representation of matrix up there but spare me the critique please
A classic Breadth-First-Search is probably the simplest approach:
class Location {
int x;
int y;
List<Location> adjacent() {
// TODO return list of locations reachable in a single step
}
}
List<Location> findShortestPath(Location start, Location destination) {
Location[][] previous = new Location[8][8];
Deque<Location> queue = new ArrayDeque<>();
queue.add(start);
do {
Location loc = queue.poll();
for (Location n : loc.neighbors()) {
if (previous[n.x][n.y] == null) {
previous[n.x][n.y] = loc;
queue.add(n);
if (n.x == destination.x && n.y == destination.y) {
// we've found a way, let's reconstruct the list of steps
List<Location> path = new ArrayList<>();
for (Location l = n; l != start; l = previous[l.x][l.y]) {
path.add(l);
}
path.reverse();
return path;
}
}
}
} while (!queue.isEmpty());
return null; // no path exists
}
This code enumerates all paths from the start location. Therefore, if there is a path to destination, it will find it. In addition, because paths are enumerated in order or ascending length, the first such path will be a shortest one.
The chess board can be implemented by a 2d array. Each cell in the matrix can be considered to be a node (or vertex) in the graph. Edge is composed of two nodes (in this case two cells) one being the from or source [ lets call it Nod A] and other being the to or neighbor or destination node [ Lets call it node B].
Edge exits if there is a possibility of moving from node A to node B.
You can use Dijkstra's algorithm.
http://krishnalearnings.blogspot.in/2015/07/implementation-in-java-for-dijkstras.html
For Node with the Knight's position you can see the possibilities of the cells where Knight can move to and add in the Min Heap. The weight of each edge is constant. You just need to update the cost of the Node.

How to hard-code legal moves for fast lookup?

I have created a gameboard (5x5) and I now want to decide when a move is legal as fast as possible. For example a piece at (0,0) wants to go to (1,1), is that legal? First I tried to find this out with computations but that seemed bothersome. I would like to hard-code the possible moves based on a position on the board and then iterate through all the possible moves to see if they match the destinations of the piece. I have problems getting this on paper. This is what I would like:
//game piece is at 0,0 now, decide if 1,1 is legal
Point destination = new Point(1,1);
destination.findIn(legalMoves[0][0]);
The first problem I face is that I don't know how to put a list of possible moves in an array at for example index [0][0]. This must be fairly obvious but I am stuck at this for some time. I would like to create an array in which there is a list of Point objects. So in semi-code: legalMoves[0][0] = {Point(1,1),Point(0,1),Point(1,0)}
I am not sure if this is efficient but it makes logically move sense than maybe [[1,1],[0,1],[1,0]] but I am not sold on this.
The second problem I have is that instead of creating the object at every start of the game with an instance variable legalMoves, I would rather have it read from disk. I think that it should be quicker this way? Is the serializable class the way to go?
My 3rd small problem is that for the 25 positions the legal moves are unbalanced. Some have 8 possible legal moves, others have 3. Maybe this is not a problem at all.
You are looking for a structure that will give you the candidate for a given point, i.e. Point -> List<Point>.
Typically, I would go for a Map<Point, List<Point>>.
You can initialise this structure statically at program start or dynamically when needing. For instance, here I use 2 helpers arrays that contains the possible translations from a point, and these will yield the neighbours of the point.
// (-1 1) (0 1) (1 1)
// (-1 0) (----) (1 0)
// (-1 -1) (0 -1) (1 -1)
// from (1 0) anti-clockwise:
static int[] xOffset = {1,1,0,-1,-1,-1,0,1};
static int[] yOffset = {0,1,1,1,0,-1,-1,-1};
The following Map contains the actual neighbours for a Point with a function that compute, store and return these neighbours. You can choose to initialise all neighbours in one pass, but given the small numbers, I would not think this a problem performance wise.
static Map<Point, List<Point>> neighbours = new HashMap<>();
static List<Point> getNeighbours(Point a) {
List<Point> nb = neighbours.get(a);
if (nb == null) {
nb = new ArrayList<>(xOffset.length); // size the list
for (int i=0; i < xOffset.length; i++) {
int x = a.getX() + xOffset[i];
int y = a.getY() + yOffset[i];
if (x>=0 && y>=0 && x < 5 && y < 5) {
nb.add(new Point(x, y));
}
}
neighbours.put(a, nb);
}
return nb;
}
Now checking a legal move is a matter of finding the point in the neighbours:
static boolean isLegalMove(Point from, Point to) {
boolean legal = false;
for (Point p : getNeighbours(from)) {
if (p.equals(to)) {
legal = true;
break;
}
}
return legal;
}
Note: the class Point must define equals() and hashCode() for the map to behave as expected.
The first problem I face is that I don't know how to put a list of possible moves in an array at for example index [0][0]
Since the board is 2D, and the number of legal moves could generally be more than one, you would end up with a 3D data structure:
Point legalMoves[][][] = new legalMoves[5][5][];
legalMoves[0][0] = new Point[] {Point(1,1),Point(0,1),Point(1,0)};
instead of creating the object at every start of the game with an instance variable legalMoves, I would rather have it read from disk. I think that it should be quicker this way? Is the serializable class the way to go?
This cannot be answered without profiling. I cannot imagine that computing legal moves of any kind for a 5x5 board could be so intense computationally as to justify any kind of additional I/O operation.
for the 25 positions the legal moves are unbalanced. Some have 8 possible legal moves, others have 3. Maybe this is not a problem at all.
This can be handled nicely with a 3D "jagged array" described above, so it is not a problem at all.

Need to draw a path using points in an arraylist

I've developed an android Travelling Salesman Problem (TSP) game application in which the user makes a path and plays against the computer, which uses the TSP algorithm to make a full path every time the user clicks to join two points with a line. Currently my method for the computer's path being draw is called whenever the user makes their move. However, my code is only allowing the first two points in the computer's path (stored in the arraylist called 'test') to be joined up.
public void CompDrawLine(List<Point> test) {
int d = 0;
int i;
test.add(test.get(0));
Point c = test.get(d);
for (i=0;i<test.size();i++)
{
cPath.moveTo(c.x,c.y);
c = test.get(d+1);
cPath.lineTo(c.x,c.y);
mCanvas.drawPath(cPath,cPaint);
// String testIndex = "this is iteration" + i;
// Toast.makeText(mContext, testIndex, LENGTH_SHORT).show();
}
cPath.reset();
}
How do I get the complete path drawn whenever the method is called??
I think your error is in the second line of your for loop. The variable d is never being incremented, so you are always using points 0 and 1. Personally, I would get rid of the d variable and just use i like this:
c = test.get(i+1);
However, another option would be to use d and increment it each time:
c = test.get(++d);
It must be a pre-increment though, or else you will be going from point 0 to point 0, and then point 1 to point 1, etc. instead of point 0 to 1, since d is initialized to 0.

Sample code not doing as expected

Here is the algorithm (not working) Please let me know where the error is
Thanks
private void checkSouth(Location point, int player) {
//Loop through everything south
boolean isthereAnOppositePlayer=false;
int oppositePlayer=0;
//Set opposite player
if (player==1) {
oppositePlayer=2;
}else{
oppositePlayer=1;
}
for (int i = point.getVertical(); i < 8; i++) {
//Create a location point with the current location being compared
MyLocation locationBeingChecked= new MyLocation();
locationBeingChecked.setHorizontal(point.getHorizontal());
locationBeingChecked.setVertical(i);
int value = board[locationBeingChecked.getVertical()][locationBeingChecked.getHorizontal()];
//If the first checked is the opposite player
if (value==oppositePlayer) {
//Then potential to evaluate more
isthereAnOppositePlayer=true;
}
//If it isn't an opposite player, then break
if(!isthereAnOppositePlayer && value!=0){
break;
}
//If another of the player's piece found or 0, then end
if (isthereAnOppositePlayer && value==player || isthereAnOppositePlayer && value==0) {
break;
//end
}
//Add to number of players to flip
if(isthereAnOppositePlayer && value==oppositePlayer && value!=0){
//add to array
addToPiecesToTurn(locationBeingChecked);
}
}
}
It looks like the locations that got rotated back to the other player are the exact same as those rotated during the first move. I would guess that the array being populated by addToPiecesToTurn is perhaps not being cleared out between each move, so all the previous locations are still in there.
If you are storing the pieces to be turned in an ArrayList, you can use the clear() method to erase the contents of the collection between each turn.
Another possible problem is that you are checking for the opposite player, and then instantly beginning to populate addToPiecesToTurn. However, the pieces in that direction are not necessarily valid to be rotated unless they are "sandwiched" in by a second location containing the current player's piece. I don't think your code is properly checking for that case; when that happens, you'll want to somehow skip flipping those pieces to the other player, such as clearing out the array of piecesToTurn.
Edit: Looking at your current solution where you are implementing every direction separately, you are going to have a lot of duplicated code. If you think about what it means to walk along a certain direction, you can think of it as adjusting the x/y value by a "step" amount. The step amount could be -1 for backwards, 0 for no move, or 1 for forwards. Then you could create a single method that handles all directions without duplicating the logic:
private void checkDirection(Location point, int player, int yStep, int xStep) {
int x = point.getHorizontal() + xStep;
int y = point.getVertical() + yStep;
MyLocation locationBeingChecked = new MyLocation();
locationBeingChecked.setHorizontal(x);
locationBeingChecked.setVertical(y);
while (isValid(locationBeingChecked)) {
// do the logic here
x += xStep;
y += yStep;
locationBeingChecked = new MyLocation();
locationBeingChecked.setHorizontal(x);
locationBeingChecked.setVertical(y);
}
}
You would need to implement isValid to check that the location is valid, i.e., in the board. Then you could call this method for each direction:
// north
checkDirection(curPoint, curPlayer, -1, 0);
// north-east
checkDirection(curPoint, curPlayer, -1, 1);
// east
checkDirection(curPoint, curPlayer, 0, 1);
// etc
This is the sort of problem that is ripe for some unit testing. You could very easily set up a board, play a move, and validate the answer, and the test results would give plenty of insight into where your expectations and reality diverge.
why didn't you use a 2d array ?
each cell would contain an enum : EMPTY, PLAYER_1, PLAYER_2 .
then, in order to go over the cells, you simply use loops for each direction.
for example, upon clicking on a cell , checking to the right would be:
for(int x=pressedLocation.x+1;x<cells[pressedLocation.y].length;++x)
{
Cell cell=cells[pressedLocation.y][x];
if(cell==EMPTY||cell==currentPlayerCell)
break;
cells[pressedLocation.y][x]=currentPlayerCell;
}
checking from top to bottom would be:
for(int y=pressedLocation.y+1;y<cells.length;++y)
{
Cell cell=cells[y][pressedLocation.x];
if(cell==EMPTY||cell==currentPlayerCell)
break;
cells[y][pressedLocation.x]=currentPlayerCell;
}

Categories