Javascript: 2 arrays with the same "weight"

I am trying to figure out how to have 2 arrays balanced by their weight.

I already have an array that stores 10 integers. Like this example:

var arrayToSplit = new Array();
arrayToSplit = [1, 1, 4, 2, 3, 2, 3, 1, 4, 2]; //Total 23

I need to take these values ​​and push them onto 2 new arrays, but with one condition:

I need to have the same weight or similar between them and both arrays with 5 numbers . So it looks like this.

new array = [4, 3, 2, 1, 1]; //Total 11
new array2 = [4, 3, 2, 1, 2]; // Total 12
+4
source share
2 answers

I implemented the pseudo-polynomial algorithm (it quickly justified any errors):

http://jsfiddle.net/536Z2/1/

arrayToSplit = [1, 1, 4, 2, 3, 2, 3, 1, 4, 2]; //Total 23
result = find_partition(arrayToSplit);
console.log(result[0]);
console.log(result[1]);

function find_partition(integers) {
    var array01 = [];
    var array02 = [];
    var partitionedArrays = [];
    var arrayLength = integers.length;
    for (var i = 0; i < arrayLength; i++) {
        if (sumArray(array01) <= sumArray(array02)) {
            array01.push(integers[i]);
        } else {
            array02.push(integers[i]);
        }
    }

    partitionedArrays.push(array01);
    partitionedArrays.push(array02);
    return partitionedArrays;
}

function sumArray(array) {
    var count = 0;

    var arrayLength = array.length;
    for (var i = 0; i < arrayLength; i++) {
        count += array[i];
    }

    return count;
}
+2
source

, , , - , , :

var arrayToSplit = new Array();
arrayToSplit = [1, 1, 4, 2, 3, 2, 3, 1, 4, 2]; //Total 23

var array1 = [];
var array2 = []; 


while(arrayToSplit.length>0)
{
    array1.push(arrayToSplit.shift());
    array2.push(arrayToSplit.shift());
}

// Results
array1 = [1, 1, 2, 3, 4]; // Total 11
array2 = [1, 2, 2, 3, 4]; // Total 12
+1

Source: https://habr.com/ru/post/1523743/


All Articles