Viewed   105 times

I can't provide the HTML due to my site not being live. Though I know from theory coding a professional will hopefully be able to follow my logic.

  • Please point out with my code how I can get this working, as I see the following link is similar but not exactly the same scenario. I'm confused how to apply it to my following code:

Generating random numbers without repeats

My Goal I want to use PHP to create the following:

  1. Place 00 to 99 into an array.
  2. Retrieve a random number from the array.
  3. Store/Use the retrieved random from the array to place in a mysql_query as seen with number = $question Note here (Do I really require ORDER BY RAND() here?)
  4. Remove the selected random number from the array list of numbers
  5. Fetch and display the random number
  6. Once all numbers have been used then an error displays saying, refresh page to reset numbers.

The next time I want another random number it cannot duplicate the same random number it selected from the array before. So if I used the code above say 109 times then only 1 number is left in the array.

Code (Edited):

   <?php

  //--------------------------------------------------------------------------
  // Example php script for fetching data from mysql database
  //--------------------------------------------------------------------------
  $host = "localhost";
  $user = "root";
  $pass = "";

  $databaseName = "monkeyscanfly";
  $tableName = "num_image";

  //--------------------------------------------------------------------------
  // 1) Connect to mysql database
  //--------------------------------------------------------------------------
  include 'DB.php';
  $con = mysql_connect($host,$user,$pass);
  $dbs = mysql_select_db($databaseName, $con);

    if(!isset($_SESSION)) {
        session_start();

        $_SESSSION['used'] = [];
    }

    $array = [0,1,2,3,4,5,6,7,8,9,"00","01","02","03","04","05","06","07","08","09",10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99]; 

    while(!empty($array)) {
        $array = array_diff($array, $_SESSSION['used']);

        //pick a random point from the array
        $random = array_rand($array);

        // Save the used element in session
        $_SESSION['used'][] = $array;


        //store the random question number
        $question = $array[$random];

        // Select information from database and use array to assign to the selected row.

        $query = mysql_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE number = $question ORDER BY RAND() LIMIT 1");

        // Remove random number that was chosen from the array, so the next time the random number is ran, it won't be found in the array.

        unset($array[$random]);

        //fetch result to print on page

        $arrayss = mysql_fetch_row($query);

        //Echo result as json
        echo json_encode($arrayss);
    }

    if(count($array) == count($_SESSION['used'])) {
        $_SESSION['used'] = [];
    }
?>

I hope this makes sense, I'm having a difficult time find out how to do it, I have searched for hours and can't get my head around it. :)

I forgot to mention that this PHP script will be reloaded by ajax code every time I need a new random number. So it has to store/remember the number with that in mind. If that makes sense?

 Answers

1

if I understood your correctly I think this code is what you're looking for. In this case since you're using AJAX we'll be saving used questions like array in session.

<?php
    if(!isset($_SESSION)) {
        session_start();

        $_SESSION['used'] = ((!isset($_SESSION['used'])) ? ([]) : ($_SESSION['used']));
    }

    //--------------------------------------------------------------------------
    // 1) Connect to mysql database
    //--------------------------------------------------------------------------
    include 'DB.php';

    $con = mysql_connect($host, $user, $pass);
    $dbs = mysql_select_db($databaseName, $con);

    $array = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99];
    $array_unique = [];

    while(!empty($array_unique = array_diff($array, $_SESSION['used']))) {
        //pick a random point from the array
        $random = array_rand($array_unique, 1);

        // Save the used element in session
        $_SESSION['used'][] = $array_unique[$random];

        //store the random question number
        $question = $array_unique[$random];

        // Select information from database and use array to assign to the selected row.
        $query = mysql_query("SELECT `number`,`association`,`image_file`,`skeleton`,`sound`,`colour`,`comments` FROM ".$tableName." WHERE `number` = ".$question." LIMIT 0,1");

        //fetch result to print on page

        $row = mysql_fetch_row($query);

        //Echo result as json
        echo json_encode($row);
    }
    if(count($array_unique) == 0) {
        $_SESSION['used'] = [];
    }
?>

Just use while and array_rand

Saturday, October 15, 2022
 
mr_ed
 
3

Well, there are a few alternatives. I'm not sure which is the fastest since you're dealing with a sizable array, but you may want to try them out:

You can use shuffle, which will randomize the entire array. This will likely have the best performance since you're consuming a significant portion of the array (10%).

shuffle($seedkeys);
$result = array_slice($seedkeys, 0, 1000);

You could use array_rand (as you already said) in the manor that Tom Haigh specifies. This will require copying the keys, so if you're dealing with a significant portion of the source array, this may not be the fastest. (Note the use of array_flip, it's needed to allow the usage of array_intersect_key:

$keys = array_flip(array_rand($seedkeys, 1000));
$result = array_intersect_key($seedkeys, $keys);

If memory is tight, the best solution (besides the MySQL one) would be a loop since it doesn't require arrays to be copied at all. Note that this will be slower, but if the array contains a lot of information, it may offset the slowness by being more memory efficient (since it only ever copies exactly what it returns)...

$result = array();
for ($i = 0; $i < 1000; $i++) {
    $result[] = $seedkeys[array_rand($seedkeys)];
}

You could do it in MySQL (assuming that the data for the array starts from MySQL). Be aware this is simple, but not that efficient (See Jan Kneschke's post)...

SELECT * FROM `foo` ORDER BY RAND() LIMIT 1000;
Sunday, September 4, 2022
 
tho_ho
 
3
$im = imagecreatefromstring($user_design);
imagefilter($im, IMG_FILTER_GRAYSCALE);
imagefilter($im, IMG_FILTER_CONTRAST, -1000);
imagepng($im, 'path/filename.png');
imagedestroy($im);

How do you convert an image to black and white in PHP

Saturday, October 22, 2022
 
4

Shuffle it with shuffle():

shuffle($xbb);

Searching Google for php shuffle array will give you tons of results as well, by the way.

Friday, September 9, 2022
2

The first block of code uses a numpy.random.* function. numpy.random.* functions (including numpy.random.binomial) make use of a global random generator object which is shared across the application.

The second block of code creates a random generator object with default_rng() and uses that object to generate random numbers without relying on global state.

Note that numpy.random.binomial (in addition to other numpy.random.* functions) is now a legacy function as of NumPy 1.17; NumPy 1.17 introduces a new random number generation system, which is demonstrated in the second block of code in your question. It was the result of a proposal to change the RNG policy. The desire to avoid global state was one of the reasons for the change in this policy.

Saturday, October 15, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :