如何找到颤动变量之间最近的数字?

How to find the nearest number between flutter variables?

我在一个 int 变量中有一个数字(称之为“a”),我还有另外 12 个包含一个数字的 int 变量。 我怎样才能从其他变量中找到最接近“a”的数字? 我应该使用列表还是其他比较方法?

所以你有一堆值和一个目标,想在值列表中找到最接近目标的值?

我想出了一个非常丑陋的方法,请看一看:

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

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

如果您想优化此代码,请查看 different ways 您可以在列表中找到最小值并将其与“数字的最小差异”-逻辑相结合:)

注意:如果您想要一个 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();
 }
}