Skip to content

Instantly share code, notes, and snippets.

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 camilomontoyau/8fcff915d84a57f70978c82342b4644e to your computer and use it in GitHub Desktop.
Save camilomontoyau/8fcff915d84a57f70978c82342b4644e to your computer and use it in GitHub Desktop.
partitions of a number in javascript
const reducer = (accumulator, currentValue) => accumulator + currentValue;
const hasElementGreaterThanOne = (array = []) => {
let begin = array.length - 2;
let result = false;
if (begin > 0) {
for (let i = begin; i > 0; i--) {
if (array[i] > 1) {
result = i;
break;
}
}
}
return result;
};
function part(num1) {
let a = num1;
let singleSum = [];
let result = [];
let b;
while (a > 0) {
singleSum.push(a);
if (singleSum.reduce(reducer) === num1) {
result.push([...singleSum]);
if (singleSum[singleSum.length - 1] > 1) {
a = singleSum[singleSum.length - 1] - 1;
singleSum.pop();
} else if (
singleSum[singleSum.length - 1] === 1 &&
hasElementGreaterThanOne(singleSum)
) {
let idx = hasElementGreaterThanOne(singleSum);
singleSum = [...singleSum.slice(0, idx + 1)];
a = singleSum[singleSum.length - 1] - 1;
singleSum.pop();
} else if (singleSum[0] >= 1) {
a = singleSum[0] - 1;
singleSum = [];
} else {
a--;
singleSum = [];
}
} else if (singleSum.reduce(reducer) < num1) {
if (singleSum.length < num1) {
continue;
} else if (singleSum.length === num1) {
singleSum.pop();
continue;
}
} else if (singleSum.reduce(reducer) > num1) {
singleSum.pop();
a--;
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment