samedi 21 octobre 2017

PHP: Generate random numbers

today my friend raise a critical challenge in-front of me (critical, bcoz still i can't solve it) "Generate random number in PHP" :)

Let me explain you the hidden parts of this question with a simple scenario:

Think we have a dial-pad that consist 1-9 keys in 3 rows & 3 columns:

 ---------------------------
|                           |
|     1       2      3      |
|                           |
|     4       5      6      |
|                           |
|     7       8      9      |
|                           |
 ---------------------------

Now, we have to generate non-repeating random numbers based on provided length, but, using these criteria: 1: generated number should never consist the previous number in same row, 2: numbers in the first row, never followed by the third row number & vice-versa, 3: first-column or last-column number should never followed by the third-column or first-column number 4: ...

meanwhile, example generated numbers can be (length = 9): 12369874/5, 142536987 etc (length = 6): 987532 etc

I tried to do this with rand():

      $chars = "123456789";
      $length = 9;
      $clen   = strlen( $chars )-1;
      $id  = '';

      for ($i = 0; $i < $length; $i++) {
              $id .= $chars[mt_rand(0,$clen)];
      }
      return ($id);

but, still no luck...

So, can you solve this question...

Thanks & Regards




Aucun commentaire:

Enregistrer un commentaire