PHP code example of drupol / phpartition

1. Go to this page and download the library: Download drupol/phpartition 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/ */

    

drupol / phpartition example snippets




 = array(1, 5, 5, 11, 6, 7, 9, 3);

$greedy = new \drupol\phpartition\Algorithm\Greedy();
$greedy->setData($data);
$greedy->setSize(3);
$result = $greedy->getResult();

// $result is:
/*
 * Array
   (
       [0] => Array
           (
               [0] => 9
               [1] => 5
               [2] => 1
           )
   
       [1] => Array
           (
               [0] => 7
               [1] => 6
               [2] => 3
           )
   
       [2] => Array
           (
               [0] => 11
               [1] => 5
           )
   )
 */

$simple = new \drupol\phpartition\Algorithm\Simple();
$simple->setData($data);
$simple->setSize(3);
$result = $simple->getResult();

// $result is:
/*
 * Array
(
    [0] => Array
        (
            [0] => 5
            [1] => 11
        )

    [1] => Array
        (
            [0] => 1
            [1] => 7
            [2] => 3
        )

    [2] => Array
        (
            [0] => 5
            [1] => 6
            [2] => 9
        )
)
 */



 = array(
  array(
    'item' => 'anything A',
    'weight' => 1,
  ),
  array(
    'item' => 'anything B',
    'weight' => 2,
  ),
  array(
    'item' => 'anything C',
    'weight' => 3,
  ),
  array(
    'item' => 'anything D',
    'weight' => 4,
  ),
);

$greedy = new \drupol\phpartition\Algorithm\Greedy();
$greedy->setData($data);
$greedy->setSize(2);
$greedy->setItemAccessCallback(function($item) {
  return $item['weight'];
});
$result = $greedy->getResult();

// $result is
/*
 * Array
   (
       [0] => Array
           (
               [0] => Array
                   (
                       [item] => anything C
                       [weight] => 3
                   )
   
               [1] => Array
                   (
                       [item] => anything B
                       [weight] => 2
                   )
   
           )
   
       [1] => Array
           (
               [0] => Array
                   (
                       [item] => anything D
                       [weight] => 4
                   )
   
               [1] => Array
                   (
                       [item] => anything A
                       [weight] => 1
                   )
   
           )
   
   )
 */