7

COMPARE TRIPLETS HACKERRANK SOLUTION

 2 years ago
source link: https://erisanal.com/compare-triplets-hackerrank-solution/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

COMPARE TRIPLETS HACKERRANK SOLUTION

PROBLEM STATEMENT: 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 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.
Comparison points is the total points a person earned.
Given a and b, determine their respective comparison points.

SOLUTION:

step1: we declare our function, let’s call it compareTriplets
step2: declare counters to track the number of times elements inside each array is greater than, less than, or equal to each other
step3: declare arrays to collect the values of the counters declared in step2
step4: declare an iterator variable that gets the keys of the first Array(a)
step5: declare a for loop statement, this loop uses the iterator to compare values in the two arrays, set the counters to either increase or decrease, and finally push the counters to their arrays (finalArray1, finalArray2)
step6: we collect the last values from finalArray1 and finalArray2 respectively and pass them into an output array
step7: we run the function against all Hackerrank test cases

The code:
function compareTriplets(a,b) {
let counterA = 0;
let counterB = 0;
let finalArray1 = [];
let finalArray2 = [];
const iterator = a.keys();
for (const key of iterator) {
if (a[key] > b[key]) {
counterA++;
counterB += 0;
finalArray1.push(counterA);
finalArray2.push(counterB);
}
if (a[key] < b[key]) {
counterB++;
counterA += 0;
finalArray2.push(counterB);
finalArray1.push(counterA);
}
if (a[key] == b[key]) {
counterA += 0;
counterB += 0;
finalArray2.push(counterB);
finalArray1.push(counterA);
}
}

const res1 = finalArray1[finalArray1.length – 1];
const res2 = finalArray2[finalArray2.length – 1];
const output = [res1, res2];
console.log(output);
return output;
}
compareTriplets([1,2,3], [3,2,1])
compareTriplets([5,6,7], [3,6,10])
compareTriplets([17,18,30], [99,16,8])
compareTriplets([20,20,30], [20,20,50])
compareTriplets([6,8,12], [7,9,15])
compareTriplets([10,15,20], [5,6,7])


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK