PHP code example of writ3it / libalgo-knapsack-problem

1. Go to this page and download the library: Download writ3it/libalgo-knapsack-problem library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

writ3it / libalgo-knapsack-problem example snippets




use Writ3it\LibAlgo\KnapsackProblem\Impl\Item;
use Writ3it\LibAlgo\KnapsackProblem\Impl\Bag;
use Writ3it\LibAlgo\KnapsackProblem\Algorithm\DynamicKnapsackSolver;

$items = [
    // new Item(<weight>, <value f.e. price>)
    new Item(2, 4), /** Item 0 **/
    new Item(1, 3), /** Item 1 **/
    new Item(4, 6), /** Item 2 **/
    new Item(4, 8)  /** Item 3 **/
];

// new Bag(<capacity>)
$bag = new Bag(8); 

$algo = new DynamicKnapsackSolver();
$value = $algo->solve($items, $bag);

var_dump([

     // Item 0,1,3 which are optimal content of the bag.
    'content'=>$bag->getItems(), 

     // Summary value of items in bag.
    'value' =>$value 

]);




use Writ3it\LibAlgo\KnapsackProblem\ItemInterface;

class CustomItem implements ItemInterface
{

    
    /**
     * {@inheritdoc}
     */
    public function getWeight(): int
    {
        // Custom logic to compute a weight.
    }
    
    /**
     * {@inheritdoc}
     */
    public function getValue(): int
    {
        // Custom logic to compute a value.
    }

    /**
     * More your own methods
     */

}



use Writ3it\LibAlgo\KnapsackProblem\ItemInterface;

class CustomBag implements BagInterface
{

    
    public function getCapacity(): int
    {
       // Custom logic to compute a capacity.
    }

    public function addItem(ItemInterface $item): void
    {
        // Custom logic to receive a items which are a solution.
    }

    /**
     * More your own methods
     */

}