Skip to content

Commit 6ef60e2

Browse files
committed
Integer partition algorithm
1 parent a975a96 commit 6ef60e2

File tree

4 files changed

+57
-1
lines changed

4 files changed

+57
-1
lines changed

algorithm/category.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@
5252
"longest_increasing_subsequence": "Longest increasing subsequence",
5353
"max_subarray": "Maximum subarray",
5454
"max_sum_path": "Maximum sum path",
55-
"sliding_window": "Sliding window"
55+
"sliding_window": "Sliding window",
56+
"integer_partition": "Integer partition"
5657
}
5758
},
5859
"etc": {
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
function partition(A, n, p){
2+
if (n === 0) tracer.logTracer._print('[' + A.join(', ') + ']');
3+
else {
4+
var end = n;
5+
if (p !== 0 && A[p-1] < n) end = A[p-1];
6+
for (var i = end; i > 0; i--){
7+
A[p] = i;
8+
partition(A, n-i, p+1);
9+
}
10+
}
11+
}
12+
13+
function integerPartition(n){
14+
//Calculate number of partitions for all numbers from 1 to n
15+
for (var i = 2; i <= n; i++){
16+
// We are allowed to use numbers from 2 to i
17+
for (var j = 1; j <= i; j++){
18+
// Number of partitions without j number + number of partitions with max j
19+
tracer._select(i, j)._wait();
20+
D[i][j] = D[i][j-1] + D[i-j][Math.max(j, i-j)];
21+
tracer._notify(i, j, D[i][j])._wait();
22+
tracer._denotify(i, j);
23+
tracer._deselect(i, j);
24+
}
25+
}
26+
return D[n][n];
27+
}
28+
29+
tracer.logTracer._print('Partitioning: ' + integer);
30+
partition(A, integer, 0);
31+
var part = integerPartition(integer);
32+
tracer.logTracer._print(part);
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
var tracer = new Array2DTracer().attach(new LogTracer());
2+
var integer = Math.floor(Math.random() * 10) + 5;
3+
var D = [], A = [];
4+
for (var i = 0; i <= integer; i++){
5+
D.push([]);
6+
D[0][i] = 1;
7+
D[i][1] = 1;
8+
for (var j = 0; j <= integer; j++) D[i][j]=0;
9+
}
10+
tracer._setData(D);
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"Integer Partition": "In number theory and combinatorics, a partition of a positive integer n, also called an integer partition, is a way of writing n as a sum of positive integers.",
3+
"Complexity": {
4+
"time": "O(n(log n))",
5+
"space": "O(n<sup>2</sup>)"
6+
},
7+
"References": [
8+
"<a href='https://en.wikipedia.org/wiki/Partition_(number_theory)'>Wikipedia</a>"
9+
],
10+
"files": {
11+
"basic": "Integer partition"
12+
}
13+
}

0 commit comments

Comments
 (0)