Created
September 18, 2015 09:02
-
-
Save jeanlescure/5ccad7ad0b50ef7561aa to your computer and use it in GitHub Desktop.
Codility Equi Solution in Javascript - 100% score
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
/* | |
A zero-indexed array A consisting of N integers is given. An equilibrium index of this array is any integer P such that 0 ≤ P < N and the sum of elements of lower indices is equal to the sum of elements of higher indices, i.e. | |
A[0] + A[1] + ... + A[P−1] = A[P+1] + ... + A[N−2] + A[N−1]. | |
Sum of zero elements is assumed to be equal to 0. This can happen if P = 0 or if P = N−1. | |
*/ | |
function solution(A) { | |
var sum = A.reduce(function(pv, cv) { return pv + cv; }); | |
var sum_right; | |
var sum_left = 0; | |
for(i = 0; i < A.length; i++) { | |
sum_right = sum - sum_left - A[i]; | |
if (sum_left === sum_right) return i; | |
sum_left += A[i]; | |
} | |
return -1; | |
} |
I'm an trying to figure this problem out. I can only understand JS or Ruby, and most detailed answers are in Java which I don't know. Is it possible to give an explanation of your solution? My attempts have all failed.
I tried running yours with an array and it always returns minus one. While this is probably a stupid question, and is quite obvious, I have no idea why or how this works. Any explanation would be awesome.
Thanks for the codes, but it would fail when A is empty or a single number array, here is the correct answer:
function solution(A){
var sum
var sum_left = 0
var sum_right
if(!A || A.length == 0){
return -1
}else if(A.length == 1){
sum = A[0]
}else{
sum = A.reduce(function(total, num){ return total + num })
}
for(var i = 0; i < A.length; i++){
sum_right = sum - sum_left - A[i]
if(sum_left == sum_right){ return i }
sum_left += A[i]
}
return -1
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will not give you 100%, at least not currently.
The changes are the following
var sum = A.reduce((a,b) => a+b, 0);
for line 10, this will deal with empty arrays. basically gives 0 as default.https://codility.com/demo/results/demoJBJ7JU-669/