tags:

views:

332

answers:

1

Hello!

simonn helped me to code an ordered integer partition function here. He posted two functions: one function simply gives back the count of partitions, the second function gives the partitions as a list.

I've already managed to translate the first function from Java to PHP:

Unfortunately, I can't manage to translate the second function. Can anyone help me and translate this small function for me?

public class Partitions2
{
    private static void showPartitions(int sizeSet, int numPartitions)
    {
        showPartitions("", 0, sizeSet, numPartitions);
    }

    private static void showPartitions(String prefix, int start, int finish,
                int numLeft)
    {
        if (numLeft == 0 && start == finish) {
                System.out.println(prefix);
        } else {
                prefix += "|";
                for (int i = start + 1; i <= finish; i++) {
                        prefix += i + ",";
                        showPartitions(prefix, i, finish, numLeft - 1);
                }
        }
    }

    public static void main(String[] args)
    {
        showPartitions(5, 3);
    }
}

It would be great if the solution would be one single function instead of a class with several functions.

Thank you very much in advance! And thanks again to simonn for this great answer!

+1  A: 

You probably don't need the main method, that just seems to be a test rig showing how to invoke the other method.

The problem mapping this code directly to PHP is that you can't overload method names in PHP. Instead you should concentrate on translating the second version of the showPartitions function. If you need a 2-argument version you can use default values for the prefix and start parameters (you'll have to change the parameter order to do this because in PHP optional parameters must come last).

Here's my (untested) attempt at translating the most important function:

function showPartitions($prefix, $start, $finish, $numLeft)
{
    if ($numLeft == 0 && $start == $finish) {
        echo $prefix."\n";
    } else {
        $prefix .= "|";
        for ($i = $start + 1; $i <= $finish; $i++) {
            $prefix .= $i.",";
            showPartitions($prefix, $i, $finish, $numLeft - 1);
        }
    }
}
Dan Dyer
If this is supposed to be a method in a class, it should call itself with $this->showPartitions
OIS
Thank you so much! :) It works fine. This is exactly what I wanted to have. The only mistake: You forgot the "$" in line 8. It must be: $prefix .= $i.",";
@OIS: I originally had it as a static method called with self::, but the OP didn't want it as part of a class, so I just made it a standalone function.@marco92w: Thanks, I've edited it to fix that.
Dan Dyer