Splitting array of numbers into two arrays with same average in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in an array of integers as the first and the only argument.

The function needs to determine whether there exists a combination of elements of the input array that when they are divided into two groups (may/may not have equal elements), the average of both the groups is just the same. If there exists any such condition the function should return true, false otherwise.

For example −

If the input array is −

const arr = [6, 3, 2, 8, 1, 5, 7, 4];

Then the output should be −

const output = true;

because the combination is [8, 1, 5, 4] and [6, 3, 2, 7] as both the groups have an average of 4.5

Example

Following is the code −

const arr = [6, 3, 2, 8, 1, 5, 7, 4];
const canHaveEqualAveragePartition = (arr = []) => {
   const sum = arr.reduce((acc, val) => acc + val);
   const array = Array(sum+1).fill(false).map(() =>
   Array(arr.length+1).fill(false));
   array[0][0] = true;
   for(let i=0; i < arr.length; ++i){
      for(let j=sum - arr[i];j>=0;--j){
         for(let k=arr.length-2;k>=0;--k){
            if(array[j][k]){
               array[j + arr[i]][k+1] = true;
               if((j + arr[i]) * (arr.length - k - 1) == (sum - j -arr[i]) * (k + 1)){
                  return true;
               }
            }
         }
      }
   }
   return false;
};
console.log(canHaveEqualAveragePartition(arr));

Output

Following is the console output −

true
raja
Published on 20-Jan-2021 06:53:23
Advertisements