I need to develop an algorithm that finds a specific value of the sum of some elements of an array. Ex: I have an array with 50 distinct values and I have a given value "X" .
I know that the sum of the combination of some elements of this array results in this value, what I need to know is what elements within this list give this sum. I can not use combination algorithms since over 9 elements already gives a limit of memory exceeded and I have arrays much larger than this to calculate.
The code I have so far is this:
/**
* Class Teste
*/
class Teste
{
static $values = array(15.92, 53.27, 244.28, 388.46, 3.14, 2.92, 18.22, 4.03);
static $include = array();
// static $expected = 712.02;
static $expected = 297.55;
static $ok = false;
private static $_instance;
/**
* @return static
*/
public static function instance()
{
return static::$_instance = static::$_instance ?: new static();
}
public function __construct()
{
while (!static::$ok) {
reset(static::$include);
static::removeItem(key(static::$include));
static::calc();
}
var_export(static::sum());
}
public static function calc()
{
foreach (static::$values as $k => $v) {
var_export(static::$include);
if (round(static::$expected, 2) == round(static::sum(), 2)) {
static::$ok = true;
break;
} else if (static::$expected > static::sum()) {
static::addItem($k);
}
if (round(static::$expected, 2) < round(static::sum(), 2)) {
static::removeItem($k);
}
}
}
public static function addItem($k)
{
if (!array_key_exists($k, static::$include)) {
static::$include[$k] = round(static::$values[$k], 2);
}
}
public static function removeItem($k)
{
unset(static::$include[$k]);
}
public static function sum()
{
return round(array_sum(static::$include), 2);
}
}
Teste::instance();