Domanda

mi L'esecuzione di questo codice dà una serie di eccezioni limiti alla linea:

int sum = array[k]+array[l]; //sum of l and k

... Dovrebbe essere una soluzione semplice, ma non riesco a capire cosa potrebbe essere la causa di esso, dato che sto usando per array.length legato il ciclo. Chiunque può aiutare?

P.S. Per la cronaca, si suppone questo codice per cercare un array int per coppie di interi o interi singoli che uguale a int bersaglio. Funziona utilizzando unicamente le di println, ma sto cercando di mettere i numeri che si aggiungono al bersaglio in vettori.

public Vector<Vector<Integer>> subsetSum(int[] array, int target) {
    //creates vectors, adds inner vector to another vector
    outer = new Vector<Vector<Integer>>();
    inner = new Vector<Integer>();
    outer.add(inner);

    for (int k = 0; k <= array.length; k++) {
        for (int l = 0; l <= array.length; l++) {
            int sum = array[k]+array[l]; //sum of l and k
            int i = 0;

            if (sum == target) {

                inner.add(i, array[l]);
                inner.add(i, array[k]);

                i++;

                //prints combination
                System.out.println(array[l]+"+"+array[k]+"="+target);
            }
            if (k == target) {
                inner.add(i, array[k]);
                i++;
                //prints if int equals target
                System.out.println(k+"="+target);
            }
            if (l == target) {
                inner.add(i, array[l]);
                i++;
                //prints if int equals target
                System.out.println(l+"="+target);
            }
        }
    }
    //return combinations that add up to target in vector form
    System.out.println(outer);
    return outer;
}
È stato utile?

Soluzione

You need to use "<" instead of "<=" in your for loops.

Since the first position in the array is 0, the last position is length-1. What's happening is that when you reach the last iteration, the index is already out of the bounds of the array.

For instance, if you have an array:

array = [0,1,2,3] the last iteration would be array[4], the length of the array, which is out of the bounds.

Altri suggerimenti

the <= should be replaced with <

Change your loops to be:

for (int k = 0; k < array.length; k++)

and

for (int l = 0; l < array.length; l++)

Since arrays are 0-based, you want to go 1 less than the length.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top