Skip to content

Instantly share code, notes, and snippets.

@jeanlescure
Last active September 2, 2022 13:57
Show Gist options
  • Save jeanlescure/797eef515cfa4a05830b to your computer and use it in GitHub Desktop.
Save jeanlescure/797eef515cfa4a05830b to your computer and use it in GitHub Desktop.
Codility TapeEquilibrium Solution in Javascript - 100% score
/*
A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
*/
function solution(A) {
var sumRight = A.reduce((pv, cv, idx) => (idx > 0) ? (pv + cv) : (0), 0);
var sumLeft = 0;
var substractions = [];
var maxI = A.length - 1;
for(var i = 0; i < maxI; i += 1){
sumLeft += A[i];
substractions.push(Math.abs(sumLeft - sumRight));
if (i + 1 <= maxI) sumRight -= A[i + 1];
}
return substractions.reduce((pv, cv, idx) => (idx > 0) ? ((pv < cv)? pv : cv) : (cv), 0);
}
@sarpisik
Copy link

function solution(A) {
  let sumLeft = A[0];
  let sumRight = A.reduceRight(
    (sum, current, i) => (i === 0 ? sum : sum + current),
    0
  );
  let result = getDiff(sumLeft, sumRight);

  for (let i = 1; i < A.length - 1; i++) {
    const current = A[i];

    sumRight -= current;
    sumLeft += current;

    const diff = getDiff(sumLeft, sumRight);
    result = result > diff ? diff : result;
  }

  return result;
}

function getDiff(num1, num2) {
  return Math.abs(num1 - num2);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment