|
| 1 | + |
| 2 | +for ( var i = 0; i <= N; i++ ) { |
| 3 | + for( var j = 0; j <= W; j++ ) { |
| 4 | + if( i === 0 || j === 0 ) { |
| 5 | + /* |
| 6 | + If we have no items or maximum weight we can take in collection is 0 |
| 7 | + then the total weight in our collection is 0 |
| 8 | + */ |
| 9 | + DP[i][0] = 0; |
| 10 | + tracer._notify( i, j, DP[i][j])._wait(); |
| 11 | + tracer._denotify( i, j); |
| 12 | + } else if ( wt[i-1] <= j ) { // take the current item in our collection |
| 13 | + |
| 14 | + dataViewer1._select(i-1)._wait(); |
| 15 | + dataViewer2._select(i-1)._wait(); |
| 16 | + tracer._select( i-1, j)._wait(); |
| 17 | + |
| 18 | + var A = val[i - 1] + DP[i - 1][j - wt[i - 1]]; |
| 19 | + var B = DP[i - 1][j]; |
| 20 | + /* |
| 21 | + find the maximum of these two values |
| 22 | + and take which gives us a greater weight |
| 23 | + */ |
| 24 | + if (A > B) { |
| 25 | + DP[i][j] = A; |
| 26 | + tracer._notify( i, j, DP[i][j])._wait(); |
| 27 | + } else { |
| 28 | + DP[i][j] = B; |
| 29 | + tracer._notify( i, j, DP[i][j])._wait(); |
| 30 | + } |
| 31 | + |
| 32 | + tracer._deselect( i-1, j); |
| 33 | + tracer._denotify( i, j); |
| 34 | + dataViewer2._deselect(i-1); |
| 35 | + dataViewer1._deselect(i-1); |
| 36 | + |
| 37 | + } else { // leave the current item from our collection |
| 38 | + |
| 39 | + DP[i][j] = DP[i - 1][j]; |
| 40 | + tracer._notify( i, j, DP[i][j])._wait(); |
| 41 | + tracer._denotify( i, j); |
| 42 | + } |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +logger._print(' Best value we can achieve is ' + DP[N][W]); |
0 commit comments