Most efficient way to execute this - java

I'm currently working with the Bukkit API, but this has more to do with general Java, so I'm asking here. I have two HashMaps to store data into, and need to be able to compare the two.
public HashMap<Scoreboard, ArrayList<PlayerScore>> lastList = new HashMap<Scoreboard, ArrayList<PlayerScore>>();
public HashMap<Scoreboard, ArrayList<PlayerScore>> currentList = new HashMap<Scoreboard, ArrayList<PlayerScore>>();
I can iterate using while loops, and that works, but there's a problem with this because I then have to iterate through another ArrayList within the loop, and since there are two hashmaps, I end up doing 4 hashmaps in total... This is my current code:
public void remove(Scoreboard board) {
Iterator<Entry<Scoreboard, ArrayList<PlayerScore>>> lastIt = lastList.entrySet().iterator();
Iterator<Entry<Scoreboard, ArrayList<PlayerScore>>> currentIt = currentList.entrySet().iterator();
while (lastIt.hasNext()) {
System.out.println("dbg1");
Entry<Scoreboard, ArrayList<PlayerScore>> nextLast = lastIt.next();
if (nextLast.getKey().equals(board)) {
System.out.println("dbg2");
while (currentIt.hasNext()) {
Entry<Scoreboard, ArrayList<PlayerScore>> nextCurrent = currentIt.next();
ArrayList<PlayerScore> lastArray = nextLast.getValue();
ArrayList<PlayerScore> currentArray = nextCurrent.getValue();
Iterator<PlayerScore> lastArrayIt = lastArray.iterator();
Iterator<PlayerScore> currentArrayIt = currentArray.iterator();
while (lastArrayIt.hasNext()) {
System.out.println("dbg3");
PlayerScore nextCurrentArray = currentArrayIt.next();
while (currentArrayIt.hasNext()) {
System.out.println("dbg4");
if (!lastArray.contains(nextCurrentArray)) {
System.out.println("dbg5");
board.resetScores(nextCurrentArray.getString());
lastArrayIt.remove();
currentArrayIt.remove();
break;
}
}
break;
}
break;
}
}
break;
}
}
I know, it's very messy, but I don't really know what else to do for this. The while loops execute so much that the server console is filled with only "dbg4" because it's outputting so fast. This also crashes the server.
Anyone know a better way to do this?

You dont need to iterate over the hashmap. You could just do:
ArrayList<PlayerScore> lastArray = lastList.remove(board);
ArrayList<PlayerScore> currentArray = currentList.remove(board);

Related

Java ArrayList trying to check if object with this name exists

