Solved

Generating a set of random unique numbers

Posted on 2016-11-17
6
32 Views
1 Endorsement
Last Modified: 2016-11-18
I want to be able to administer quiz questions in a random unique order. I think one way to do this would be to use the array shuffle function, but I read that it was not truly random.

I thew together a quiz and wrote the function below. Is the rand function truly random? I looked at the manual and I saw random_int but it said "pseudo random".

I'm trying to quit smoking and doing a poor job articulating myself but I hope this is enough to understand what I'm trying to do.

What about mt_rand? http://php.net/manual/en/function.mt-rand.php

If I wanted to write professional level code would I be better off writing a function that generates a truly random number?

How would I go about that, please don't tell me everything or give me something complete, but if you could get me started thinking I would appreciate it (even if I use mt_rand I think I should try to understand how to generate a random number).

Thank you very much.

<?php

function generateNumbers($max) {
  $number = new SplFixedArray($max);
  $j = 0;
  $number[$j] = rand(1, 68);
  $j++;
  $loopLimit = $max - 1;
  
  while ($j <= $loopLimit) {
    $generatedNumber = rand(1, $max);
    for ($i = 0; $i <= $j; $i++) {
      if ($number[$i] == $generatedNumber) {
        break;
      }
      elseif ($i == $j) {
        $number[$j] = $generatedNumber;
        $j++;
        break;
        }
      }
    }
    return $number;
}

?>

Open in new window

1
Comment
Question by:burnedfaceless
  • 4
6 Comments
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 41892127
PHP my_rand() is good enough.  You might also want to consider using range() and shuffle().  You can shuffle more than once, if you'd like.

In an application like this, don't let the great be the enemy of the good.  You're not in need of cryptographic excellence.  You just need random-enough numbers!
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 500 total points
ID: 41892135
You might take some inspiration from this.  You could repackage it as a function that returns the array of numbers.

Also, congratulations on the decision to quit smoking.  It's not easy, but it's worth it for all kinds of reasons.  I'm speaking as a born-again non-smoker.  You're doing the right thing.
https://iconoun.com/demo/temp_burnedfaceless.php
[code]<?php // demo/temp_burnedfaceless.php.php
/**
 * https://www.experts-exchange.com/questions/28983854/Generating-a-set-of-random-unique-numbers.html
 */
error_reporting(E_ALL);
echo '<pre>';

$kount = 32;
while($kount)
{
    $kount--;
    
    $row = range(1,24);
    shuffle($row); // RANDOMLY ORDERED UNIQUE NUMBERS FROM 1 -- 24
    
    $txt = implode(',', $row);
    print_r($txt);
    echo PHP_EOL ;
}

Open in new window

[/code]
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 500 total points
ID: 41892140
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 34

Expert Comment

by:gr8gonzo
ID: 41892213
1. How important is it that each number be unique?

2. If it's critical, then is there a "lifespan" to the number? For example, if you generate "3", will it be okay to generate "3" again an hour from now when you run your script again, or can "3" never, ever be used again?

3. How important is it that each number be truly random, and are there any min/max requirements on the number? For example, if you had "1", "2", "3", "123213429676734", would that be okay?

4. Most importantly of all, what's the number ultimately going to be used for? This question along might allow us to provide some better advice/guidance.
2
 

Author Closing Comment

by:burnedfaceless
ID: 41892469
Thanks for posting but Ray managed to translate my jibberish and answer my question - I'm letting the great be the enemy of the good when what I've written serves the purpose at hand (basically randomizing all quizzes and multiple choice selectors, but more crucially some scripts will contain material that will need to be treated like flashcards, and this allows me to shuffle the flashcards which is important, more important the more you do). I do think I can improve on this - if a subject is learned through thinking through it (rather than rote memorization) then it's not important to isolate individual sections - you can run through the entire material because they're working on thought processes and the memorization will come for some, but ultimately the way to learn that material is to work through it understanding how to solve it, then the memorization will come. Even for that kind of material I think you can tag a particular one that someone had trouble with and allow them to review it sooner, I'll have to test it out - bunch of music theory that I've more or less forgotten so it should be a good test.

Anyways I bummed a smoke - my brain is working again. Thanks for the encouragement Ray, I got back on Chantix. Made it one month with Chantix then the cravings came back (really weird after about 10 days) and I thought I could handle them but they got so strong I had to smoke.

I'll do what it takes to quit. Another try makes me that much more likely to stop.

[b]Ray I'm not sure if you're reading this because it's quite the essay but I'm going to try to do frontend work (unless I got a job doing something else) soon. If I get a job in town it would be ideal because I could attend school and take the two intro level programming classes - I am 90% sure they are Java - then I could get the PHP class to count as an upper level elective and have a degree. I want to be able to work through this book http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.691.3733&rep=rep1&type=pdf. Should I learn C++ right now along with HTML5 and CSS3? Is C++ a good language to know?[/b]
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41892777
About those cravings... They go on for at least a year, so don't be surprised or disappointed that a month or three is not enough to break the chains.  Persistence is a virtue.  I found the cravings to be triggered by associative events.  Even a full year after quitting, I went water skiing and when I jumped back into the boat I had a sudden and familiar craving for the cigarette I had always smoked after skiing!  It took me a lot of tries to stop completely.  Everyone I know who has quit has had a similar experience.  You'll get there, even if the path is not always straight to the goal.

About C++ ... Sure, it's definitely worth understanding, at least well enough to read code and make an educated guess about what it is doing.  You don't have to develop a depth of knowledge, but it's one of many useful languages that can help to shape your thinking about information problems.  From a practical viewpoint, a depth of knowledge in JavaScript will be very useful.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now