Search code examples
phprandom

PHP Complex Number Selection


I have wrote the following code:

$row_array = range( 1 , $puzzle_size , 1 );
$yes_array = array_rand( $row_array , $total_numbers_to_display );

The values of $puzzle_size and $total_numbers_to_display depends on the difficulty level:

$puzzle_size will be 8, 20 and 40 for easy, medium and hard levels. $total_numbers_to_display = 3

The value of $yes_array is not giving me the output I need. What it gave me right now is:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

What I am requiring is for there to be at least 1 number gap between each result.

Example 1:

Array
(
    [0] => 1
    [1] => 3
    [2] => 5
)

Example 2:

Array
(
    [0] => 1
    [1] => 4
    [2] => 7
)

Example 3:

Array
(
    [0] => 2
    [1] => 4
    [2] => 7
)

I am unsure of how to do this.


Solution

  • Please edit your code as shown below :

    <?php 
    // Total number of items required
    $puzzle_size = 50;
    
    // Total items to be displayed 
    $total_numbers_to_display = 5;
    
    // Seed the array items as per $puzzle_size value
    $row_array = range( 1 , $puzzle_size , 1 );
    
    // Function to get the random array items and pick only the number of items required. array_rand() will return only the keys of the array, not the values.
    function randItems($sourceArray){
        
        // declare global variable
        global $total_numbers_to_display;
    
        // generate random array elements and return 
        return array_rand( $sourceArray , $total_numbers_to_display );
    }
    
    // Function to check whether any consequtive numbers are generated from randItems function above. If exists, then re-pick the random elements from $row_array 
    function get_non_consequtive_numbers($outputArray)
    {
        // declare global variable
        global $row_array;
    
       // iterate through the array provided as parameter
       foreach($outputArray as $num){
    
            // check if any previous or next number exists in the generated array. If exists, then re-pick the random elements from $row_array
            if( in_array(($num+1) , $outputArray ) or in_array(($num-1), $outputArray ) )
            {
    
                // calling randItems and recursive function to check.
                return get_non_consequtive_numbers(randItems($row_array));   
            }
        }
        
        // if no consequtive numbers found, then the array is valid and return.
        return $outputArray;      
    }
    
    // initiating the generation process
    $yes_array = get_non_consequtive_numbers(randItems($row_array));
    
    // printing the output obtained from above line
    print_r($yes_array);
    

    Output is as expected in the question.