Generate unique random numbers from 10000000 to 99999999
I need to create unique random contacts using only numbers. I need to produce from 10,000,000 to 99,999,999. I need to create 100,000 contacts
Here's the code I'm currently using:
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $quantity);
}
print_r( UniqueRandomNumbersWithinRange(10000000,99999999,100000));
This code still works on my server using 50,000 but not 100,000 items. Can you help me, is there any code that can produce this many unique numbers without using too much memory on the server?
source to share
I believe this should do the trick for you:
<?php
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$i = 0;
$numbers = array();
while( $i <= $quantity ){
$numbers[$i] = mt_rand($min, $max);
$i++;
}
print_r( $numbers );
}
UniqueRandomNumbersWithinRange(10000000,99999999,100000);
?>
As per the comment on my answer, it is possible to use multiple keys containing the same output. This code will eliminate duplicates, but it takes a lot more time:
<?php
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$i = 0;
$numbers = array();
while( $i <= $quantity ){
$number = mt_rand( $min, $max );
if( !in_array( $number, $numbers ) ){
$numbers[$i] = $number;
$i++;
}
}
print_r( $numbers );
}
UniqueRandomNumbersWithinRange(10000000,99999999,100000);
?>
source to share
Small idea; make a range ($ min, $ quantity) and then multiply all the generated numbers by $ max / $. This would drastically shorten your array of numbers and keep the correct range.
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$numbers = range(0, $quantity);
shuffle($numbers);
array_walk($numbers, function(&$value, $key, $params) {
$value = floor($params[0] + $value * ($params[1]-$params[0]) / $params[2]);
}, array($min, $max, $quantity));
return $numbers;
}
print_r( UniqueRandomNumbersWithinRange(10000000,99999999,100000));
source to share
range()
uses only a lot of memory; you create an array of 90,000,000 int
values, each containing 8 bytes on your 64-bit machine. This makes it a 686MB array.
So, we need to generate each number ourselves and check if it is already in your result array (to ensure that each number is unique)
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
if ($max - $min < $quantity * 10) return false;
$unique_numbers = array();
while (count($unique_numbers) < $quantity) {
$random_number = mt_rand($min, $max);
if (!in_array($random_number, $unique_numbers)) $unique_numbers[] = mt_rand($min, $max);
}
return $unique_numbers;
}
The first line inside the function checks to see if there are enough numbers between $min
and $max
to generate $quantity
unique numbers; otherwise we get an infinite loop. I added a factor of 10, so there is room for randomness;)
source to share