PHP Online Compiler
Example: Solve 0/1 Knapsack Problem in PHP
C
C++
C#
Java
Python
PHP
main.php
STDIN
Run
<?php // Solve 0/1 Knapsack Problem in PHP // This will return max size of the value function maxSize($a, $b) { return $a > $b ? $a : $b; } // This function will solve the 0 1 knapsack problem function solveKnapSack($W, $wt = [], $val = [], $n) { if ($n == 0 || $W == 0) { return 0; } // 1. If the weight of the nth item is more than // 2. Knapsack capacity W, then this item cannot be included in the optimal solution if ($wt[$n - 1] > $W) { return solveKnapSack($W, $wt, $val, $n - 1); } // It returns the maximum of two cases: // 1. nth item included // 2. not included else { return maxSize($val[$n - 1] + solveKnapSack($W - $wt[$n - 1], $wt, $val, $n - 1), solveKnapSack($W, $wt, $val, $n - 1)); } } // It's the driver code $val = [60, 100, 120]; $wt = [10, 20, 30]; $W = 50; $n = intval (sizeof($val) / sizeof($val[0])); // This will print the solution of 0-1 Knapsack problem echo "The solution of 0-1 Knapsack problem is: " . solveKnapSack($W, $wt, $val, $n); ?>
Output
Clear
ADVERTISEMENTS