Building a tester class? - java

I am a very new java user, and I have always had trouble with testing my programs. Here I have implement a basic boolean array interface. I want to test it buy adding a couple values and then running each of the interface methods. Please be nice I am not very good at this but I want to get better.
package booleanmatrix;
import java.util.Arrays;
/**
*
* #author David
*/
public class ArrayMatrix implements BooleanMatrixs {
private boolean a[][];
public int Rows;
public int Cols;
public int capacityr = 1;
public int capacityc = 1;
public int pT=0;
public int pF=0;
public ArrayMatrix() {
a = new boolean[capacityr][capacityc];
}
#Override
public int getNumberRows() {
return capacityr;
}
#Override
public int getNumberCols() {
return capacityc;
}
#Override
public void set(int row, int col) throws IndexOutOfBoundsException {
if (row > capacityr) {
capacityr = row;
boolean B[][] = new boolean[capacityr][capacityc];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
B[k][j] = a[k][j];
}
}
a = B;
}
if (col > capacityc) {
capacityc = col;
boolean C[][] = new boolean[capacityr][capacityc];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
C[k][j] = a[k][j];
}
}
a = C;
}
a[row][col] = true;
pT++;
}
#Override
public void clear(int row, int col) throws IndexOutOfBoundsException {
if (row > capacityr) {
capacityr = row;
boolean B[][] = new boolean[capacityr][capacityc];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
B[k][j] = a[k][j];
}
}
a = B;
}
if (col > capacityc) {
capacityc = col;
boolean C[][] = new boolean[capacityr][capacityc];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
C[k][j] = a[k][j];
}
}
a = C;
}
a[row][col] = false;
}
#Override
public void set(int row, int col, boolean value) throws IndexOutOfBoundsException {
if (row > capacityr) {
capacityr = row;
boolean B[][] = new boolean[capacityr][capacityc];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
B[k][j] = a[k][j];
}
}
a = B;
}
if (col > capacityc) {
capacityc = col;
boolean C[][] = new boolean[capacityr][capacityc];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
C[k][j] = a[k][j];
}
}
a = C;
}
a[row][col] = value;
if(value==true){
pT++;
}
}
#Override
public void toggle(int row, int col) throws IndexOutOfBoundsException {
if (row > capacityr) {
capacityr = row;
boolean B[][] = new boolean[capacityr][capacityc];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
B[k][j] = a[k][j];
}
}
a = B;
}
if (col > capacityc) {
capacityc = col;
boolean C[][] = new boolean[capacityr][capacityc];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
C[k][j] = a[k][j];
}
}
a = C;
}
if (a[row][col] == true) {
a[row][col] = false;
pT--;
} else {
a[row][col] = true;
pT++;
}
}
#Override
public void setAll() {
Arrays.fill(a, Boolean.TRUE);
pT=(capacityr*capacityc);
}
#Override
public void clearAll() {
Arrays.fill(a, Boolean.FALSE);
pT=0;
}
#Override
public void setAll(boolean value) {
if (value == false) {
Arrays.fill(a, Boolean.FALSE);
} else {
Arrays.fill(a, Boolean.TRUE);
pT=(capacityr*capacityc);
}
}
#Override
public boolean get(int row, int col) throws IndexOutOfBoundsException {
boolean x;
x = a[row][col];
return x;
}
#Override
public int[][] getTruePositions() {
int count = 0;
int ret[][] = new int[pT][2];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
if (a[k][j] == true) {
ret[count][0] = k;
ret[count][1] = j;
count++;
}
}
}
return ret;
}
#Override
public int[][] getFalsePositions() {
int total = (capacityr*capacityc);
int P=(total-pT);
int count=0;
int ret[][] = new int[P][2];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
if (a[k][j] == false) {
ret[count][0] = k;
ret[count][1] = j;
count++;
}
}
}
return ret;
}
#Override
public int[][] getPositions(boolean value) {
int total = (capacityr*capacityc);
int P=(total-pT);
int count=0;
if(value==false){
int retf[][] = new int[P][2];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
if (a[k][j] == false) {
retf[count][0] = k;
retf[count][1] = j;
count++;
}
}
}
return retf;}
else{
int count2 = 0;
int ret[][] = new int[pT][2];
for (int k = 0; k < capacityr; k++) {
for (int j = 0; j < capacityc; j++) {
if (a[k][j] == true) {
ret[count2][0] = k;
ret[count2][1] = j;
count2++;
}
}
}
return ret;
}}
#Override
public int getNumberTrueValues() {
return pT;
}
#Override
public int getNumberFalseValues() {
int total = (capacityr*capacityc);
int P=(total-pT);
return P;
}
#Override
public int getNumberValues(boolean value) {
if (value==false){
int total = (capacityr*capacityc);
int P=(total-pT);
return P;
}
else{return pT;}}
#Override
public String toString(){
String X= "1)The number of rows"+capacityr+"\n 2)The number of Columns"+capacityc+"\n 3)The number of True Values"+pT+"\n 4)The number of false values"+(capacityc*capacityr-pT);
return X;
}
public static void main(String[] args) {
}
}

