Je suis assez nouveau à Java et j'essaie d'écrire un algorithme qui renvoie la somme des indices de paires qui sont égales au total.IndexOutOfBoundsException lors de l'appel de la fonction récursive
Je reçois une erreur lorsque j'appuie sur ma fonction récursive à propos des limites. Les limites me semblent bien, je ne fais que passer dans l'arrayliste mise à jour, donc je ne sais pas d'où ça vient.
Erreur
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at com.example.helloworld.HelloWorld.getMatches(HelloWorld.java:36)
at com.example.helloworld.HelloWorld.getMatches(HelloWorld.java:41)
algorithme
public class HelloWorld {
ArrayList<Integer> matches = new ArrayList<>();
ArrayList<Integer> temp = new ArrayList<>();
public static void main(String[] args) {
ArrayList<Integer> param = new ArrayList<>(Arrays.asList(0, 0, 0, 0, 1, 1));
int res = new HelloWorld().pairwise(param, 1);
System.out.println(res);
}
private int pairwise(ArrayList<Integer> arr, Integer total) {
for (Integer item: arr) {
this.temp.add(item);
}
getMatches(this.temp, total);
return getIndices(this.matches, arr);
}
private void getMatches(ArrayList<Integer> arr, Integer total) {
boolean noMatch = true;
for (int i=1; i<arr.size(); i++) {
if (arr.get(0) + arr.get(i) == total) {
//add to matches
this.matches.add(arr.get(0));
this.matches.add(arr.get(i));
//remove from temp
this.temp.remove(0);
this.temp.remove(arr.get(i));
noMatch = false;
if (this.temp.size() > 1) {
//ERROR HERE
getMatches(this.temp, total);
}
}
}
if (noMatch) {
this.temp.remove(0); //remove first one
if (this.temp.size() > 1) {
getMatches(this.temp, total);
}
}
}
private int getIndices(ArrayList<Integer> matches, ArrayList<Integer> array) {
int count = 0;
for (Integer item: matches) {
int index = array.indexOf(item);
count += index;
array.set(index, -3000);
}
return count;
}
}
Toute aide est très appréciée.
Cest il! J'ai même réalisé cela avant et je regardais les «itérateurs de liste» dans une approche différente. Merci, le temps d'une pause ... – andrewgi