Jump to content

Help need with random number problem


lxndr

Recommended Posts

Can anyone help me with the following coding problem.

I need to write a php function that can generate an array of non duplicate random numbers within a given range BUT also not have any particular array element contain its only position, ie.  element 1 of the array can't contain 1, element 2 cant's contain 2 etc.

For example, for a 5 element array with random numbers between 1 and 5, the following would be OK:

$array[1]: 3
$array[2]: 1
$array[3]: 5
$array[4]: 2
$array[5]: 4

but the following would NOT be OK:

$array[1]: 5
$array[2]: 1
$array[3]: 3
$array[4]: 2
$array[5]: 4

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/29268-help-need-with-random-number-problem/
Share on other sites

[quote author=mjdamato link=topic=117158.msg477755#msg477755 date=1165114533]
Hmm... Do you want random numbers or do you want non-repeating numbers as in your example? And is the range of numbers always the same as the number of items in the array and do the arrays always start at 1 and not 0?
[/quote]

Non-repeating random numbers
The range of numbers is always the same as the number of array elements, ie. 40 array elements would be numbers 1 to 40.
The numbers always start at 1 and go up consequetively, ie. 1,2,3,4 etc


..
Too easy. Give me something hard:

[code]<?php

$maxValue = 5;

$randomValues = array();
for ($i=1; $i<=$maxValue; $i++) {
  $tmp = rand(1, $maxValue);
  while ($tmp == $i || in_array($tmp, $randomValues) ) {
    $tmp = rand(1, $maxValue);
  }
  $randomValues[$i] = $tmp;
}

echo "<pre>";
print_r($randomValues);
echo "<pre>";
?>[/code]
[quote author=mjdamato link=topic=117158.msg477760#msg477760 date=1165115312]
Too easy. Give me something hard:

[code]<?php

$maxValue = 5;

$randomValues = array();
for ($i=1; $i<=$maxValue; $i++) {
  $tmp = rand(1, $maxValue);
  while ($tmp == $i || in_array($tmp, $randomValues) ) {
    $tmp = rand(1, $maxValue);
  }
  $randomValues[$i] = $tmp;
}

echo "<pre>";
print_r($randomValues);
echo "<pre>";
?>[/code]
[/quote]

That's great.  Thanks muchly !

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.