ArrayList replacing everything before when new element is added? - java

I'm attempting to add elements into an arraylist (also append an arraylist to the other), however it seems to rewrite everything else already present in that arraylist too - so I'm left with an arraylist filled with the last element added.
Here's the method concerned:
private static ArrayList<Move> checkX(int r, int c) {
ArrayList<Move> moves = new ArrayList<Move>();
if (jumps()) { // if jumps are found && this piece can jump
for (int i = 0; i <= 1; i+=2) {
if (Character.isLowerCase(board[r-1][c+i]) && board[r-2][c+2*i] == ' ') {
}
}
} else { // if no jumps are found then move normally
for (int i = -1; i <= 1; i+=2) {
try {
if (board[r-1][c+i] == ' ') {
Move tempMove = new Move(r, c);
tempMove.addDestination((r-1), (c+i));
moves.add(tempMove);
}
} catch (Exception e) {}
}
}
for (int i = 0; i < moves.size(); i++) {
System.out.println(moves.get(i).toString());
}
return moves;
}
Move class:
public class Move {
private static ArrayList<int[]> destinations;
// private static char[][] tmpboard;
public Move(int r, int c) {
destinations = new ArrayList<int[]>();
int[] initSquare = {r, c};
destinations.add(initSquare);
}
public void addDestination(int r, int c) {
int[] destinationSquare = {r, c};
destinations.add(destinationSquare);
}
public ArrayList<int[]> getMove() {
return destinations;
}
public String toString() {
String returnStr = "";
for (int i = 0; i < destinations.size(); i++) {
returnStr += Arrays.toString(destinations.get(i));
}
return returnStr;
}
}
Every time I attempt to print out everything stored in an instance of 'moves' it seems to only print out the last element added to the list n times.

private static ArrayList<int[]> destinations;
Here's your issue. Try removing the static modifier.
What static here means that the latest additions of destinations will affect all Move instances, which makes them identical.
It's possible you were thinking of final there instead, which would make more sense.

Related

(Java) ArrayList length becomes zero after a nonzero method

