如何在顫振中將兩個不同的串列相乘。像下面的例子
串列 a = [2,3];
串列 b = [1,4];
串列 c = [3,5];
我如何獲得
串列 d = [6,60];
uj5u.com熱心網友回復:
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);
}
uj5u.com熱心網友回復:
如果你不知道:
- 您收到的串列數量
- 串列中的元素數量
您可以執行以下操作:
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]
}
uj5u.com熱心網友回復:
執行此操作的通用函式,其中input是整數串列的串列,其中每個串列的長度可以是任何值。
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;
}
在您的示例中:
var a = [2,3];
var b = [1,4];
var c = [3,5];
var input = [a, b, c];
print(productList(input));
產量:
[6, 60]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407423.html
標籤:
