如果有人能夠提供幫助,謝謝。
這是我要比較的串列
[{"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 值
如果有人有任何建議。將不勝感激
謝謝
uj5u.com熱心網友回復:
我將資料更改為更方便的結構
下面的所有代碼都將基于這個結構
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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488741.html
