Thursday, February 23, 2023

Coding Challenge #9

Check if One Array Can Be Nested In The Other (here)

Given two arrays, check first can be nested in the second.

Array 1 can be nested if:

  1. Array 1's min value > Array 2's min value
  2. Array 2's max value < Array 2's max value

Using yesterday's challenge to quickly get the min/max value of an array to get a head start...

 function getExtremes(ary){
    var x = {min:null,max:null}; // return null if ary length is 0
    if(ary.length < 1) return x;
    
    x.min = ary[0]; // default to first index of array
    x.max = ary[0];
    for(var xint = 1, len = ary.length;xint < len;xint++){
        x.min = Math.min(x.min, ary[xint]);
        x.max = Math.max(x.max, ary[xint]);
    }
    return x;
}

function test(){
    var ary = [];
    var len = Math.round(Math.random() * 3) + 2; // [2,5] inclusive
    for(var xint = 0;xint < len;xint++)
        ary.push(Math.round(Math.random() * 100)); // [0,100] inclusive
    
    var polarz = getExtremes(ary);
    
    var ary2 = [];
    var len2 = Math.round(Math.random() * 3) + 2; // [2,5] inclusive
    for(var xint = 0;xint < len2;xint++)
        ary2.push(Math.round(Math.random() * 100)); // [0,100] inclusive
    
    var polarz2 = getExtremes(ary2);
    
    if(polarz.min > polarz2.min && polarz.max < polarz2.max){
        console.log("Array A: " + ary.toString() + " has min: " + polarz.min + ", max: " + polarz.max + ", and Array B: " + ary2.toString() + " has min: " + polarz2.min + ", max: " + polarz2.max + ". Can it be nested? YES.");
    }else{
        console.log("Array A: " + ary.toString() + " has min: " + polarz.min + ", max: " + polarz.max + ", and Array B: " + ary2.toString() + " has min: " + polarz2.min + ", max: " + polarz2.max + ". Can it be nested? NO.");
    }
}

test();
test();
test();
test();
test();

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 ...