I'm having a bit of trouble in my head trying to solve this:
I'm working on a "rankList", an arrayList made of "Score". Score it's the object that has the following atributes: name,wins,loses,draws. My class Ranking has an ArrayList of Score objects. To create a new Score object I just use the name (and set the rest to 0 since it's new). However I'm trying to check if the player's name it's already in rankList I don't have to create new but sum a win or lose or draw.
I have been reading arround that I have to override equals then others say I have to override contains... It's getting a big mess in my head. My fastest solution would be to write an "for" that goes arround the arrayList and use the getName().equals("name"); however this is getting too messi in my code. I have checkPlayer (if the palyer is in the list):
public boolean checkPlayer(String playerName) {
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
return true;
}
}
return false;
}
then if I want to incrase the wins i have this :
public void incraseWins(String playerName) {
if (checkPlayer(playerName)) {
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
this.rankList.get(i).setWins(this.rankList.get(i).getWins() + 1);
break;
}
}
} else {
createPlayer(playerName);
//more for to get to the player i'm looking for...
for (int i = 0; i < this.rankList.size(); i++) {
if (this.rankList.get(i).getName().equals(playerName)) {
this.rankList.get(i).setWins(this.rankList.get(i).getWins() + 1);
break;
}
}
}
So i guess there is a better way to do this... :/
ArrayList is not the right data structure here. To check if an element exists in the array you are searching the entire arraylist. Which means it's O(N).
To keep an array list is sorted order and do a binary search on it would definitely be faster as suggested in the comments. But that wouldn't solve all your problems either because insert into the middle would be slow. Please see this Q&A: When to use LinkedList over ArrayList?
One suggestion is to use a Map. You would then be storing player name, player object pairs. This would give you very quick look ups. Worst case is O(log N) i believe.
It's also worth mentioning that you would probably need to make a permanent record of these scores eventually. If so an indexed RDBMS would give you much better performance and make your code a lot simpler.
Try using a hashtable with a key, it would be much more efficient!
e..Why not using map<>.
a binary search is good idea if you must use List,code like this
List<Method> a= new ArrayList<>();
//some method data add...
int index = Collections.binarySearch(a, m);
Method f = a.get(index);
and class method is impl of Comparable,then override compareTo() method
public class Method implements Comparable<Method>{
........
#Override
public int compareTo(Method o) {
return this.methodName.compareTo(o.getMethodName());
}
if you don't want use binsearch,CollectionUtils in commons can help you
CollectionUtils.find(a, new Predicate() {
#Override
public boolean evaluate(Object object) {
return ((Method)object).getMethodName().equals("aaa");
}
});
in fact CollectionUtils.find is also a 'for'
for (Iterator iter = collection.iterator(); iter.hasNext();) {
Object item = iter.next();
if (predicate.evaluate(item)) {
return item;
}
}

Smoother way to exit a void recursive Java function

So I wrote this function that behaves like Knuth's Algorithm X. Just for illustration - the function requires a large matrix of possible rows among which it tries to select the combination of the ones that make up for a legitimate solution.
The thing is, once we found the solution, since its void, the function doesn't return anything and instead just backtracks up (which consequently means it prints out sudoku for every level in the recursion depth).
Any suggestions on how to end the function the moment the solution is found? I am currently using System.exit(0) but that isn't nice since the program then ends the moment you find the solution (so anything you want to do afterwards is impossible - for example run the function on array of sudokus and solve each one).
The code is here:
public static void solve(ArrayList<int[]> solution, ArrayList<int[]> coverMatrix) {
if (Arrays.equals(solvedCase, workCase)) {
//this means we found the solution
drawSudoku(testOutput);
System.exit(0);
} else {
//find the column we didnt yet cover
int nextColToCover = findSMARTUnsatisfiedConstraint(coverMatrix, workCase);
//get all the rows that MIGHT solve this problem
ArrayList<int[]> rows = matchingRows(coverMatrix, nextColToCover);
//recusively try going down every one of them
for (int i = 0; i < rows.size(); i++) {
//we try this row as solution
solution.add(rows.get(i));
//we remove other rows that cover same columns (and create backups as well)
removeOtherRowsAndAdjustSolutionSet(coverMatrix);
if (isSolutionPossible(coverMatrix)) {
solve(solution, coverMatrix);
}
// here the backtracking occurs if algorithm can't proceed
// if we the solution exists, do not rebuild the data structure
if (!Arrays.equals(solvedCase, workCase)) {
restoreTheCoverMatrix(coverMatrix);
}
}
}
}
If I understand you correctly, you want to end recursion when you got the first solution. You can achieve this by having boolean return type for the method, and return true when you get first solution :.
public static boolean solve(ArrayList<int[]> solution, ArrayList<int[]> coverMatrix) {
if (Arrays.equals(solvedCase, workCase)) {
//this means we found the solution
drawSudoku(testOutput);
return true;
} else {
//find the column we didnt yet cover
int nextColToCover = findSMARTUnsatisfiedConstraint(coverMatrix, workCase);
//get all the rows that MIGHT solve this problem
ArrayList<int[]> rows = matchingRows(coverMatrix, nextColToCover);
//recusively try going down every one of them
for (int i = 0; i < rows.size(); i++) {
//we try this row as solution
solution.add(rows.get(i));
//we remove other rows that cover same columns (and create backups as well)
removeOtherRowsAndAdjustSolutionSet(coverMatrix);
if (isSolutionPossible(coverMatrix)) {
boolean result = solve(solution, coverMatrix);
if(result == true) return result;//else continue
}
// here the backtracking occurs if algorithm can't proceed
// if we the solution exists, do not rebuild the data structure
if (!Arrays.equals(solvedCase, workCase)) {
restoreTheCoverMatrix(coverMatrix);
}
}
return false;
}
}
You can use the AtomicReference Class with a Boolean:
public static void solve(ArrayList<int[]> solution, ArrayList<int[]> coverMatrix, AtomicReference<Boolean> test) {
if (Arrays.equals(solvedCase, workCase)) {
//this means we found the solution
drawSudoku(testOutput);
test.set(true);//System.exit(0);
}
solve(solution, coverMatrix, test);
if(!test.get())
{
// here the backtracking occurs if algorithm can't proceed
// if we the solution exists, do not rebuild the data structure
if (!Arrays.equals(solvedCase, workCase)) {
restoreTheCoverMatrix(coverMatrix);
}
}
You can call your method like this(just initialize the Boolean to false):
public static void main(String[] args)
{
AtomicReference<Boolean> test1 = new AtomicReference<Boolean>();
test1.set(false);
solve(***, ***, test1);
}
You could misuse the concept of exceptions for that, although I would not recommend it.
First define a custom exception class.
public class SuccessException extends Exception {}
Throw an instance on success.
if (Arrays.equals(solvedCase, workCase)) {
drawSudoku(testOutput);
throw new SuccessException();
}
Call the function initially in a try block.
try {
solve(solution, coverMatrix);
} catch(SuccessException e) {
/* Solution found! */
}

Set variable to reference another variable, Java

In Android Studio, I have two array lists with a custom object
ArrayList<MenuMaker> consessionlist = new ArrayList<MenuMaker>();
ArrayList<MenuMaker> entrylist = new ArrayList<MenuMaker>();
And have a few voids that depending on which mode we are in, it needs to use one ArrayList or the other:
private void createMenuButtons()
{
int FoodSize = consessionlist.size();
...
I realize I could do an if statement that if mode = 0 use consessionlist, else use entrylist, but is there a way to say
private void setmode(mode)
{
if (mode == 0){
menulist = consessionlist;
}
else
{
menulist = entrylist;
}
}
private void createMenuButtons()
{
int FoodSize = menulist.size();
...
*Pass-by-reference vs pass-by-value seem to kick my butt on the Oracle test.
I thought I would have to use an if statement overtime I need to choose or have to add some weird complexity, but thus far its actually working as I wanted it to.

How can I continue adding nodes in my linked list with a while loop?

I'm currently learning linked list and I have discovered the basics of coding it and I fully understand them. However, I have a certain amount of nodes preset, so the user would not be able to add more. How would one implement a while loop to keep cycling through and asking the user if they want to add another piece of data.
Here is the code that I already have so far:
public class List {
public int x;
public List ptr = null;
}
Above is the object class for List. List contains a data type of x and a pointer.
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
List front = new List();
front.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
List l1 = new List();
l1.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
List l2 = new List();
l2.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
front.ptr = l1;
l1.ptr = l2;
printNodes(front);
}
public static void printNodes(List p) {
while (p != null) {
System.out.print(p.x + " ");
p = p.ptr;
}
}
}
As you can see, I have 3 Nodes created, but you cannot add anymore. I'd like to have something along the lines of:
boolean goAgain = true;
while (goAgain) {
//create a new node
String again = JOptionPane.showInputDialog("Add another node?");
if (!again.equalsIgnoreCase("yes")) {
goAgain = false;
}
}
Thank you!
P.S - I am a sophomore in high school, please use vocabulary that I will be able to understand. I wouldn't say I'm a java noob, but I'm no expert either.
Well I'd clean up your while loop to include everything in one statement. But that's just because I'm lazy. ;)
while (!JOptionPane.showInputDialog("Add another node?").equalsIgnoreCase("yes"))
{
//make a new node
}
As for the code to make a new node I would suggest implementing your List class from the List interface that Java has. You can read about it here. If you're just starting out in Java though it might be a little hard to understand. As a comment on your existing code here:
List front = new List();
front.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
You're not exactly making a new node per-say, you're just creating new instances of your List class. In this case the object is labeled 'front' My suggestion is to read up more on how a List is meant to function. Here is a good example.

Having trouble understanding how to maintain state using classes

I'm new to using OOP, I typically just put all my code in a single class and use methods. But I want to maintain state information and think classes are the best fit but I'm having trouble wrapping my head around it.
Say I have a list of items and I want to stop when the total sum of all previous items in the list equals X(in this case 10 so it takes item 1 + 2, then 2+3.etc..until it hits the threshold 10), I can use a method to calculate it but it involves me doing the entire process all over again when all I really need to do is increment by the last item and then see if my data exceeds the threshold. Here's my code so far but I know its not good because although it works its really just using the class as an independent method and recalculating on every loop. My goal is to,using this structure, reduce loops if not necessary to check thresholds.
Any suggestions?
Code:
public class LearningClassesCounter {
public static void main(String[] args) {
int[] list = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] data_list = new int[list.length];
for (int current_location = 0; current_location<list.length;current_location++) {
//can only put commands in here. Nothing above.
Counter checker = new Counter(data_list);
System.out.println(checker.check_data(current_location));
for (int i =0; i<100; i++){
if (checker.check_data(current_location) == false) {
break;
}
data_list[current_location] = (list[current_location]+1); //this is just a random function, it could be any math function I just put it in here to show that some work is being done.
}
}
//its done now lets print the results
for (Integer item : data_list) {
System.out.println(item);
}
}
}
class Counter {
private int[] data_list;
private int total_so_far;
// create a new counter with the given parameters
public Counter(int[] data_list) {
this.data_list = data_list;
this.total_so_far = 0;
}
public boolean check_data(int current_location) {
// TODO Auto-generated method stub
int total_so_far = 0;
//System.out.println(total_so_far);
for (int item : data_list) {
total_so_far = item + total_so_far;
if (total_so_far >= 10) {
break;
}
}
if (total_so_far>=10) {
return false;
} else {
return true;
}
}
}
I don't need anyone to fix my code or anything(I want to do it myself, the code is just to give an idea of what I'm doing). I'm more interested in the flaw in my logic and maybe a way for me to better think about designing classes so I can apply them to my own situations better.
So the solution is that you do not update the data_list directly. Instead have a setter method in the Counter class that takes the index and value to update. It updates the value in the array and also updates a count value.
Something like this:
class Counter{
private final int[] list;
private count = 0;
private final maxCount = 10;
public Counter(int[] list){
this.list = list;
}
public boolean updateValueAndCheckPastMax(int index, int value){
list[index] = value;
count += value;
return count >= maxCount;
}
}
You are way over thinking this, and a counter class is not really necessary in this case.
I'm also interested as to why you'd be doing this line:
data_list[current_location] = (list[current_location]+1);
Do you want your data_list to be the same as list, but each value is incremented by 1?
If you are merely trying to return a sub-array of the values that are < 10, i would suggest just doing this in a for loop, and using an int as a counter.

Categories