[FIXED] PHP Complex Number Selection

Issue

I wrote the following code:

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

The values ​​for $puzzle_size and $total_numbers_to_display depend on the difficulty:

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

I am not getting the desired output from the values ​​in $yes_array. Here’s what I’ve been given for now:

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

What I need is at least one 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 don’t know 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.

Answered By – Practical Opportunist

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published