Take a look at this JUnit tutorial. It might be just a bit of overkill, but a good unit testing framework is usually the best way to test your code at this level.

Add a new class that has a Main method (if you are using eclipse there is an auto click button that does that for you) then instantiate a new variable from your class.
ArrayMatrix arrayVar = new ArrayMatrix();
Then you would be able to access all the methods such as:
arrayVar.getNumberCols();

Related

Why my A* method can't find the solution? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 days ago.
Improve this question
I'm trying to implement the A* algorithm in Java in order to solve the 15-Puzzle, but I get an infinite loop and I don't understand why.
I tried with the removal of the openList.clear(); statement, but in this way I get another problem: the tiles begin to do some erroneous movements.
Here is the code of the Board:
public class BoardPrototype implements Prototype, Cloneable {
public Box[][] board;
public int manhattanDistance = 0;
public int g_n = 0;
public final List<Integer> finalList = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0);
#Override
public Object clone() {
try {
BoardPrototype cloned = (BoardPrototype) super.clone();
cloned.board = new Box[board.length][board[0].length];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
cloned.board[i][j] = new BoxBuilder()
.setX(board[i][j].getX())
.setY(board[i][j].getY())
.setValue(board[i][j].getValue())
.setG_n(board[i][j].getG_n())
.setInitialX(board[i][j].getInitialX())
.setInitialY(board[i][j].getInitialY())
.setManhattanDistance(board[i][j].getManhattanDistance())
.build();
}
}
return cloned;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
#Override
public boolean equals(Object o) {
if (o instanceof BoardPrototype that) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
if (board[i][j].getValue() != that.board[i][j].getValue())
return false;
}
}
return true;
} else {
return false;
}
}
#Override
public int hashCode() {
int result = Arrays.hashCode(board[0]);
for (int i = 1; i < board.length; i++) {
result = 31 * result + Arrays.hashCode(board[i]);
}
return result;
}
public void setBoard(Box[][] board) {
this.board = board;
}
public void setManhattanDistance(int manhattanDistance) {
this.manhattanDistance = manhattanDistance;
}
public int getManhattanDistance() {
manhattanDistance = 0;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
manhattanDistance += board[i][j].getManhattanDistance();
}
}
return manhattanDistance;
}
public void setG_n(int g_n) {
this.g_n = g_n;
}
public int getG_n() {
return this.g_n;
}
public BoardPrototype swap(int index1, int index2) {
BoardPrototype copy = (BoardPrototype) this.clone();
int row1 = index1 / 4;
int col1 = index1 % 4;
int row2 = index2 / 4;
int col2 = index2 % 4;
copy.board[row1][col1].setManhattanDistance(copy.board[row1][col1].getManhattan(index2, copy.board[row1][col1].getValue()));
copy.board[row2][col2].setManhattanDistance(copy.board[row2][col2].getManhattan(index1, copy.board[row2][col2].getValue()));
copy.board[row1][col1].setValue(copy.board[row2][col2].getValue());
copy.board[row2][col2].setValue(0);
copy.board[row1][col1].setInitialX(copy.board[row2][col2].getInitialX());
copy.board[row2][col2].setInitialX(copy.board[row1][col1].getInitialX());
copy.board[row1][col1].setInitialY(copy.board[row2][col2].getInitialY());
copy.board[row2][col2].setInitialY(copy.board[row1][col1].getInitialY());
copy.board[row1][col1].setG_n(copy.board[row2][col2].getG_n() + 1);
copy.board[row2][col2].setG_n(copy.board[row1][col1].getG_n() + 1);
copy.board[row1][col1].update();
copy.board[row2][col2].update();
return copy;
}
public List<BoardPrototype> neighbors(BoardPrototype board) {
ArrayList<BoardPrototype> neighbors = new ArrayList<>();
int blankIndex = board.getBlankIndex();
int row = blankIndex / 4;
int col = blankIndex % 4;
if (row > 0) {
BoardPrototype cloned = (BoardPrototype) board.clone();
cloned = cloned.swap(blankIndex, blankIndex - 4);
cloned.setManhattanDistance(cloned.getManhattanDistance());
neighbors.add(cloned);
}
if (col > 0) {
BoardPrototype cloned = (BoardPrototype) board.clone();
cloned = cloned.swap(blankIndex, blankIndex - 1);
cloned.setManhattanDistance(cloned.getManhattanDistance());
neighbors.add(cloned);
}
if (row < 3) {
BoardPrototype cloned = (BoardPrototype) board.clone();
cloned = cloned.swap(blankIndex, blankIndex + 4);
cloned.setManhattanDistance(cloned.getManhattanDistance());
neighbors.add(cloned);
}
if (col < 3) {
BoardPrototype cloned = (BoardPrototype) board.clone();
cloned = cloned.swap(blankIndex, blankIndex + 1);
cloned.setManhattanDistance(cloned.getManhattanDistance());
neighbors.add(cloned);
}
return neighbors;
}
public int getBlankIndex() {
int index = 0;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(this.board[i][j].getValue() == 0) {
index = i * 4 + j;
}
}
}
return index;
}
public boolean isSolved() {
int count = 0;
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(board[i][j].getValue() == finalList.get(count)) {
count++;
if (count == 16) {
return true;
}
} else {
return false;
}
}
}
return false;
}
}
And this one is the code of the class that implements the A* algorithm:
public class Game15Solver {
private static Game15Solver game15Solver;
ManhattanComparator manhattanComparator = new ManhattanComparator();
private Game15Solver() {}
public static Game15Solver getInstance() {
if(game15Solver == null) {
game15Solver = new Game15Solver();
}
return game15Solver;
}
public List<BoardPrototype> AStar(BoardPrototype board) {
PriorityQueue<BoardPrototype> openList = new PriorityQueue<>(manhattanComparator);
List<BoardPrototype> closeList = new ArrayList<>();
openList.add(board);
while (!openList.isEmpty()) {
BoardPrototype current = openList.poll();
closeList.add(current);
openList.clear();
if (current.isSolved()) {
System.out.println("Solved");
} else {
for (BoardPrototype neighbor : current.neighbors(current)) {
if (!closeList.contains(neighbor)) {
if(!openList.contains(neighbor)) {
neighbor.setG_n(current.getG_n() + 1);
openList.add(neighbor);
} else {
var tmpList = (Arrays.asList(openList.toArray()));
int ind = tmpList.indexOf(neighbor);
BoardPrototype boardPrototype = (BoardPrototype) tmpList.get(ind);
if(neighbor.getG_n() + 1 < boardPrototype.getG_n()) {
openList.remove(neighbor);
neighbor.setG_n(current.getG_n() + 1);
openList.add(neighbor);
}
}
}
}
}
}
return closeList;
}
}
Do you know how can I solve this problem? Thank you.

