Compare the Triplets - JavaScript?

The "Compare the Triplets" problem is a popular algorithmic challenge where you compare two arrays of three integers each and count how many comparisons each array wins. Alice and Bob each have three scores, and we need to determine who wins more individual comparisons.

Problem Statement

Given two triplets (arrays of 3 elements each), compare corresponding elements and award points: 1 point to Alice if her element is greater, 1 point to Bob if his element is greater, 0 points for ties. Return an array with [Alice's score, Bob's score].

Example Input

Alice: [5, 6, 7]
Bob: [3, 6, 10]

Solution

Here's the corrected solution that properly compares triplets:

function compareTriplets(a, b) {
    let aliceScore = 0;
    let bobScore = 0;
    
    for (let i = 0; i  b[i]) {
            aliceScore++;
        } else if (a[i] 

Alice's scores: [ 5, 6, 7 ]
Bob's scores: [ 3, 6, 10 ]
Result: [ 1, 1 ]

How It Works

The algorithm compares each corresponding pair:

// Step by step comparison
let alice = [5, 6, 7];
let bob = [3, 6, 10];

console.log("Comparison 1: 5 vs 3 ?", 5 > 3 ? "Alice wins" : "Bob wins");
console.log("Comparison 2: 6 vs 6 ?", 6 === 6 ? "Tie" : "Someone wins");
console.log("Comparison 3: 7 vs 10 ?", 7 > 10 ? "Alice wins" : "Bob wins");
Comparison 1: 5 vs 3 ? Alice wins
Comparison 2: 6 vs 6 ? Tie
Comparison 3: 7 vs 10 ? Bob wins

Alternative Implementation

Using array methods for a more functional approach:

function compareTripletsFunctional(a, b) {
    const aliceWins = a.filter((val, i) => val > b[i]).length;
    const bobWins = b.filter((val, i) => val > a[i]).length;
    return [aliceWins, bobWins];
}

console.log(compareTripletsFunctional([17, 28, 30], [99, 16, 8]));
[ 2, 1 ]

Conclusion

The Compare Triplets problem demonstrates basic array iteration and conditional logic. The key is to compare corresponding elements and count wins for each participant, ignoring ties.

Updated on: 2026-03-15T23:19:00+05:30

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements