Created
August 24, 2012 15:00
-
-
Save riovv/3451709 to your computer and use it in GitHub Desktop.
Unreadable Array inversion counter!
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
/* | |
* Count inversions in an array using JavaScript | |
* Friday fun writing algorithms as UNREADABLE CODE WITH FEW LINEZ FTW :D::D | |
*/ | |
var array_inversions = function (A) { | |
var I = 0, | |
R = function (A) { return (A.length < 2) ? A : M(R(A.splice(0, A.length/2)), R(A)) }, | |
M = function (B, C) { | |
var D = [] | |
while (B.length && C.length) { | |
if (B[0] <= C[0]) D.push(B.shift()) | |
else { | |
D.push(C.shift()) | |
I += B.length | |
} | |
} | |
return B.length ? D.concat(B) : D.concat(C) | |
} | |
return R(A) ? I : null | |
} | |
console.log(array_inversions([1,3,5,2,4,6])) // 3 | |
console.log(array_inversions([1,5,3,2,4,6])) // 4 | |
console.log(array_inversions([6,5,4,3,2,1])) // 15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment