Last active
October 10, 2019 21:53
-
-
Save f1lander/74a827eb2abc0c8e9fedde6c2aabe767 to your computer and use it in GitHub Desktop.
Find count of pairs of HackerRank code challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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