albator albator - 6 months ago 12
MySQL Question

Find which unique numbers was summed to produce a result number

On my site, I have multiple checkbox fields, where each input doubles in value from the previous, like this:

<form name=test>
<input type='checkbox' name='groupe' value = '1'>
<input type='checkbox' name='groupe' value = '2'>
<input type='checkbox' name='groupe' value = '4'>
<input type='checkbox' name='groupe' value = '8'>
<input type='checkbox' name='groupe' value = '16'>
etc...
</form>


I stock the fields selected (by the user) result in summing all of the values selected.

Let's say that the user had selected 4 and 1. In this case, I insert the sum of field values, which is 5. At this stage, after insert, my SQL table is:

test
5


I need to retrieve the values selected to create this result number 5.

The information to do that are:
- 31 (the max result, which is the sum of each field 1+2+4+8+16)
- it is impossible to get a result value of 5 using 2+2+1, because an input cannot be selected twice;

I did a lot of searching to solve this, but I couldn't find anything helpful. How do I do this in SQL or PHP?

Answer

I'm not sure what the point of storing the sum and then recovering the individual values - why not store the separate values?

That said, if you must, the algorithm is quite simple:

<?php
    print_r(get_parts($argv[1]));

    function get_parts($number) {
        $res = array();
        for ($pow = 1; $pow <= 16; $pow <<= 1)
        {
           if ($pow & $number) {
               array_push($res, $pow);
           }
        }
        return $res;
    }
?>

This function will accept a number and return an array of the components:

$ php test.php 5
Array
(
    [0] => 1
    [1] => 4
)
$ php test.php 31
Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 8
    [4] => 16
)