Reputation: 53
How do I multiply two distinct lists in flutter. Like example below
List a = [2,3];
List b = [1,4];
List c = [3,5];
how do I obtain
List d = [6,60];
Upvotes: 0
Views: 2050
Reputation: 493
Generalized function to do this, where input
is a List of a List of integers, where the lengths of each list can be anything.
List<int> productList(List<List<int>> input) {
// handle some edge cases
if (input.isEmpty) {
return [];
} else if (input.length < 2) {
return input.first;
}
// sort the input so the largest list is first
input.sort(
(listA, listB) => listB.length.compareTo(listA.length),
);
var product = input.first;
for (var productIndex = 0; productIndex < product.length; productIndex++) {
// iterate over the rest of the list, keep multiplying if each list
// contains a number at productIndex
for (var inputIndex = 1; inputIndex < input.length; inputIndex++) {
var numList = input[inputIndex];
if (numList.length > productIndex) {
product[productIndex] *= numList[productIndex];
} else {
break;
}
}
}
return product;
}
In your example:
var a = [2,3];
var b = [1,4];
var c = [3,5];
var input = [a, b, c];
print(productList(input));
yields:
[6, 60]
Upvotes: 0
Reputation: 660
if you do not know:
You can do something like:
void main() {
//creating an empty growable list of list
List<List<int>> listOfLists = List.generate(0, (i) => []);
//your N List, maybe from api or something
List<int> a = [2, 3];
List<int> b = [1, 4];
List<int> c = [3, 5];
//adding all list to main one
listOfLists.addAll([a, b, c]);
//creating list which will have results
final results = [];
//recursive logic
listOfLists.asMap().forEach((listOfListsIndex, list) {
if (listOfListsIndex == 0) {
//adding first values as there's none to multiply
//you can remove the if statement if you init earlier
//final results = listOfLists[0];
//listOfLists.removeAt(0);
results.addAll(list);
} else {
list.asMap().forEach((listIndex, value) {
if (results.length > listIndex) {
//case when listOfLists[0] length is minor
//preventing error
//List<int> a = [2];
//List<int> b = [1, 4];
//List<int> c = [3, 5];
//List<int> d = [3, 5, 4, 6, 7];
results[listIndex] = results[listIndex] * value;
} else {
results.add(value);
}
});
}
});
print(results);
//[6, 60]
}
Upvotes: 0
Reputation: 316
void main() {
List a = [2, 3];
List b = [1, 4];
List c = [3, 5];
List d = [];
for (int i = 0; i < a.length; i++) {
d.add(a[i] * b[i] * c[i]);
}
print(d);
}
Upvotes: 1