I am using an ArrayList to store objects that are "valid" for the purposes of my program and referencing it later in the same class file.
private static ArrayList<TownResource> validResources = new ArrayList<>();
A public method is called, which then calls a private method within the class that makes validResources's size nonzero.
public static boolean detection(int row, int col, TownResource[][] rArray, ResourceEnum[][][] bT, BuildingEnum buildingType) {
int checkTime = 0;
int patternIndex = 0;
try {
for (int i = 1; i < checkTime+1; i++) {
if (compare(row, col, rArray, buildingTemplate[patternIndex], buildingType)) {
for (int j = 0; j < validResources.size(); j++) {
validResources.get(j).setScannedBuilding(buildingType);
}
System.out.println("Size at compare" + validResources.size());
return true;
}
}
}
catch (ArrayIndexOutOfBoundsException e){
//System.out.println("Out of bounds exception?");
}
return false;
}
The compare method is a private method that on one condition, may clear validResources.
private static boolean compare(int row, int col, TownResource[][] rArray, ResourceEnum[][] buildingTemplate, BuildingEnum buildingType) {
for (int r = 0; r < buildingTemplate.length; r++) {
for (int c = 0; c < buildingTemplate[r].length; c++) {
if (match(rArray[row+r][col+c], buildingTemplate[r][c])) {
//System.out.println("Successful comparison at " + (row+r) + ", " + (col+c));
}
else {
validResources.clear();
return false;
}
}
}
return true;
}
match is what sets validResources to be nonzero in size:
private static boolean match(TownResource toBeChecked, ResourceEnum checker) {
if (checker == ResourceEnum.NONE) {
return true;
}
else if (toBeChecked.getResource() == checker) {
validResources.add(toBeChecked);
return true;
}
return false;
}
However, when I know validResources to be nonzero in size(this causes detection to return true which triggers a new method placement), it becomes zero.
public static void placement(TownResource[][] rArray, Building[][] bArray, BuildingEnum building) {
// other parts of method commented out for example
System.out.println(validResources.size());
for (int i = 0; i < validResources.size(); i++) {
System.out.println("Is this statement firing?");
System.out.println(validResources.get(i).getResource());
validResources.get(i).setResource(ResourceEnum.NONE);
}
Have I declared validResources incorrectly? Or is there something else at play?
Thank you.
This was an error in how I executed detection(). This method is called by another method within another class when iterating through a 2D array. The ArrayList validResources becomes nonempty in one check, but gets overwritten by another as a result of the program not calling placement until every object in the 2D array had detection called on it. I changed this to call placement immediately.

Recursively search 2D array without row and column indexing in method?

I'm currently working on a homework assignment and I'm really stuck on this idea of recursively searching an array without a row and column to index. I believe I can use helper methods but I'm new to recursion and find it a little confusing. This is the method that I'm not allowed to change (for the purpose of the assignment)
public Couple search(int[][]array, int element){
}
I'm also provided an inner class from the instructor. We haven't learned anything about inner classes, however, the appear to be nothing special. It is basic and I doesn't do anything special so I won't include the code unless there is something that is needed that I don't know. (I don't want to be cheating and I want to more-or-less figure it out too).
private class Couple{
// declaration of (int) row and (int) col
public Couple(row, col){
// this.row = row
// col = col
}
public String toString(){
// returns string
}
}
EDIT: I also can't use any loops
Edit: removed for-loop, added recursive Example
example for recursive subroutine
public class FindElement2DimArrayExample {
private class Couple {
private int row;
private int col;
public Couple(int row, int col) {
this.row = row;
this.col = col;
}
public String toString() {
return "[" + row + ", " + col + "]";
}
}
public static void main(String[] args) {
int[][] array = new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
System.out.println(new FindElement2DimArrayExample().search(array, 5));
}
public Couple search(int[][] array, int element) {
return searchRecursively(array, element, 0, 0);
}
public Couple searchRecursively(int[][] array, int element, int actualRow, int actualCol) {
if (array.length <= actualRow) {
return null;
} else if (array[actualRow].length <= actualCol) {
return searchRecursively(array, element, actualRow + 1, 0);
} else if (array[actualRow][actualCol] == element) {
return new Couple(actualRow, actualCol);
} else {
return searchRecursively(array, element, actualRow, actualCol + 1);
}
}
}
Recursion is not the best way to search a 2D Array, but if it is your assignment, you may try to realize it via the "Divide and Conquer" approach: Split the array into two parts and recursively call the method again on these two parts until you found the element.
Maybe this is useful for you: how to search elements in a 2d array using recursion
You didn't specify that you cant write some other method...
So i'd write another search method with signature:
private Couple search(Couple couple, int[][] array, int element)
Containing the following:
static private Couple search(Couple couple, int[][] array, int element) {
try {
System.out.println("Checking:" + couple + (array[couple.col][couple.row]));
} catch (ArrayIndexOutOfBoundsException aioobe) {}
if (couple.col>=array.length) return search(new Couple(0,couple.row+1),array,element);
if (couple.row>=array[0].length) return new Couple(-1,-1);
if (array[couple.row][couple.col] == element) return couple;
else return search(new Couple(couple.col+1,couple.row),array,element);
}
and call it from your other method by:
static public Couple search(int[][] array, int element) {
return search(new Couple(0,0),array,element);
}
That should do the trick.
Other then that (if you cant write additional method) then I'd use a stack.
full code:
public class NewClass1 {
static class Couple {
int col, row;
public Couple(int col, int row) {
this.col = col;
this.row = row;
}
#Override
public String toString() {
return "Couple{" + "col=" + col + ", row=" + row + '}';
}
}
static int[][] getArr(int nx, int ny) {
Random rand = new Random();
int[][] arr = new int[nx][ny];
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
arr[i][j] = rand.nextInt(90)+10;
}
}
return arr;
}
static void print(int [][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + ";");
}
System.out.println("");
}
}
static public Couple search(int[][] array, int element) {
return search(new Couple(0,0),array,element);
}
static private Couple search(Couple couple, int[][] array, int element) {
try {
System.out.println("Checking:" + couple + (array[couple.col][couple.row]));
} catch (ArrayIndexOutOfBoundsException aioobe) {}
if (couple.col>=array.length) return search(new Couple(0,couple.row+1),array,element);
if (couple.row>=array[0].length) return new Couple(-1,-1);
if (array[couple.row][couple.col] == element) return couple;
else return search(new Couple(couple.col+1,couple.row),array,element);
}
public static void main(String[] args) {
int[][] arr = getArr(10,10);
print(arr);
System.out.println(search(arr,11));
}
}

