5
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 different values and 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 which are the elements within this list that gives this sum. I cannot use combination algorithms because above 9 elements already gives exceeded memory limit 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();
The problem is cool, but in php it’s really challenging. In Javascript, I would create a setInterval cycle to run an algorithm in a controlled way, without bursting memory. In php, I think you’ll need to see the creation of http://au2.php.net/manual/en/intro.pthreads.php threads or some asynchronous way of working, otherwise any algorithm will pop.
– Gustavo
@user6492 uses an iterative solution that then the maximum memory you will consume is about the same size as the final response. What consumes the most memory in such a problem is recursion.
– Oralista de Sistemas