Skip to content

Instantly share code, notes, and snippets.

@mkamranhamid
Created June 5, 2020 13:14
Show Gist options
  • Save mkamranhamid/407adf31f781b3ac133b4b5c8c1ddaa9 to your computer and use it in GitHub Desktop.
Save mkamranhamid/407adf31f781b3ac133b4b5c8c1ddaa9 to your computer and use it in GitHub Desktop.
Find value that occurs in odd number of elements.
// codility test prep questions
// For example, in array A such that:
// A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9
// the elements at indexes 0, 2 and 4 have value 9,
// the elements at indexes 1 and 3 have value 3,
// the element at index 5 has value 7 and is unpaired.
function findPairs(arr){
var hash = {}
arr.map((num)=>{
if(!hash[num]){
hash[num] = 1
} else {
hash[num] += 1
}
})
return hash;
}
function findPairFrequency(hash, freq){
return Object.keys(hash).filter(key=> hash[key]==freq)[0]
}
var randomArray = [9,3,9,3,9,7]
var pairingHash = findPairs(randomArray)
var noPair = findPairFrequency(pairingHash, 1)
console.log(noPair)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment