-2

var a, b, c, d, e; // These vars are not required

Logic:

a <b <c <d <e => True

  • If b = null, then a <c <d <e => True
  • If all = null, => True

How to validate the solution for a concise and accurate way? Here I am just example 5 variables but actually more than 20 variables.

Tính Ngô Quang
  • 4,400
  • 1
  • 33
  • 33

1 Answers1

1

You can use a sliding window over an array with a size of two in order to compare each pair of items. The idea is simple given an array [a, b, c, d] you would compare each pair of items

1. [a, b, c, d]
   |____|
    a < b

2. [a, b, c, d]
      |____|
       b < c

3. [a, b, c, d]
         |____| 
          c < d

Here is how this technique can be implemented in JavaScript. I'd be re-using the part of my answer from that question that uses generators.

All that is left is to implement the comparison. This can be easily generalised for any sort of comparison - less than, greater than, equality, etc, if we accept a function that takes two parameters and compares them. This can then accept any number of parameters to check. Here is how can this work:

function* windowGenerator(inputArray, size) { 
  for(let index = 0; index+size <= inputArray.length; index++) {
    yield inputArray.slice(index, index+size);
  }
}

function toWindows(inputArray, size) {
  //compute the entire sequence of windows into an array
  return Array.from(windowGenerator(inputArray, size))
}

function compareAll(biOperator, ...args) {
  return toWindows(args, 2)
    .every(([a, b]) => biOperator(a, b));
}

//some sample operators
const lt = (a, b) => a < b;
const gt = (a, b) => a > b;
const eq = (a, b) => a === b;

console.log(
  "1 < 3 < 2 =", 
  compareAll(lt, 1, 3, 2)
);
console.log(
  "1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 =", 
  compareAll(lt, 1, 2, 3, 4, 5, 6, 7, 8, 9)
);

console.log(
  "1 > 3 > 2 =",
  compareAll(gt, 1, 3, 2)
);
console.log(
  "9 > 8 > 7 > 6 > 5 > 4 > 3 > 2 > 1 =",
  compareAll(gt, 9, 8, 7, 6, 5, 4, 3, 2, 1)
);

We can also remove the need to materialise the entire set of sliding windows before doing the comparison by directly working with the generated sequence:

function* windowGenerator(inputArray, size) { 
  for(let index = 0; index+size <= inputArray.length; index++) {
    yield inputArray.slice(index, index+size);
  }
}

function compareAll(biOperator, ...args) {
  for (const [a, b] of (windowGenerator(args, 2))) {
    if (!biOperator(a, b)) {
      return false
    }
  }
  
  return true;
}

//some sample operators
const lt = (a, b) => a < b;
const gt = (a, b) => a > b;
const eq = (a, b) => a === b;

console.log(
  "1 < 3 < 2 =", 
  compareAll(lt, 1, 3, 2)
);
console.log(
  "1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 =", 
  compareAll(lt, 1, 2, 3, 4, 5, 6, 7, 8, 9)
);

console.log(
  "1 > 3 > 2 =",
  compareAll(gt, 1, 3, 2)
);
console.log(
  "9 > 8 > 7 > 6 > 5 > 4 > 3 > 2 > 1 =",
  compareAll(gt, 9, 8, 7, 6, 5, 4, 3, 2, 1)
);
VLAZ
  • 26,331
  • 9
  • 49
  • 67