M
M
MasterCopipaster2020-11-11 11:07:13
PHP
MasterCopipaster, 2020-11-11 11:07:13

Write an algorithm for enumerating options with weight?

Tell me even stupid I don’t know how to do it, there is such an array.

<?php
$a = [
    0 => 'a',
    1 => 'b',
    2 => 'c'
];

I need to iterate over all possible options, but with the weight saved, as the weight is the array index.
Now I will explain in more detail: that is, the element with index 0 cannot go after index 1 and index 1 cannot be before zero.
For the current array, you get the following options:
a
b
c
ab
ac
bc
abc

Please note that variants of the acb type cannot be obtained because the index b is less than the index c.
I hope I explained it clearly, the algorithm for enumerating all possible options is not suitable here. And it doesn't even occur to me how to write it adequately.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-11-11
@MasterCopipaster

If permutations are not needed, then everything is simple. Each element is either included in the next option or not. Accordingly, you loop 1 to pow(2, count($arr)). You convert each loop number to binary with the decbin built-in function, reverse the result, and use it to make a new version - if 1 is in the corresponding place in the returned decbin string, then include the element, if 0, then exclude it.

$arr = [0 => 'a', 1 => 'b', 2 => 'c'];
$res = [];

for ($i = 1; $i < pow(2, count($arr)); $i++ ) {
    $bin = decbin($i);
    $case = "";
    foreach(str_split(strrev($bin)) as $ind => $symb) if ($symb == "1") $case .= $arr[$ind];
    $res[] = $case;
}

echo implode(", ", $res); // a, b, ab, c, ac, bc, abc

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question