Bubble Sort an Array

I have an add point method, which adds a slot and puts a point inside. After adding the slot I want to sort what is in the array. How do I do that? Here is my code:
public void add(Point p)
{
int k;
for (int j = 0;j<myConsumerCurve.length;j++)
for (k=j+1;k<myConsumerCurve.length;k++)
if (k!=j && myConsumerCurve[k] == myConsumerCurve[j]) {
}
Point[] tempCurve = new Point [myConsumerCurve.length +1];
for(int i=0; i < myConsumerCurve.length; i++)
{
tempCurve[i] = myConsumerCurve[i];
}
tempCurve[myConsumerCurve.length] = p;
myConsumerCurve = tempCurve;
bubblesort(myConsumerCurve);
}
public static void bubblesort(Point[] myConsumerCurve)
{
}

Null Pointer Exception in LinkedList Hash Table

So I'm creating a hash table with LinkedLists using the multiplication method. As an instance variable I define the LinkedList "T" that I'll be using, and in the constructor of the class I specify the size of T. However, every time I run my Driver testing class, I get NullPointerExceptions on everything I try to reference anything in T[]. Am I overlooking something? I've spent over an hour trying to figure it out.
ChainedHashTable class:
public class ChainedHashTable
{
private LinkedList<Integer>[] T;
private int m;
private double A;
public ChainedHashTable(int n)
{
for (m = 1; m < n; m *= 2);
T = new LinkedList[m];
Random random = new Random();
int s = random.nextInt(Integer.MAX_VALUE);
A = (s * 1.00) / Integer.MAX_VALUE;
}
public void insert(Integer key)
{
T[hash(key)].add(Integer.valueOf(key));
}
public void delete(int key)
{
T[hash(key)].remove(Integer.valueOf(key));
}
public Integer search(int key)
{
int n = T[hash(key)].indexOf(key);
if (n == -1)
return -1;
else
return T[hash(key)].get(n);
}
private int hash(int key)
{
System.out.println((int)(m * ((key * A) % 1)));
return (int)(m * ((key * A) % 1));
}
public void printTable()
{
for (int i = 0; i < T.length; i++)
{
System.out.println("index: " + i + " " + T[i]);
}
}
}
Driver class:
public class Driver
{
public static void main(String[] args)
{
ChainedHashTable test1 = new ChainedHashTable(20);
test1.printTable();
test1.insert(4);
test1.insert(54);
test1.insert(6);
test1.insert(3);
test1.insert(26);
test1.insert(54);
test1.insert(11);
test1.insert(10);
test1.insert(76);
test1.insert(42);
test1.insert(41);
test1.insert(32);
test1.insert(87);
test1.insert(76);
test1.insert(72);
test1.insert(57);
test1.insert(29);
test1.insert(16);
test1.insert(92);
test1.insert(64);
test1.printTable();
}
}
You are creating an array of references to type LinkedList and setting them to their initial state, which is null.
T = new LinkedList[m];
T now is an array of the computed size m. You need to initialize the objects inside of the array.
T = new LinkedList[m];
for (int i = 0; i < m; i++) {
T[i] = new LinkedList<>();
}

How to print the maximum valued path in a 2D array in Java?

