Skip to content

Instantly share code, notes, and snippets.

@f1lander
Last active October 10, 2019 21:53
Show Gist options
  • Save f1lander/74a827eb2abc0c8e9fedde6c2aabe767 to your computer and use it in GitHub Desktop.
Save f1lander/74a827eb2abc0c8e9fedde6c2aabe767 to your computer and use it in GitHub Desktop.
Find count of pairs of HackerRank code challenge
const ar = [10, 20, 20, 10, 10, 30, 50, 10, 20];
const getPairs = (n, ar) => {
let pairs = 0, i = 0;
ar.sort((a, b) => a - b);
while (i < n) {
const count = ar.filter(item => item === ar[i]).length;
if (count >= 2) {
i = i + count;
const divide = (count / 2);
pairs += Math.floor(divide);
} else {
i += 1;
}
}
return pairs;
}
const getPairsSecond = (n, ar) => {
let pairs = 0;
let foundedNum = [];
for (let i = 0; i < n; i++) {
let count = 0;
for (let j = 0; j < n; j++) {
if (ar[i] == ar[j] && foundedNum.indexOf(ar[j]) == -1) {
count++;
}
}
if (count >= 2){
const divide = (count / 2);
pairs += Math.floor(divide);
foundedNum.push(ar[i]);
}
}
return pairs;
}
console.time("FIRST");
console.log(getPairs(ar.length, ar));
console.timeEnd("FIRST");
console.time("SECOND");
console.log(getPairsSecond(ar.length, ar));
console.timeEnd("SECOND");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment