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];
}
seems to pass in hackerrank if a and b treated as arrays:
function compareTriplets(a, b) {
let score = [0,0]
for (let i = 0; i < a.length; i++)
a[i] > b[i] ? score[0]++ : a[i] < b[i] ? score[1]++ : ""
return score
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With