Monday, April 10, 2023

Coding Challenge #47 Get Surrounding Indices (Accepts Floats)

 // assumes array is sorted least to greatest
function getNearIdxs(ary, val){ // returns object with 2 valid indices (assuming ary was not empty)
    if(ary.length < 2) return {min:0,max:0};
    var out = {min:0,max:0};
    for(var xint = 0,len=ary.length;xint < len;xint++){
        if(val < ary[xint]){
            out.max = xint;
            out.min = Math.max(0,xint-1);
            return out;
        }
    }
    return out;
}

var a = [1,2,3,4,5,6,7,8];
function test(val){
    x = getNearIdxs(a, val);
    console.log("Min: " + a[x.min] + ", max: " + a[x.max]);
}

test(2); // should return min 2, max 3
test(4); // 4, 5
test(4.5); // 4, 5
test(6.9); // 6, 7

No comments:

Post a Comment

Coding Challenge #54 C++ int to std::string (no stringstream or to_string())

Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...