[英]Flutter : Compare int with list<Map<String,int>>
如果有人能夠提供幫助,謝謝。
這是我要與之比較的列表
[{"quote":3,"money":3000}, {"quote":6,"money":7000}, {"quote":8,"money":8000}]
在上一頁中,用戶輸入購買金額,例如 3500 美元。 如果數量超過
3000 then the user needs to present 3 quotes
7000 then the user needs to present 6 quotes
8000 then the user needs to present 8 quotes
我正在努力尋找一種解決方案來比較金額與列表值以獲得相應的 Map 值
如果有人有任何建議。 將不勝感激
謝謝
我將數據更改為更方便的結構
下面的所有代碼都將基於這個結構
final data = [{"quote":3,"money":3000}, {"quote":6,"money":7000}, {"quote":8,"money":8000},];
下一步是對數據進行排序,
如果數據已經像您提供的示例一樣排序,則可以跳過此步驟
我要使用合並排序對數據進行排序
我更改了Tomic-Riedel 的 mergeSort 實現以滿足我們的需要。
List<Map<String, int>> mergeSort(List<Map<String, int>> array) {
// Stop recursion if array contains only one element
if(array.length <= 1) {
return array;
}
// split in the middle of the array
int splitIndex = array.length ~/ 2;
// recursively call merge sort on left and right array
List<Map<String, int>> leftArray = mergeSort(array.sublist(0, splitIndex));
List<Map<String, int>> rightArray = mergeSort(array.sublist(splitIndex));
return merge(leftArray, rightArray);
}
List<Map<String, int>> merge(leftArray, rightArray) {
List<Map<String, int>> result = [];
int? i = 0;
int? j = 0;
// Search for the smallest eleent in left and right arrays
// array and insert it into result
// After the loop only one array has remaining elements
while(i! < leftArray.length && j! < rightArray.length) {
if(leftArray[i]['money'] <= rightArray[j]['money']) {
result.add(leftArray[i]);
i++;
} else {
result.add(rightArray[j]);
j++;
}
}
// Insert remaining elements of left array into result
// as long as there are remaining elements
while(i! < leftArray.length) {
result.add(leftArray[i]);
i++;
}
// Insert remaining elements of right array into result
// as long as there are remaining elements
while(j! < rightArray.length) {
result.add(rightArray[j]);
j++;
}
return result;
}
然后我們用它來獲取采購清單代碼:
final amount = 3500;
final sortedData = mergeSort(data);
// at this point out data is sorted by 'money'
List<Map<String, int>> canBePurchased = [];
for (Map<String, int> item in sortedData) {
if (item['money']! <= amount) {
canBePurchased.add(item);
}
}
print(canBePurchased);
// to get only the last item
if (canBePurchased.isNotEmpty) {
print(canBePurchased.last);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.