Created
January 8, 2015 22:11
-
-
Save michalmikolajczyk/945460ea2d3bd695cb1c to your computer and use it in GitHub Desktop.
some codility identical indices test
This file contains hidden or 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
var A = []; | |
A[0] = 3; | |
A[1] = 5; | |
A[2] = 6; | |
A[3] = 3; | |
A[4] = 3; | |
A[5] = 5; | |
function identicalIndices(someArray) { | |
var count = 0; | |
someArray.forEach(function (item, index) { | |
var restOfArray = someArray.slice(index + 1, someArray.length); | |
restOfArray.forEach(function (pairCandidate) { | |
if (pairCandidate === item) { | |
count++; | |
} | |
}); | |
}); | |
return count; | |
} | |
var b = identicalIndices(A); | |
console.log(b); | |
} | |
// Another way to do this is to create a helper object | |
// which stores the indices like this | |
// var helper = {}; | |
// var count = 0 | |
// A.forEach(function (item, index) { | |
// if (helper[item]) { | |
// helper[item].push(index); | |
// } else { | |
// helper[item] = [index]; | |
// } | |
// }); | |
// for (var key in helper) { | |
// if (helper.hasOwnProperty((key… | |
// if (helperObject[item]) { | |
// helperObject[item]++; | |
// if (helperObject[item] % 2 === 0) { | |
// count++; | |
// } | |
// } else { | |
// helperObject[item] = 1; | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment