Everyone Can Code!

JavaScript Kata #39: Equal Sides Of An Array

By YayoDrayber | Learn To Code With Me | 22 Sep 2022


If you missed the introductory post, it's here. For a list of previously solved katas, please refer to the bottom of this page.

If this is your first time seeing my post, please note - these katas are probably randomly assigned per user so please don't go into Codewars thinking we will have exactly the same user experience, I am just posting these in the order that I got them.

Kata #39

DESCRIPTION:

You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1.

For example:

Let's say you are given the array {1,2,3,4,3,2,1}:
Your function will return the index 3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6.

Let's look at another one.
You are given the array {1,100,50,-51,1,1}:
Your function will return the index 1, because at the 1st position of the array, the sum of left side of the index ({1}) and the sum of the right side of the index ({50,-51,1,1}) both equal 1.

Last one:
You are given the array {20,10,-80,10,10,15,35}
At index 0 the left side is {}
The right side is {10,-80,10,10,15,35}
They both are equal to 0 when added. (Empty arrays are equal to 0 in this problem)
Index 0 is the place where the left side and right side are equal.

Note: Please remember that in most programming/scripting languages the index of an array starts at 0.

Input:
An integer array of length 0 < arr < 1000. The numbers in the array can be any integer positive or negative.

Output:
The lowest index N where the side to the left of N is equal to the side to the right of N. If you do not find an index that fits these rules, then you will return -1.

Note:
If you are given an array with multiple answers, return the lowest correct index.

Starting code:

function findEvenIndex(arr)
{
  //Code goes here!
}

My attempt that worked:

function findEvenIndex(arr){
  let i = 0
  let nIndex = 0
  let isEven = false
  
  for (i = 0 ; i < arr.length && isEven == false; i++){
    
    let sumLeftOfN = 0
    let sumRightOfN = 0
    
    for(iLeft = 0; iLeft < i; iLeft++){
      sumLeftOfN += +arr[iLeft]
    }
    
    for(iRight = i+1; iRight < arr.length; iRight++){
      sumRightOfN += +arr[iRight]
    }
    
    if(sumLeftOfN === sumRightOfN){
      isEven = true
      nIndex = i
    } else{
      nIndex = -1
    }
    
  }
  
  return nIndex
}

Brain-melting problem. I wanted to use the .reduce() method but I wasn't sure how to pick out the left side and the right side of the N index of the array so I went with what I have right now, but rank #1 by a measly 34 users show us how:

function findEvenIndex(arr)
{
  var left = 0, right = arr.reduce(function(pv, cv) { return pv + cv; }, 0);
  for(var i = 0; i < arr.length; i++) {
      if(i > 0) left += arr[i-1];
      right -= arr[i];
      
      if(left == right) return i;
  }
  
  return -1;
}

Rank #2 with two-liners by users  rahul,   AltSquich,   hassan.m98,   davidsonq,   Travis Merrit:

const sum = (a, from, to) => a.slice(from, to).reduce((a, b) => a + b, 0)
const findEvenIndex = a => a.findIndex((el, i) => sum(a, 0, i) === sum(a, i + 1));

Rank #3 looks a lot like rank #1 and made by user d-sheep:

function findEvenIndex(arr)
{
  let left = 0;
  let right = arr.reduce((s,n) => s + n, 0);
  for (let i = 0; i < arr.length; i++) {
    right -= arr[i];
    if (left === right) return i;
    left += arr[i];
  }
  return -1;
}

Rank #4 by users petebrChernyshovaAlexandraLomakoDashakarki011:

function findEvenIndex(arr)
{
  function sum(arr){
    return arr.reduce(function(a,b){return a+b;},0);
  }

  return arr.findIndex(function(el,i,arr){
    return sum(arr.slice(0, i)) === sum(arr.slice(i+1,arr.length));
  });
}

Rank #5 by user palmertodd:

function findEvenIndex(arr){
  return arr.findIndex((e,i,a)=> a.slice(0,i).reduce((p,c)=>p+c,0)==a.slice(i+1).reduce((p,c)=>p+c,0));
}

Rank #6 by user skhamoud:

function findEvenIndex(arr){
  const sum = arr => arr.reduce((acc,cur)=> (acc+cur) ,0)
  return arr.findIndex((val,idx) => sum(arr.slice(0,idx)) === sum(arr.slice(idx+1)))
}

Rank #7 by user ellielo:

function findEvenIndex(arr){
  // LOOP THROUGH INDEX
    for (var i = 0; i < arr.length; i++) {
      var j = arr.slice(0, i);
      var l = arr.slice(i+1, arr.length);
  // ADD THE LEFT SIDE AND THE RIGHT SIDE 
      function add(a, b) {
        return a + b
      }
    var sumLeft = j.reduce(add, 0);
    
    var sumRight = l.reduce(add, 0);

  // DOES IS EQUAL THE SAME 
    if (sumLeft === sumRight) {
      return i
    };
    if (i === arr.length-1 && sumLeft!== sumRight) {
      return -1
     }
    }
}

Rank #8 made by users drewtylerwhin007roshlaroshmattleahy and youssefby96 also looks a bit like rank #3 and rank #1 but without using the .reduce() method:

function findEvenIndex(arr)
{
  var leftsum = 0;
  var rightsum = 0;
  for(var i = 0; i < arr.length; i++) {
    rightsum += arr[i]; 
  }
  for(i = 0; i < arr.length; i++) {
    rightsum -= arr[i];
    if(leftsum === rightsum) return i;
    leftsum += arr[i];
  }
  return -1;
}

Rank #9 by user Konstantin Modin with a one-liner:

findEvenIndex=(a,b=a=>a.reduce((a,b)=>a+b,0))=>a.findIndex((_,i)=>b(a.slice(0,i))==b(a.slice(i+1)))

Rank #10 by user SteveAquino:

function sum(a, b) { return a + b; }

function findEvenIndex(arr) {
  return arr.findIndex((_, i) =>
    arr.slice(0, i + 1).reduce(sum) === arr.slice(i).reduce(sum)
  );
}

Wanted to show all the top ten approaches just to show that my messy approach could have been tons better.

That's it for Kata #39, stay tuned for more katas to be solved!

Link to Kata #1: Square(n) Sum

Link to Kata #2: Convert a Number to a String

Link to Kata #3: DNA to RNA Conversion

Link to Kata #4: Remove First and Last Character

Link to Kata #5: MakeUpperCase

Link to Kata #6: Total amount of points

Link to Kata #7: A Needle in the Haystack

Link to Kata #8: Sum of positive

Link to Kata #9: Basic Mathematical Operations

Link to Kata #10: Beginner - Reduce but Grow

Link to Kata #11: Square Every Digit

Link to Kata #12: Friend or Foe?

Link to Kata #13: Grasshopper - Summation

Link to Kata #14: Get the Middle Character

Link to Kata #15: Descending Order

Link to Kata #16: String ends with?

Link to Kata #17: Sum of two lowest positive integers

Link to Kata #18: Sum of odd numbers

Link to Kata #19: Find the next perfect square!

Link to Kata #20: Reversed Strings

Link to Kata #21: Jaden Casing Strings

Link to Kata #22: Even or Odd

Link to Kata #23: Returning Strings

Link to Kata #24: Opposite number

Link to Kata #25: Are You Playing Banjo?

Link to Kata #26: Beginner Series #1 School Paperwork

Link to Kata #27: Remove String Spaces

Link to Kata #28: Invert values

Link to Kata #29: Count by X

Link to Kata #30: Beginner Series #2 Clock

Link to Kata #31: Is this a triangle?

Link to Kata #32: Sum of the first nth term of Series

Link to Kata #33: Find the smallest integer in the array

Link to Kata #34: Simple multiplication

Link to Kata #35: How good are you really?

Link to Kata #36: Who likes it?

Link to Kata #37: Convert a String to a Number!

Link to Kata #38: Highest and Lowest

Resources

  1. https://www.publish0x.com/learn-to-code-with-me/obligatory-introductory-post-xddgyxl
  2. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-1-squaren-sum-xvmywpl
  3. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-2-convert-a-number-to-a-string-xmymkwm
  4. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-3-dna-to-rna-conversion-xgjlpox
  5. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-4-remove-first-and-last-character-xyeyykj
  6. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-5-makeuppercase-xzgnnqd
  7. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-6-total-amount-of-points-xeellvx
  8. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-7-a-needle-in-the-haystack-xlqzzgp
  9. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-8-sum-of-positive-xxzyyrl
  10. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-9-basic-mathematical-operations-xlqzzer
  11. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-10-beginner-reduce-but-grow-xxzyylv
  12. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-11-square-every-digit-xnnxxyr
  13. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-12-friend-or-foe-xddggmm
  14. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-13-grasshopper-summation-xnnxxwr
  15. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-14-get-the-middle-character-xrgnney
  16. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-15-descending-order-xmymmwn
  17. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-16-string-ends-with-xeelnpk
  18. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-17-sum-of-two-lowest-positive-integers-xjroxpn
  19. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-18-sum-of-odd-numbers-xeelnwk
  20. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-19-find-the-next-perfect-square-xozowvo
  21. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-20-reversed-strings-xvmyqyn
  22. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-21-jaden-casing-strings-xwywdwd
  23. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-22-even-or-odd-xwywdvd
  24. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-23-returning-strings-xeelxvw
  25. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-24-opposite-number-xxzyerp
  26. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-25-are-you-playing-banjo-xjrowyk
  27. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-26-beginner-series-1-school-paperwork-xxzyelp
  28. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-27-remove-string-spaces-xjrowqk
  29. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-28-invert-values-xnnxgwx
  30. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-29-count-by-x-xyeyzjz
  31. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-30-beginner-series-2-clock-xddgwmj
  32. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-31-is-this-a-triangle-xjrowxk
  33. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-32-sum-of-the-first-nth-term-of-series-xzgnjex
  34. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-33-find-the-smallest-integer-in-the-array-xpzpkkx
  35. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-34-simple-multiplication-xvmyqqd
  36. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-35-how-good-are-you-really-xjrowwz
  37. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-36-who-likes-it-xmymelp
  38. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-37-convert-a-string-to-a-number-xpzpkop
  39. https://www.publish0x.com/learn-to-code-with-me/javascript-kata-38-highest-and-lowest-xyeyrkv

How do you rate this article?

1


YayoDrayber
YayoDrayber

A Yayo, A Drayber, among others.


Learn To Code With Me
Learn To Code With Me

Just started with Codewars and will be posting the solutions I came up with here and the apparent best practices.

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.