2008年6月25日 星期三

Combination Generator for PHP

之前需要寫個組合產生器,
寫來寫去, 也跟網路上找到的寫法一樣, 就順便用了他的注解嚕...
/*                                                                                                                            
 * Date   : 2008-06
 * Name   : getCombinationOutput
 * Usage  : Generate all combinations of the elements in the array
 * Input  : @param array   input array contains all elements
 *          @param integer number of choosing
 *          @param string  output file name
 * Output : a text file contains all combination
 *
 * Example :
 * $array = array( 684, 1056, 1066, 1274 );
 * getCombinationOutput( $array, 2, "test.out" );
 *
 * test.out :
 * 684 1056
 * 684 1066
 * 684 1274
 * 1056 1066
 * 1056 1274
 * 1066 1274
 */

function getCombinationOutput( $input_array, $select, $output )
{
    $_number = sizeof($input_array);

    if ( !($_fp = fopen( $output, "a") ) ) 
    {   
        echo "can't open file!\n\r";

        return 0;
    }   

    $_array = array();

    for ( $_i=0; $_i<$select; $_i++ )
    {
        $_array[$_i] = $_i + 1;
    }

    while (1)
    {
        $_temp = array();

        for ( $_i = 0; $_i < $select; $_i++ )
        {
            $_index = $_array[$_i];

            fwrite ( $_fp, $input_array[$_index -1]." " );
        }

        fwrite ( $_fp, "\n" );

        // generate next combination in lexicographical order
        // start at last item
        $_i = $select - 1;

        // find next item to increment
        while ( $_array[$_i] == ( $_number - $select + $_i + 1 ) )
        {
            $_i--;
        }

        // all done
        if ( $_i < 0 )
        {
            break;
        }

        // increment
        $_array[$_i] = $_array[$_i] + 1;
        // do next
        for ( $_j = $_i + 1; $_j < $select; $_j++ )
        {
            $_array[$_j] = $_array[$_i] + $_j - $_i;
        }
    }

    fclose ( $_fp );

    return $output;
}