I’m aware that there is already a thread on this topic, however I’m just wondering why this solution isn’t working for HackerRank’s “Compare the Triplets” problem? I’m only getting an output of 1 when it should be 1 1.
The problem states that if a0 > b0, a1 > b1, or a2 > b2 (and vice versa), the result should print separate spaced integers of 1 for any comparison that is not equal.
https://www.hackerrank.com/challenges/compare-the-triplets/problem
function solve(a0, a1, a2, b0, b1, b2) { var solution = [] if (a0 > b0 || a1 > b1 || a2 > b2) { solution += 1; } else if (a0 < b0 || a1 < b1 || a2 < b2 ) { solution += 1; } return solution.split(''); }
—- UPDATE —-
The code above only worked for the first test case and not the rest. The code below, although clunky, worked for all test cases.
function solve(a0, a1, a2, b0, b1, b2) { var s = [0, 0]; if (a0 > b0) {s[0] += 1;} if (a1 > b1) {s[0] += 1;} if (a2 > b2) {s[0] += 1;} if (a0 < b0) {s[1] += 1;} if (a1 < b1) {s[1] += 1;} if (a2 < b2) {s[1] += 1;} return s; }
Advertisement
Answer
There can be many different solutions to this problem, but the issue with the mentioned solution is that there should not be “else” statement because in that case the second comparison never happens. Corrected:
function solve(a0, a1, a2, b0, b1, b2) { var solution = [] if (a0 > b0 || a1 > b1 || a2 > b2) { solution += 1; } if (a0 < b0 || a1 < b1 || a2 < b2 ) { solution += 1; } return solution.split(''); }