如何找到颤振变量之间最接近的数字



我在一个int变量中有一个数字(称之为"a"(,我有12个其他int变量,其中包含一个数字。我怎么能找到最接近";a";来自其他变量?我应该使用列表还是其他比较方法?

代码有点冗长,但我希望它能帮助您理解如何在dart中编写逻辑。

如果你想优化这个代码,可以看看在列表中找到最小值的不同方法,并将其与";一个数字的最小差值"-逻辑:(

注意:如果你想在操场上查看这样的代码片段,请使用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();
}
}

所以您有一堆值和一个目标,并希望在值列表中找到与目标最接近的值?

我想出了一个非常丑陋的方法来做到这一点,请看一看:

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);
}

相关内容

  • 没有找到相关文章

最新更新