N
N
noteblock2017-05-16 17:41:09
JavaScript
noteblock, 2017-05-16 17:41:09

How to sort an array based on the sum of elements?

Given : an array consisting of the numbers 1 and 2.
What you need : I'm building a grid of elements. There is a situation when “not ok”:
81f5e5ac822f40ccba297c1b11889599.png
To do this, I sort the array elements into a new array in groups so that the sum of the elements in the group is equal to 4. Accordingly, the order of the array elements should be as close as possible to the original - only some elements should change places.
I wrote the main part of the code (JS), but there is a bug that I can’t handle:
for example, for an array [1,1,2,1,1,2, 1,2,2,2 ] - it works until the selected moment, then - an infinite loop.
My shitcode:

arr = [1,1,2,1,1,2,1,2,2,2];
var summ = 0;
var rowsCounter = 0;
var rows = []; // финальный массив
function arraySort(){
  for (var i = 0; i < arr.length; i++) {
    summ += arr[i];
    if (summ > 4){
      for (var x = i; x < arr.length; x++) {
        if (summ - arr[x] == 4){
          temp = arr[i];
          arr[i] = arr[x];
          arr[x] = temp;
          summ = 4;
          break;
        } else {
          continue;
        }
      }
    }
    if (summ == 4){
      rows.push(arr.slice(0, i + 1));
      arr.splice(0, i + 1);
      summ = 0;
      break;
    }
  };
}

while (arr.length > 0){
  arraySort();
}

console.log(rows)

Apparently, the remaining small arrays for which some kind of exception is needed?
Because for example, the array [1,2,2] is simply split into [2] [1] [2]
Any help, guys!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Adamos, 2017-05-16
@noteblock

If you just need to collect ones and twos in groups with a sum of 4, then:
0. Count the number of ones and twos.
1. We collect all deuces in pairs.
2. If one is left, add two units to it, if any.
3. We collect all the remaining units by four.
All. No nested loops, recursions and other things are stupidly needed here.

S
Stalker_RED, 2017-05-16
@Stalker_RED

Here is the reason for your infinite loop.

while (arr.length > 0){
  arraySort();
}
You submit elements to the input, the total amount of which is equal to fifteen. No matter how hard you try, they cannot be divided by 4 without a remainder. And you didn't foresee the rest.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question