Solve Sudoko in Java

I've written the code as per the logic, but my Eclipse console is empty when I click 'Run'.
This is my code:
public class test {
public static void main(String[] args) {
int[][] board = new int[9][9];
helper(board, 0, 0);
}
public static void saveBoard(int[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
}
public static void helper(int[][] board, int row, int col) {
if (row == board.length - 1) {
saveBoard(board);
return;
}
if (col == board.length - 1) {
col = 0;
row += 1;
}
for (int i = 1; i <= 9; i++) {
if (isSafe(board, row, col, i)) {
board[row][col] = i;
helper(board, row, col + 1);
}
}
}
public static boolean isSafe(int[][] board, int row, int col, int number) {
// row & column
for (int i = 0; i < board.length; i++) {
if (board[row][i] == number) return false;
if (board[i][col] == number) return false;
}
// grid
int sc = (col / 3) * 3;
int sr = (row / 3) * 3;
for (int i = 0; i < sr + 3; i++) {
for (int j = 0; j < sc + 3; j++) {
if (board[i][j] == number) return false;
}
}
return true;
}
}
or here's a screenshot

java program to print number in integer as shuffle

Sorry if my question is not clear, lets say I have int a = 1234;.
How can I print as follows, for a number of any length?
123
132
213
231
321
312
Thanks in advance.
public class Test {
private static void swap(int[] p, int i, int j) {
int t= p[i];
p[i]= p[j];
p[j]= t;
return;
}
private static boolean nextPerm(int[] p) { // need p.length > 1
int n= p.length;
int i= n;
if (i-- < 1) return false;
for(;;) {
int ii= i--;
if (p[i] < p[ii]) {
int j= n;
while (!(p[i] < p[--j]));
swap(p, i, j);
for (j= n; j > ii; swap(p, --j, ii++));
return true;
}
if (i == 0) {
for (int j= n; j > i; swap(p, --j, i++));
return false;
}
}
}
public static void main(String[] args) {
int x = 123;
String s = "" + x;
int n = s.length();
int[] p = new int[n];
for (int i = 0; i < n; i++){
p[i] = i;
}
do {
for (int i = 0; i < n; i++){
System.out.print(s.charAt(p[i]));
}
System.out.println();
}
while (nextPerm(p));
}
}
finally I found, below is the code,
class ShuffleNumber {
private static int[] a = {1,2,3};
private static void print(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(" " + a[i]);
System.out.println();
}
private static void shuffle(){
int[] b = (int[])a.clone();
for (int i = b.length - 1; i > 0; i--) {
int j = (int)Math.floor(Math.random() * (i+1));
int temp = b[j];
b[j] = b[i];
b[i] = temp;
}
print(b);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
shuffle();
}
}

Get all 1-k tuples in a n-tuple

With n=5 and k=3 the following loop will do it
List<String> l=new ArrayList<String>();
l.add("A");l.add("B");l.add("C");l.add("D");l.add("E");
int broadcastSize = (int) Math.pow(2, l.size());
for (int i = 1; i < broadcastSize; i++) {
StringBuffer buffer = new StringBuffer(50);
int mask = i;
int j = 0;
int size=0;
System.out.println();
while (mask > 0) {
if ((mask & 1) == 1) {
System.out.println(".. "+mask);
buffer.append(l.get(j));
if (++size>3){
buffer = new StringBuffer(50);
break;
}
}
System.out.println(" "+mask);
mask >>= 1;
j++;
}
if (buffer.length()>0)
System.out.println(buffer.toString());
}
but it's not efficient I would like to do it with Banker's sequence and thus explore first singletons, then pairs, then 3-tuple and stop.
I did not find a way do that, but at least this loop should be more efficient:
List<String> l=new ArrayList<String>();
l.add("A");l.add("B");l.add("C");l.add("D");l.add("E");
int broadcastSize = (int) Math.pow(2, l.size());
for (int i = 1; i < broadcastSize; i++) {
StringBuffer buffer = new StringBuffer(50);
int mask = i;
int j = 0;
if (StringUtils.countMatches(Integer.toBinaryString(i), "1") < 4){
while (mask > 0) {
if ((mask & 1) == 1) {
buffer.append(l.get(j));
}
mask >>= 1;
j++;
}
if (buffer.length()>0)
System.out.println(buffer.toString());
}
}
there is also: but k embedded loops looks ugly
//singleton
for (int i = 0; i < l.size(); i++) {
System.out.println(l.get(i));
}
//pairs
for (int i = 0; i < l.size(); i++) {
for (int j = i+1; j < l.size(); j++) {
System.out.println(l.get(i)+l.get(j));
}
}
//3-tuple
for (int i = 0; i < l.size(); i++) {
for (int j = i+1; j < l.size(); j++) {
for (int k = j+1; k < l.size(); k++) {
System.out.println(l.get(i)+l.get(j)+l.get(k));
}
}
}
//...
// k-tuple
This technique is called Gosper's hack. It only works for n <= 32 because it uses the bits of an int, but you can increase it to 64 if you use a long.
int nextCombo(int x) {
// moves to the next combination with the same number of 1 bits
int u = x & (-x);
int v = u + x;
return v + (((v ^ x) / u) >> 2);
}
...
for (int x = (1 << k) - 1; (x >>> n) == 0; x = nextCombo(x)) {
System.out.println(Integer.toBinaryString(x));
}
For n = 5 and k = 3, this prints
111
1011
1101
1110
10011
10101
10110
11001
11010
11100
exactly as you'd expect.
this should be the most efficient way, even if k embedded loops looks ugly
//singleton
for (int i = 0; i < l.size(); i++) {
System.out.println(l.get(i));
}
//pairs
for (int i = 0; i < l.size(); i++) {
for (int j = i+1; j < l.size(); j++) {
System.out.println(l.get(i)+l.get(j));
}
}
//3-tuple
for (int i = 0; i < l.size(); i++) {
for (int j = i+1; j < l.size(); j++) {
for (int k = j+1; k < l.size(); k++) {
System.out.println(l.get(i)+l.get(j)+l.get(k));
}
}
}
// ...
//k-tuple
Apache commons has iterators for subsets of size k, and for permutations.
Here is an iterator that iterates through 1-k tuples of an n-tuple, that combines the two:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.collections4.iterators.PermutationIterator;
import org.apache.commons.math3.util.Combinations;
public class AllTuplesUpToKIterator implements Iterator<List<Integer>> {
private Iterator<int[]> combinationIterator;
private PermutationIterator<Integer> permutationIterator;
int i;
int k;
int n;
public AllTuplesUpToKIterator(int n, int k) {
this.i = 1;
this.k = k;
this.n = n;
combinationIterator = new Combinations(n, 1).iterator();
permutationIterator = new PermutationIterator<Integer>(intArrayToIntegerList(combinationIterator.next()));
}
#Override
public boolean hasNext() {
if (permutationIterator.hasNext()) {
return true;
} else if (combinationIterator.hasNext()) {
return true;
} else if (i<k) {
return true;
} else {
return false;
}
}
#Override
public List<Integer> next() {
if (!permutationIterator.hasNext()) {
if (!combinationIterator.hasNext()) {
i++;
combinationIterator = new Combinations(n, i).iterator();
}
permutationIterator = new PermutationIterator<Integer>(intArrayToIntegerList(combinationIterator.next()));
}
return permutationIterator.next();
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
public static List<Integer> intArrayToIntegerList(int[] arr) {
List<Integer> result = new ArrayList<Integer>();
for (int i=0; i< arr.length; i++) {
result.add(arr[i]);
}
return result;
}
public static void main(String[] args) {
int n = 4;
int k = 2;
for (AllTuplesUpToKIterator iter= new AllTuplesUpToKIterator(n, k); iter.hasNext();) {
System.out.println(iter.next());
}
}
}

Everytime I run this method my array is reset

Everytime I call set() it resets all the values in the array to false except for what ever the int row int col is because i set that to true before the method ends. Why is this happening I thought I was making a copy of the array B and then setting the values that are in A to the values in B? Or am I mistaken here.
public void set(int row, int col) throws IndexOutOfBoundsException {
if (row >capacityr) {
boolean B[][] = new boolean[row+1][capacityc+1];
for (int k = 0; k < capacityr; k++)
for (int j = 0; j < capacityc; j++)
B[k][j] = a[k][j];
capacityr=row;
a = B;
}
if (col >capacityc) {
boolean C[][] = new boolean[capacityr+1][col+1];
for (int k = 0; k <capacityr; k++)
for (int j = 0; j < capacityc; j++)
C[k][j] = a[k][j];
capacityc=col;
a = C;
}
a[row][col] = true;
pT++;
}
It should be easier to use an ArrayList but I think this would fix your problem.
public void set(int row, int col) throws IndexOutOfBoundsException {
if(row > capacityr) {
if(col > capacityc) {
//both row and col are too big
boolean temp[][] = new boolean[row+1][col+1];
//copy a
for(int i = 0; i <= capacityr; i++) {
for(int j = 0; j <= capacityc; j++) {
temp[i][j] = a[i][j];
}
}
//set all the new elements to false
for(int i = capacityr+1; i <= row; i++) {
for(int j = capacityc+1; j <= col; j++) {
temp[i][j] = false;
}
}
//set row and col and a to temp
temp[row][col] = true;
a = temp;
//update capacity
capacityr = row;
capacityc = col;
}
else {
//just row is too big
boolean temp[][] = new boolean[row+1][capacityc+1];
for(int i = 0; i <= capacityr; i++) {
for(int j = 0; j <= capacityc; j++) {
temp[i][j] = a[i][j];
}
}
for(int i = capacityr+1; i <= row; i++) {
temp[i][capacityc] = false;
}
temp[row][col] = true;
a = temp;
capacityr = row;
}
}
else {
if(col > capacityc) {
//just col is too big
boolean temp[][] = new boolean[capacityr+1][col+1];
for(int i = 0; i <= capacityr; i++) {
for(int j = 0; j <= capacityc; j++) {
temp[i][j] = a[i][j];
}
}
for(int j = capacityc+1; j <= col; j++) {
temp[capacityr][j] = false;
}
temp[row][col] = true;
a = temp;
capacityc = col;
}
else {
//neither are too big
a[row][col] = true;
}
}
}

Categories