DEV Community


My ridiculously unreadable but concise solution to the Compare Tuples challenge on HackerRank

Lukas Müller
・2 min read

Here's the challenge:

Here's the definition of the challenge:

Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty.

The rating for Alice's challenge is the triplet a = (a[0], a[1], a[2]), and the rating for Bob's challenge is the triplet b = (b[0], b[1], b[2]).

The task is to find their comparison points by comparing a[0] with b[0], a[1] with b[1], and a[2] with b[2].

If a[i] > b[i], then Alice is awarded 1 point.
If a[i] < b[i], then Bob is awarded 1 point.
If a[i] = b[i], then neither person receives a point.
Enter fullscreen mode Exit fullscreen mode

Comparison points is the total points a person earned.

Given a and b, determine their respective comparison points.

My initial approach was a simple if/else loop, filling the 2 positions of a previously defined array, and then returning that array.

Something along the lines of this:

function compareTriplets(a, b) {
  let counterA = 0,
      counterB = 0;
  for (let i=0; i < a.length; i++){
      if (a[i] > b[i]) {
      } else if (a[i] < b[i]) {

  return [counterA, counterB];
Enter fullscreen mode Exit fullscreen mode

This is obviously a fine enough solution and what I would probably write in a real project.

But I thought: "I bet can write this in one line". And so I did:

const compareTriplets = (a, b) => [[a, b], [b, a]].map((c, i) => c[0].reduce((acc, _curr, i) => acc + (c[0][i] > c[1][i]), 0));
Enter fullscreen mode Exit fullscreen mode

And it works! And I'm sure there's ways to make it even more concise. And there's definitely a way to extend it to accept a hypothetically infinite (within the limits of JS) amount of arrays.

As said before, I would never write something like this for a real project. The reason is that it's completely unreadable. It would probably take me 10 minutes to understand the code I produced if I came across it in a legacy project or I wouldn't even get that far because I would think to myself "which self-important twat wrote this?" and close my editor out of frustration.

Anyway, it was a fun mind challenge and I think I might understand .map() and .reduce() a bit better now :)

Discussion (1)

crosseye profile image
Scott Sauyet

Interesting, as my solution to that was a few characters shorter, but I never thought about it as code-golfed. It's just how I think.

(a, b) => a.reduce(([x, y], a, i) => a > b[i] ? [x + 1, y] : a < b[i] ? [x, y + 1] : [x, y], [0, 0])
Enter fullscreen mode Exit fullscreen mode