How do I find the closest array element to an arbitrary (non-member) number?

前端 未结 5 1462
闹比i
闹比i 2021-01-18 13:48

Seemingly similar questions: \"Finding closest number in an array\" (in Java) and \"find nearest match to array of doubles\" (actually a geography problem).

5条回答
  •  离开以前
    2021-01-18 14:33

    List results;
    int target = 0;
    int nearestValue = 0;
    if (results.Any(ab => ab == target)) {
        nearestValue= results.FirstOrDefault(i => i == target);
    } else {
        int greaterThanTarget = 0;
        int lessThanTarget = 0;
        if (results.Any(ab => ab > target) {
            greaterThanTarget = results.Where(i => i > target).Min();
        }
    
        if (results.Any(ab => ab < target)) {
            lessThanTarget = results.Where(i => i < target).Max();
        }
    
        if (lessThanTarget == 0 ) {
            nearestValue= greaterThanTarget;
        } else if (greaterThanTarget == 0) {
            nearestValue = lessThanTarget;
        } else {
            if (target - lessThanTarget < greaterThanTarget - target) {
                nearestValue = lessThanTarget;
            } else {
                nearestValue = greaterThanTarget;
            }
        }
    }
    

提交回复
热议问题