JSFiddle - React, Tailwind, and code Playground

by spliter

JavaScript

function sortGroup({sum = 0, index = 0, arr, max}) {
  let newSum = sum + arr[index];
  
  //  base cases to stop recursion:
  if (newSum === max) {
    return true;
  } else if (newSum > max) {
    return false;
  } else if (newSum < max && index === arr.length - 1) {
    //  shouldn't be needed: don't think it will ever get into this brnach but still…
    return false;
  }
  
  //  recursive attack:
  return findMatch(sum + num, index + 1, arr, max);
}

function fairSplit(input) {
  let groupSum = 0;
  
  // first of all, makes sure the input is an Array:
  if (!Array.isArray(input)) {
    return 'The input should be an Array of integers';
  }

  // 1. Low-hanging fruit: let's figure out max sum per group and
  // whether we can split the input into equal sums:
  const arrSum = input.reduce((accumulator, currentValue) => accumulator + currentValue);
  const maxGroupSum = arrSum/2;
  
  console.log(groupmaxGroupSumSum);
  if (maxGroupSum === Nan) {
    // ALERT! Not all input items are numbers.
    return `Please check the input data: the input should be an Array of integers (numbers, digits, this sort of things)`;
  }
  
  if (maxGroupSum % 2 !== 0) {
    // Impossible to get equal sum in both groups. So, no luck here, I'm done;    
    return false;
  }
  
  // 2. Now let's sum up all "multiplies of 3". No need to further process
  // if their sum is higher than maxGroupSum.
  const multiplesOfThree = input.filter(num => num % 3 === 0 );
  groupSum = multiplesOfThree.reduce((accumulator, currentValue) => accumulator + currentValue, group1Sum);
  if (groupSum > maxGroupSum) {
    // Impossible to get equal sum in both groups considering condition #3
    return false;
  }
  
  // 3. Ok, were were unluky enough to get all the way down here.
  // Now we have to process the remaining numbers for real:
  let remainingLoosers = input.filter(num => num % 3 !== 0 );
  
  //… now let's sort the remainingLoosers array
  remainingLoosers = remainingLoosers.sort();
  let...