Skip to content

Commit e214105

Browse files
committed
Algorithm for Ugly Numbers( DP Solution )
1 parent 1db8388 commit e214105

File tree

4 files changed

+64
-1
lines changed

4 files changed

+64
-1
lines changed

algorithm/category.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@
6060
"max_subarray": "Maximum Subarray",
6161
"max_sum_path": "Maximum Sum Path",
6262
"sliding_window": "Sliding Window",
63-
"integer_partition": "Integer Partition"
63+
"integer_partition": "Integer Partition",
64+
"ugly_numbers": "Ugly Numbers"
6465
}
6566
},
6667
"etc": {
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
for ( var i = 1; i < N; i++ ) {
2+
// next is minimum of m2, m3 and m5
3+
var next = (M[0] <= M[1])?( M[0] <= M[2] )?M[0]:M[2]:( M[1] <= M[2] )?M[1]:M[2];
4+
logger._print( ' Minimum of ' + M[0] + ', ' + M[1] + ', ' + M[2] + " : " + next );
5+
A[i] = next;
6+
7+
tracer._notify( i, A[i] )._wait();
8+
tracer._denotify( i );
9+
10+
if ( next === M[0] ) {
11+
I[0]++;
12+
M[0] = A[I[0]] * 2;
13+
tracer2._notify( 0, M[0])._wait();
14+
tracer3._notify( 0, I[0])._wait();
15+
tracer2._denotify(0);
16+
tracer3._denotify(0);
17+
18+
}
19+
if ( next === M[1] ) {
20+
I[1]++;
21+
M[1] = A[I[1]] * 3;
22+
tracer2._notify( 1, M[1])._wait();
23+
tracer3._notify( 1, I[1])._wait();
24+
tracer2._denotify(1);
25+
tracer3._denotify(1);
26+
}
27+
if ( next === M[2] ) {
28+
I[2]++;
29+
M[2] = A[I[2]] * 5;
30+
tracer2._notify( 2, M[2])._wait();
31+
tracer3._notify( 2, I[2])._wait();
32+
tracer2._denotify(2);
33+
tracer3._denotify(2);
34+
}
35+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
var N = 15;
2+
var A = new Array(N);
3+
for (var i = N - 1; i >= 0; i--) {
4+
A[i] = 0;
5+
}
6+
A[0] = 1; // By convention 1 is an ugly number
7+
8+
var M = [2,3,5]; // multiples of 2, 3, 5 respectively
9+
var I = [0,0,0]; // iterators of 2, 3, 5 respectively
10+
11+
var logger = new LogTracer();
12+
var tracer = new Array1DTracer('Ugly Numbers')._setData(A);
13+
var tracer2 = new Array1DTracer('Multiples of 2, 3, 5')._setData(M);
14+
var tracer3 = new Array1DTracer(' Iterators I0, I1, I2 ')._setData(I);
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"Ugly Numbers": "Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence (1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, …) shows the first 11 ugly numbers. By convention, 1 is included. The given code displays the first N ugly numbers.",
3+
"Complexity": {
4+
"time": "O(n)",
5+
"space": "O(n)"
6+
},
7+
"References": [
8+
"<a href='http://www.algorithmist.com/index.php/UVa_136'>Algorithmist</a>"
9+
],
10+
"files": {
11+
"basic": "Ugly Numbers"
12+
}
13+
}

0 commit comments

Comments
 (0)