I wanted to make program for solving 8 queens problem. I made "Table" class and started going through 8 iterations and making all possible combination of table so that none of the queens can attack one another. But somehow list at the end of the iteration is filled with same elements and the table from last iteration(Table table) which I am using as starting point for next one is changed as well. I have already seen posts about problems with ArrayList, but all of them were solved by making new instance of object in loop, but here new instance is alredy made inside loop.
Class Table
package mixony;
public class Table
{
private char[][] table;
private final int WIDTH = 8;
private final int HEIGHT = 8;
private final char COVERED = '+';
public Table()
{
table = new char[HEIGHT][WIDTH];
}
public char getField(int x, int y)
{
return table[y][x];
}
public void setQueen(int x, int y)
{
//SET THAT TILE AS QUEEN TILE
table[y][x]='Q';
//GO TROUGH THAT COLUMN AND FILL ALL THE COVERED TILES
for(int i=0; i<HEIGHT; i++)
if(table[i][x]!='Q')
table[i][x]=COVERED;
//GO TROUGH THAT ROW AND FILL ALL THE COVERED TILES
for(int i=0; i<WIDTH; i++)
if(table[y][i]!='Q')
table[y][i]=COVERED;
//GO TROUGH THAT DOWN VERTICAL AND FILL ALL THE COVERED TILES
int factor = (x<y)?x:y;
int x1=x-factor;
int y1=y-factor;
for (int i = 0; (x1 + i) < WIDTH && (y1 + i) < HEIGHT; i++)
if(table[y1+i][x1+i]!='Q')
table[y1+i][x1+i]=COVERED;
//GO TROUGH THAT UP VERTICAL AND FILL ALL THE COVERED TILES
x1=x;
y1=y;
while(true)
{
if(x1==0 || y1==WIDTH-1)
break;
x1--;
y1++;
}
for (int i = 0; (x1 + i) < WIDTH && (y1 - i) > 0; i++)
if(table[y1-i][x1+i]!='Q')
table[y1-i][x1+i]=COVERED;
}
public char[][] getTable() {
return table;
}
public void setTable(char[][] table) {
this.table = table;
}
public void log(int index)
{
System.out.println("\nTABLE "+index+"\n\t---------------------------------");
for (int y=0; y<HEIGHT; y++)
{
System.out.print("ROW "+y+"\t|");
for (int x=0; x<WIDTH; x++)
{
System.out.print(" "+getField(x, y)+" |");
}
System.out.print("\n\t---------------------------------\n");
}
}
}
Class with main method
package mixony;
import java.util.LinkedList;
public class PlayTest
{
public static void main(String[] args)
{
LinkedList<Table> tables = new LinkedList<Table>();
LinkedList<Table> improvedTables = new LinkedList<Table>();
tables.add(new Table());
final Table table = tables.get(0);
for(int y=0; y<8; y++)
{
for(int x=0; x<8; x++)
{
if(table.getField(x, y)!='Q'
&& table.getField(x, y)!='+')
{
Table imp = new Table();
imp.setTable(table.getTable());
imp.setQueen(x, y);
improvedTables.add(imp);
table.log(0);
}
}
}
}
}