Skip to content

Instantly share code, notes, and snippets.

@ckahle33
Last active April 11, 2016 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckahle33/b0a20d845e3e51f63d741fc6ca58587f to your computer and use it in GitHub Desktop.
Save ckahle33/b0a20d845e3e51f63d741fc6ca58587f to your computer and use it in GitHub Desktop.
array Sort
// [2, 1, 1]
// x = 2
// [[2], [1], [1]]
// 1, 1], [2]]
// [2, 2, 1, 1, 2, 2, 2]
// x = 3
// [[2, 1], [2, 1]]
//assumes input is an array.. would normally error handle / check it
var output = [];
var interim = [];
function arraySort(max, input) {
var interimSum = 0;
var i = input.length;
do {
debugger;
i--
interimSum = interim.reduce(function(pv, cv) {
return pv + cv;
}, 0);
if (input[i] === max) {
output.push([input[i]])
input.splice(i, 1)
i = input.length
} else if (input[i] < max) {
// need to get the sum of interim and decide if we need to clear it
if (interim.length) {
if (interimSum + input[i] <= max) {
// safely push value that wont exceed max
interim.push(input[i])
input.splice(i, 1);
} else if (interimSum === max) {
output.push(interim)
interim = [];
} else {
// start over with a re-ordered array, probably not performant
var lastVal = input.pop()
input.unshift(lastVal)
arraySort(3, input)
}
// for the first item in interim
} else {
interim.push(input[i]);
input.splice(i, 1);
if (!input.length) {
output.push(interim);
}
}
}
} while (i > 0)
}
var max = 3;
var input = [1, 2, 2, 2, 1, 1, 1, 3];
arraySort(max, input);
console.log(output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment