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;
}
Ghost of Christmas Future Update (11/8/23)
I keep getting notifications about this post so I thought I'd go back and solve it again as an employed software engineer. Asking questions on S/O was scary when I first started because I had no idea what I was doing. Fast forward nearly six years and I still feel like I have no idea what I'm doing half of the time, but now I code for a living and love it. Here's how I'd solve it now.
function compareTriplets(a, b) {
let aliceTotal = 0;
let bobTotal = 0;
a.map((aliceScore, i) => {
aliceScore > b[i] ? alice += 1 :
aliceScore < b[i] ? bob += 1 :
0;
});
return [aliceTotal, bobTotal];
}
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('');
}