Home > Back-end >  Using the ternary operator multiple times
Using the ternary operator multiple times

Time:10-06

I am currently doing some coding challenges and encountered one wich i wanted to solve with using the ternary operator. I know that there is some previous answers but no one (that i found) was using the ternary operator. Do you guys know what did i miss here ?

The point here is to add 1 to a if a1>b1, 1 to b if b1 > a1 etc ... One other point is, if a1 = b1, no one gets a point
Link to the problem : https://www.hackerrank.com/challenges/compare-the-triplets/problem

function compareTriplets(a0, a1, a2, b0, b1, b2) {
  let dataCompilator = [0, 0]
  a0 > b0 ? dataCompilator[0]  = 1 : dataCompilator[1]  = 1;
  a1 > b1 ? dataCompilator[0]  = 1 : dataCompilator[1]  = 1;
  a2 > b2 ? dataCompilator[0]  = 1 : dataCompilator[1]  = 1;
  return dataCompilator;
}
console.log(compareTriplets(5, 6, 7, 3, 6, 10))

My output :
0 3

What the outputs SHOULD have been :
1 1

CodePudding user response:

The problem is that you have three cases:

  • a > b: dataCompilator[0] should be incremented
  • a == b: Nothing happens
  • a < b: dataCompilator[1] should be incremented

And a ternary condition only addresses two cases. In your code it does the following:

  • a > b: If true, dataCompilator[0] is incremented
  • else: dataCompilator[1] is incremented

So you miss the equality case. To solve it only with ternaries, you could do the following (be aware that's only for the exercise, I would advocate against it in real code, as it makes the code difficult to read):

a > b ? dataCompilator[0]  = 1 : (a < b ? dataCompilator[1]  = 1 : null)

CodePudding user response:

The problem with your code is that, there are 3 states of comparison.

  • Greater Than
  • Less Than
  • Equal

You are not checking for Equal, so for that scenario, by default you will go to else section. Hence output is [1, 2]

What you need is to add extra check for non-equal

function compareTriplets(a0, a1, a2, b0, b1, b2) {
  let dataCompilator = [0, 0]
  a0 > b0 ? dataCompilator[0]  = 1 :  a0 < b0 ? dataCompilator[1]  = 1 : 0;
  a1 > b1 ? dataCompilator[0]  = 1 :  a1 < b1 ? dataCompilator[1]  = 1 : 0;
  a2 > b2 ? dataCompilator[0]  = 1 :  a2 < b2 ? dataCompilator[1]  = 1 : 0;
  return dataCompilator;
}
console.log(compareTriplets(5, 6, 7, 3, 6, 10))

Note: Nested ternary operators are not good for readability and are sometimes considered bad practice. Its always better to use if..else ladder in such scenario

You can achieve same with loops to make things simple

function compareTriplets(...args) {
  let alice = 0
  let bob = 0
  for (let i = 0; i < args.length / 2; i  ) {
    if (args[i] > args[args.length - i - 1])
      alice  
    else if (args[i] < args[args.length - i - 1])
      bob  
  }
  return [alice, bob];
}

console.log(compareTriplets(5, 6, 7, 3, 6, 10))

  • Related