I guess you all know the "strawberry" problem that some give you in job interviews, where you need to calculate the path between 2 corners of a 2D array that you can only move up or to the right and you have the calculate the maximum valued path.
I have a perfectly working code that does it in Recursion, but it's complexity is to high.
i also solved the problem in the "for loop" solution that does it in O(n^2) complexity.
but in this solution i just couldn't figure out a way to print the route like i did in the recursion solution.
This is my code (it is quite long to read here so i guess you should copy,compile and run).
look at the results of the recursion solution, BTW - The path needs to be from the left bottom corner to the right upper corner
I want to print the route the same way in the better solution:
public class Alg
{
public static void main(String args[])
{
String[] route = new String[100];
int[][]array = {{4,-2,3,6}
,{9,10,-4,1}
,{-1,2,1,4}
,{0,3,7,-3}};
String[][] route2 = new String[array.length][array[0].length];
int max = recursionAlg(array,array.length-1,0,route);
int max2 = loopAlg(array,array.length-1,0,route2);
System.out.println("The max food in the recursion solution is: "+max);
System.out.println("and the route is: ");
printRouteArray(route);
System.out.println("The max food in the loop solution: "+max2);
System.out.println("The route is: ");
//SHOULD PRINT HERE THE ROUTE
}
public static int loopAlg(int [][] arr,int x, int y, String[][] route)
{
int n=0;
int[][]count = new int[arr.length][arr[0].length];
for(int i = x; i>=0 ; i--)
{
for(int j = 0; j<arr[0].length; j++)
{
if (i==x && j==0) {count[i][j]=arr[i][j];}
else if (i == x) { count[i][j]=count[i][j-1]+arr[i][j];}
else if (j == 0) { count[i][j]=count[i+1][j]+arr[i][j]; }
else{
if (count[i][j-1]>count[i+1][j]) {count[i][j]=count[i][j-1]+arr[i][j];}
else { count[i][j]= count[i+1][j]+arr[i][j];}
}
}
}
return count[0][arr[0].length-1];
}
public static int recursionAlg(int [][] arr, int x, int y,String[] route)
{
return recursionAlg(arr,0,x,y,arr[0].length-1,route,0);
}
public static int recursionAlg(int[][]arr,int count,int x, int y, int max_y, String[] route, int i)
{
if (x == 0 && y == max_y) {return count;}
else if (x == 0) {
route[i]="Right";
return recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1);
}
else if (y==max_y){
route[i]="Up";
return recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1);
}
else if (recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1)>recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1))
{
route[i]="Up";
return recursionAlg(arr,count+arr[x-1][y],x-1,y,max_y,route,i+1);
}
else
{
route[i]="Right";
return recursionAlg(arr,count+arr[x][y+1],x,y+1,max_y,route,i+1);
}
}
public static void printRouteArray(String[] arr)
{
int i=0;
while (i<arr.length && (arr[i]=="Up" || arr[i]=="Right"))
{
System.out.print(arr[i]+"-->");
i++;
}
System.out.println("End");
}
}
Hope you can help, thanks!
You need another 2-dimensional array inside loopAlg that memorizes which step to take to come to this next entry for every entry in your initial 2-dim array. See the following code and https://ideone.com/kM8BAZ for a demo:
public static void main(String args[])
{
String[] route = new String[100];
int[][]array = {{4,-2,3,6}
,{9,10,-4,1}
,{-1,2,1,4}
,{0,3,7,-3}};
String[] route2 = new String[100];
int max = recursionAlg(array,array.length-1,0,route);
int max2 = loopAlg(array,array.length-1,0,route2);
System.out.println("The max food in the recursion solution is: "+max);
System.out.println("and the route is: ");
printRouteArray(route);
System.out.println("The max food in the loop solution: "+max2);
System.out.println("The route is: ");
printRouteArray(route2);
}
public enum Dirs {START, FROM_LEFT, FROM_DOWN};
public static int loopAlg(int [][] arr,int x, int y, String[] route)
{
int n=0;
int[][]count = new int[arr.length][arr[0].length];
Dirs[][] directions = new Dirs[arr.length][arr[0].length];
List<String> path = new ArrayList<String>();
for(int i = x; i>=0 ; i--)
{
for(int j = 0; j<arr[0].length; j++)
{
if (i==x && j==0) {count[i][j]=arr[i][j]; directions[i][j] = Dirs.START;}
else if (i == x) { count[i][j]=count[i][j-1]+arr[i][j]; directions[i][j] = Dirs.FROM_LEFT;}
else if (j == 0) { count[i][j]=count[i+1][j]+arr[i][j]; directions[i][j] = Dirs.FROM_DOWN;}
else{
if (count[i][j-1]>count[i+1][j]) {count[i][j]=count[i][j-1]+arr[i][j];directions[i][j] = Dirs.FROM_LEFT;}
else { count[i][j]= count[i+1][j]+arr[i][j];directions[i][j] = Dirs.FROM_DOWN;}
}
}
}
int i=0, j=arr[0].length-1;
while(directions[i][j]!= Dirs.START) {
if(directions[i][j] == Dirs.FROM_LEFT) {
path.add("Right");
j--;
}
else {
path.add("Up");
i++;
}
}
Collections.reverse(path);
i=0;
for(String part:path) {
route[i] = part;
i++;
}
return count[0][arr[0].length-1];
}

Categories

Resources