Sto cercando di implementare una semplice moltiplicazione di matrice in Java, dove sto memorizzando le matrici in ArrayList bidimensionale. Sembrerebbe che l'errore sia causato dall'impostazione della matrice Result
, all'interno del ciclo annidato, ma non capisco perché.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
public class Test {
public static void main(String args[]) {
int n = 2;
ArrayList<ArrayList<Integer>> Result = new ArrayList<ArrayList<Integer>>(Collections.nCopies(n, new ArrayList<Integer>(Collections.nCopies(n, 0))));
ArrayList<ArrayList<Integer>> A = new ArrayList<ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> B = new ArrayList<ArrayList<Integer>>();
A.add(new ArrayList<Integer>(Arrays.asList(1, 6)));
A.add(new ArrayList<Integer>(Arrays.asList(2, 2)));
B.add(new ArrayList<Integer>(Arrays.asList(0, 9)));
B.add(new ArrayList<Integer>(Arrays.asList(5, 6)));
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
for (int k = 0; k < n; k++){
int val = A.get(i).get(k) * B.get(k).get(j);
Result.get(i).set(j, Result.get(i).get(j) + val);
}
}
}
}
}
Il codice produce il risultato A * B = [[40, 75], [40, 75]]
quando in realtà dovrebbe essere A * B = [[30, 45], [10, 30]]
.
risposte:
2 per risposta № 1Il Result
è inizializzato erroneamente.
ArrayList<ArrayList<Integer>> Result = new ArrayList<ArrayList<Integer>>(
Collections.nCopies(n,
new ArrayList<Integer>(Collections.nCopies(n, 0))));
Questo crea una matrice in cui due righe (o colonne, a seconda di come la si guarda) sono in effetti la stessa riga (colonna), con riferimento due volte.
Puoi iniziare Result
come quello:
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
result.add(new ArrayList<>(Collections.nCopies(n, 0)));
}