drupol/phpartition

平衡数组分割的分区问题变得简单。

0.1.2 2017-01-15 22:37 UTC

This package is auto-updated.

Last update: 2024-09-11 20:12:44 UTC


README

Build Status Code Coverage Scrutinizer Code Quality Dependency Status

在数论和计算机科学中,分区问题是指决定给定的多集是否可以被分割成多个平衡的子集。

需求

  • PHP >= 5.6
  • (可选) PHPUnit 来运行测试。

示例

<?php

include "./vendor/autoload.php";

$data = 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
        )
)
 */

您也可以传递对象或数组,但那时,您必须定义如何访问它们的值。

<?php

include "./vendor/autoload.php";

$data = 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
                   )
   
           )
   
   )
 */

还可以混合要分割的对象类型。

待办事项

  • 实现Complete Karmarkar-Karp (CKK)算法
  • 文档。