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:
- Array 1's min value > Array 2's min value
- 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