Skip to content

Corrected explanations and included an example #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 22, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions src/algorithms/math/integer-partition/integerPartition.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ export default function integerPartition(number) {
partitionMatrix[0][numberIndex] = 0;
}

// Let's fill the first row. It represents the number of way of how we can form
// number zero out of numbers 0, 1, 2, ... Obviously there is only one way we could
// form number 0 and it is with number 0 itself.
// Let's fill the first column. It represents the number of ways we can form
// number zero out of numbers 0, 0 and 1, 0 and 1 and 2, 0 and 1 and 2 and 3, ...
// Obviously there is only one way we could form number 0
// and it is with number 0 itself.
for (let summandIndex = 0; summandIndex <= number; summandIndex += 1) {
partitionMatrix[summandIndex][0] = 1;
}
Expand All @@ -35,7 +36,18 @@ export default function integerPartition(number) {
} else {
// The number of combinations would equal to number of combinations of forming the same
// number but WITHOUT current summand number plus number of combinations of forming the
// previous number but WITH current summand.
// <current number - current summand> number but WITH current summand.
// Example: number of ways to form number 4 using summands 1, 2 and 3 is the sum of
// {number of ways to form 4 with sums that begin with 1 +
// number of ways to form 4 with sums that begin with 2 and include 1} +
// {number of ways to form 4 with sums that begin with 3 and include 2 and 1}
// Taking these sums to proceed in descending order of intergers, this gives us:
// With 1: 1+1+1+1 -> 1 way
// With 2: 2+2, 2+1+1 -> 2 ways
// With 3: 3 + (4-3) <= convince yourself that number of ways to form 4 starting
// with 3 is == number of ways to form 4-3 where 4-3 == <current number-current summand>
// Helper: if there are n ways to get (4-3) then 4 can be represented as 3 + first way,
// 3 + second way, and so on until the 3 + nth way. So answer for 4 is: 1 + 2 + 1 = 4 ways
const combosWithoutSummand = partitionMatrix[summandIndex - 1][numberIndex];
const combosWithSummand = partitionMatrix[summandIndex][numberIndex - summandIndex];

Expand Down