我在 int 變數中有一個數字(稱之為“a”),我還有 12 個包含數字的 int 變數。我怎樣才能從其他變數中找到最接近“a”的數字?我應該使用 List 還是其他比較方法?
uj5u.com熱心網友回復:
代碼有點冗長,但我希望它可以幫助您理解如何在 dart 中撰寫邏輯。
如果您想優化此代碼,請查看在串列中找到最小值并將其與“與數字的最低差”邏輯結合的不同方法:)
注意:如果您希望在 Playground 中查看這樣的代碼片段,請使用Dart Pad!
import 'dart:math';
void main() {
List numbersList = [-10, 22]; // play around with it
List<int> differenceList = []; // helper list
int compareNumber = -11; // play around with it
// 1. Check if identical number is in numbersList:
bool checkForIdenticalNumber() {
if(numbersList.contains(compareNumber)) {
print("The number $compareNumber is identical to the compareNumber");
return true;
}
return false;
}
// 2. Define checking logic:
void checkDifference(int number) {
if (number > compareNumber) {
int difference = number - compareNumber;
differenceList.add(difference);
} else {
int difference = compareNumber - number;
differenceList.add(difference);
}
}
// 3. Use Check forEach element on numbersList:
void findNearestNumber() {
numbersList.forEach(
(number) => checkDifference(number)
);
}
// 4. Identify the solution:
void checkForSolution() {
int index = differenceList.indexWhere((e) => e == differenceList.reduce(min));
print("The closest number is: ${numbersList[index]}");
}
// 5. Only execute logic, if the number to compare is not inside the numbersList:
bool isIdentical = checkForIdenticalNumber();
if (!isIdentical) {
findNearestNumber();
// print(numbersList);
// print(differenceList);
checkForSolution();
}
}
uj5u.com熱心網友回復:
因此,您有一堆值和一個目標,并且想要在值串列中找到與目標最接近的值?
我想出了一個非常丑陋的方法來做到這一點,請看:
void main() {
int target = 6;
List<int> values = [
1,2,3,4,5,8,9,10,11,12,13 // we should get 5
];
// get the absolute value of the difference for each value
var difference = values.map((v) => (target-v)<0?(v-target):(target-v)).toList();
// get the smallest value (there's probably a better way to do it?)
int diffValue = values.fold(-1, (p, c) => p==-1?c:(p<c?p:c));
// find the index of said value
int index = difference.indexOf(diffValue);
// the result is the original value at that index
int result = values[index];
print(result);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374637.html
上一篇:GoogleSheet計算使用數學結果值而不是顯示值問題
下一篇:如何自然流暢地將物件移動到目標?
