Awkward criteria when generating random sequence - php

What I need to do to generate a sequence of non-repeating integers within a given range that meets the specific criteria that I have?
Here are the criteria:
Use only the numbers between 1 and MAX (let's say 9).
Numbers cannot repeat within the sequence except:
2a. Two of the first 5 numbers from the sequence must be repeated.
2b. These two numbers must be repeated at random points within the last 5 places in the final sequence (the last 5 includes the repeats).
For example:
SET: 1,2,3,4,5,6,7,8,9
Random Sequence (with repeats):
2,4,6,9,3,1,5,2,8,7,3
r, , , ,r, , ,x, , ,x
Here I have indicated the numbers that were randomly selected to be repeated (out of the first 5 in the random sequence) with an r and the insertion points where they were randomly placed (into the last 5 of the final sequence) with an x.
Any help in figuring this out is much appreciated. Actual use will be a bit more complicated than this, but I know what I will need to do once I can get this far.
Edit
To clarify a little more, I have 1-20, and I need a 22 digit random sequence. Every number must be used, two will be used twice as discussed in my original post. I chose 10 above to simplify a little. I should be able to adapt the logic you've all given.

I assume when you say "non-repeating" you mean "distinct" (unique) as opposed to "eventually becomes periodic" (as in "the digits of pi do not repeat")
Generate n distinct integers in your range.
Pick two from the first 5. Call these a and b.
Remove the last 3 from the list.
Insert a at position 0, 1, 2, or 3 in the sublist.
Insert b at position 0, 1, 2, 3, or 4 in the sublist.
Add the sublist back to the end of the list.
Removal of the sublist is not necessary but makes it easier to conceptualize.
Not obvious what to do if n+2 is less than 10. In particular, this algorithm may crash for n < 5 and return the wrong result for n=7.

If I understand you correctly, you have 1 to N random numbers that must be used in a 10-set permutation with some specific criteria about repeats. In php, I suggest this (not counting php-internals) O(n) solution:
//Generate a full list of keys
$source = range(1, MAX);
//NOTE: if MAX < 10, you must pad the array
//Get a random group of 10 of the keys
$input = array_rand(array_flip($source), 10);
//Shuffle (can be done later as well; this is the randomization).
//array_rand() does not change order.
shuffle($input);
//Select the first of 5 that must be repeated in the last 5
$one = rand(0, 4);
$onev = $input[$one];
//Remove this array key to prevent collisions with the second of 5
$input = array_diff($input, array($onev));
//Select a random index in the last 5 to be replaced with $one
$rep = rand(5, 9);
$repv = $input[$rep];
//Remove this array key to prevent collisions with the other to-be-replaced
$input = array_diff($input, array($repv));
//Acquire the new keys list of input now that two elements have been removed
$keys = array_slice(array_keys($input), 0, 3);
//Select the second-of-5 to replace in the last 5. No worry of collision now.
$two = array_rand($keys, 1);
$two = $keys[$two];
//Select the second from the last-of-5 to be replaced by $two
//No worry of collision because the other index is removed.
$keys = array_slice(array_keys($input), 4, 8);
$rept = array_rand($keys, 1);
$rept = $keys[$rept];
//Replace one of the last-of-five with one of the first-of-five
$input[$rept] = $input[$two];
//Restore removed keys as well as perform replacement of other last-of-five
$input[$one] = $onev;
$input[$rep] = $onev;
//re-randomize based on shuffle
ksort($input);
No loops, no conditionals.

A word of warning on this solution. I wouldn't use it for a large set of numbers. If I were doing this same solution for a much larger set, I would use array_splice to drop chosen members from the array. As you get a much larger space, finding an unused number in your range becomes quite expensive, and demands a better solution than the brute force method below.
This will build half of your target set. You will call it twice, once for each half.
function build_half($min, $max, $num_elements, $arr = array() ){
while( count($arr) <= $num_elements)
{
$candidate = rand($min, $max);
if( !in_array($candidate, $arr))
{
array_push($arr, $candidate);
}
}
return $arr;
}
This will grab $this_many elements from the array.
function random_grab($arr, $this_many){ // don't try this on the subway
$nums_to_repeat = array();
// catch some edge cases...
if( $this_many > count($arr) )
{
return FALSE;
}
else if( $this_many == count($arr) )
{
return shuffle($arr);
}
while( count($nums_to_repeat) <= $this_many)
{
$rand_key = rand(0, count($arr) - 1);
if( ! in_array($arr[$rand_key], $nums_to_repeat))
{
array_push($nums_to_repeat, $arr[$rand_key]);
}
}
return $nums_to_repeat;
}
This is a fairly specialized case, but could be made more general by allowing the offset floor and ceiling to be passed in as parameters. For your problem they would be 5 and 9, so we just derive them directly.
function random_insert_2nd_half($target, $source){
$offsets_consumed = array();
$num_elements = count($target);
while( count($source) > 0 )
{
$offset = rand( ($num_elements/2), $num_elements - 1);
if( ! in_array( $offset, $offsets_consumed)
{
$arr[$offset] = array_pop($nums_to_repeat);
}
}
}
Ok so after having done all that, let's put it to work.
// Generate the first half of the array
$my_array = $repeated_nums = array();
$my_array = build_half(1, 10, 5);
// then grab the 2 random numbers from that first half.
$repeated_nums = random_grab($my_array, 2);
// So now we have our random numbers and can build the 2nd half of the array.
// we'll just repeat the call to the first function.
$my_array = build_half(1, 10, 5, $my_array);
// Then swap out two of the values in the second half.
$my_array = random_insert_2nd_half($my_array, $repeated_nums);
// at this point $my_array should match what you are looking for.

Hope this gets you on your way:
$max = 20; // max value
$repeats = 2; // numbers to be repeated
$nums = range(1, $max);
shuffle($nums);
$halfPoint = ceil($max / 2);
$firstHalf = array_slice($nums, 0, $halfPoint);
$repeaters = array_intersect_key($firstHalf, array_flip(array_rand($firstHalf, $repeats)));
$secondHalf = array_merge(array_slice($nums, $halfPoint), $repeaters);
shuffle($secondHalf);
$result = array_merge($firstHalf, $secondHalf);
var_dump(join(',', $result));

To generate distinct numbers within a range you can use something like this:
$arr_num = array();
while(count($arr_num)<=7)
{
$num = rand(1, 9);
if (!in_array($num, $arr_num))
{
$arr_num[] = $num;
}
}
$arr_num now has 8 distinct elements. Pick five elements of the array:
for ($i=0; $i<=4; $i+=1)
{
$new_arr[$i] = $arr_num[$i];
}
Now pick two numbers from $new_arr numbers:
$r1 = array_rand($new_arr);
$r2 = array_rand($new_arr);
Now you can insert these numbers into the original array at two of the last random positions. Hope it helped!

$max = 15;
$array = array(1, $max);
for($x = 1; $x <= $max; $x++)
{ $array[$x] = rand(1, $max); }
$firstDup = $array[rand(1,5)];
$secondDup = $firstDup;
do { $firstDup = $array[rand(1,5)];
} while($firstDup == $secondDup);
do { $array[rand($max-5,$max)] = $firstDup;
} while(!in_array($firstDup,array_slice($array,$max-5,5)));
do { $array[rand($max-5,$max)] = $secondDup;
} while(!in_array($secondDup,array_slice($array,$max-5,5)));

Related

How to limit duplicate values in an array

First of all, I apologize for my lack of English. I hope you do understand what I'm trying to explain here.
So basically I need to build a function that would limit the number of duplicate values inside an array.
The reason I need to do this is that I'm building a system that would divide numbers into groups and every group has to have the same amount of numbers.
EDIT: Random number represents the group number.
I've written a function do this but for some reason, it is not working properly.
function jagaTiimid($max, $liiget, $tArvLength, $tArv){
$tiimid = []; //Starting array
for($z=0;$z<$liiget;$z++){
$numbers = [];
$rn = randomNumber($tArvLength, $tArv, $numbers); //Generate a random number for a group, etc group 1, group 2, group 3
$mitu = countInArray($tiimid, $rn); //Check how many times that number has occured in array
if($mitu == $max){ //If it equals to maximum number of times then...
$rnUus = randomNumber($tArvLength, $tArv, $numbers); //generate a new random number
while($rnUus == $rn){
$numbers = [];
$rnUus = randomNumber($tArvLength, $tArv, $numbers);
} //loop until the new generated number doesn't equal to old rn.
$tiimid[] = $rnUus; //if it doesn't equal to $rn then push into array
}else{
$tiimid[] = $rn;
}
}
return $tiimid;
}
For some reason the number still occures more than it is suppose to.
Basically how it shouldn't end up is.
As you can see, one group(group 2) occurs more times than other group but it should be equal for both groups.
EDIT: CountInArray();
function countInArray($array, $what) {
$count = 0;
for ($i = 0; $i < count($array); $i++) {
if ($array[$i] === $what) {
$count++;
}
}
return $count;
}
When the first random pick hits a number that is already used $liiget times, the inner loop kicks in, but it does not check whether the newly generated random number already occurs $liiget times.
For efficiency I would keep track of the number of times a number has been used. Also, you could benefit from a safety net, in case there really is no number any more that would not exceed the maximum recurrence.
It is not necessary to have a nested loop. The code would look like this:
function jagaTiimid($max, $liiget, $tArvLength, $tArv){
$tiimid = []; //Starting array
$counts = []; // Helper for quick count
$tries = 0; // Counter to avoid infinite looping
while (count($tiimid) < $liiget && $tries++ < 100) {
$numbers = [];
$rn = randomNumber($tArvLength, $tArv, $numbers); //Generate a random number for a group, etc group 1, group 2, group 3
if (!isset($counts[$rn])) $counts[$rn] = 0; // initialise on first occurence
if ($counts[$rn] < $max) {
$tiimid[] = $rn; // add it to the result
$counts[$rn]++; // ... and adjust the count
$tries = 0; // reset the safety
}
}
return $tiimid;
}
replace while($rnUus == $rn) with while(countInArray($tiimid, $rnUus) >= $max)
– Ilya Bursov

How to randomly generate a number from a range of numbers but exclude some numbers? [duplicate]

This question already has answers here:
PHP rand() exclude certain numbers
(10 answers)
Closed 6 years ago.
How would I generate a random number from a range of numbers between 1 and 10 while excluding an array of numbers e.g. 4,5,6.
$exclude = array(4,5,6);
The following code allows to generate random numbers within a range however only for a single number and not an array of numbers
function randnumber() {
do {
$numb = rand(1,10);
} while ($varr == 4);
return $numb;
}
Create a loop that iterates until a generated random number using rand function is not in array. If the generated number is found in array, again another random number is generated.
do {
$number = rand(1,10);
} while(in_array($number, array(4,5,6)));
echo $number;
or
while(in_array(($number = rand(1,10)), array(4,5,6)));
echo $number;
You can use it like a function too:
<?php
function randomNo($min,$max,$arr) {
while(in_array(($number = rand($min,$max)), $arr));
return $number;
}
echo randomNo(1,10,array(4,5,6));
The above function, does the same process, in addition, you can reuse the code. It gets minimum and maximum number and the array of values to exclude.
Finally,
without loop, but with recursive function. The function generates a random number and returns if it is not found in the exclude array:
function randomExclude($min, $max, $exclude = array()) {
$number = rand($min, $max);
return in_array($number, $exclude) ? randomExclude($min, $max, $exclude) : $number;
}
echo randomExclude(1,10,array(4,5,6));
<?php
$exclude = array(4,5,6); // The integers to excluded
do
{
$x = rand(1, 10); // Generate a random integer between 1 and 10
}while(in_array($x, $exclude)); // If we hit something to exclude, try again
echo $x; // A random integer not excluded
?>
It would be wise to check if not all inputs are excluded to avoid infinite loops
You can simply do this, using array functions like this:
function my_rand($min, $max, array $exclude = array())
{
$range = array_diff(range($min, $max), $exclude);
array_shuffle($range);
return array_shift($range);
}
Some time ago I also wanted to become rid of these nasty little while loops. Reduced to fit your version of the problem, my approach would be to:
first generate a random number which in range (10 - 3) to indicate the position of the number to be generated in the hypothetical list of numbers in the desired range excluding {4,5,6}
second increment this value by the lower range (1)
third increment by 1 for every number in the set {4,5,6} it is equal to or greather (in order from the smallest to the highest number in that set)
So, all in all I'd basically stretch and blurr the hypothetical set of numbers the generated random value can be to fit into the possible outcomes.
$total = range(0,10);
$exclude = range(4,6);
$include = array_diff($total, $exclude);
print_r (array_rand($include));

How to generate a random number with fixed length only with 0's and 1's and a fixed amount of 1's?

I did some research, but didn't found any solution for my question.
What I want to archive:
Generate a random number out of 0's ($min) and 1's ($max), but with a fixed amount ($many) of 1's in the random number. The random number should have a length of 6 as in my while loop (while($xLoop <= 6)).
Here is my current code:
$min = 0;
$max = 1;
$many = 3;
$xLoop = 1;
while($xLoop <= 6) {
$nRand = mt_rand($min,$max);
if($nRand == 1){ //if random number comes out number 1
$many--; // Prevent number 1 more then $many...
//Do something...
}else{ //if random number comes out not number 1
//Do something and still looping until get 6 times
}
echo $nRand.' - '.$many.'</br>'; //For debugin... i want to see how many number 1 comes out.
$xLoop++;
}
It will loop 6 times, so we have a random number of the length 6, but I want a fixed amount of 1's in my random number, which is $many (here 3). And the rest filled with 0's until we reach the length 6.
How can I fix this code? Or is there a simpler way?
This should work for you:
No need for a loop. Just first fill an array with 1's $many times. Then array_merge() the array with the 0's which you fill up until $length elements.
At the end just shuffle() the array and implode() it to print it
<?php
$min = 0;
$max = 1;
$many = 3;
$length = 6;
$arr = array_fill(0, $many, $min);
$arr = array_merge($arr, array_fill($many, $length-$many, $max));
shuffle($arr);
echo implode("", $arr);
?>
possible output:
011010

avoid duplicates amongst creating random numbers

if I want to create some variables that contain random numbers that differ from each other, right now this is the method i'm using(in this case i'm using PHP to set example):
while($rand1==$rand2 or $rand2==$rand3 or $rand3==$rand4 or $rand4==$rand5 or
rand1==$rand3 or $rand2==$rand4 or $rand3==$rand5 or $rand5==$rand4 or
$rand1==$rand4 or $rand2==$rand5 or $rand4==$rand3 or $rand5==$rand3 or
$rand1==$rand5 or $rand3==$rand2 or $rand4==$rand1 or $rand5==$rand2 or
$rand2==$rand1 or $rand3==$rand1 or $rand4==$rand2 or $rand5==$rand1):
$rand1=rand(1,1000);
$rand2=rand(1,1000);
$rand3=rand(1,1000);
$rand4=rand(1,1000);
$rand5=rand(1,1000);
endwhile;
so, if I want to create 100 variables all with differing numbers,I wouldn't want to use this method for obvious reason. Any better alternatives?
put them in an array and search the array.
$arr = array();
$arr[] = rand(1,1000);
You can just loop through as many as you like
This gives you 5 unique randoms in the given range:
$a = range(1, 1000);
shuffle($a);
$randoms = array_slice($a, 0, 5);
(I assume performance is not critical).
In a more efficient way,
$randoms = array();
while(count($randoms) < 5)
$randoms[rand(1, 1000)] = 1;
$randoms = array_keys($randoms);
From your code I assume you need numbers from 1 to 1000 and you don't want duplicates. Here's a way not to loop through your random numbers every time since it's time consuming if you need 100 random numbers:
$pool = range(1, 1000);
$numbers = array();
for ($i = 0; $i < 5; $i++) {
$random = rand(0, count($pool) - 1);
$numbers[$i] = $pool[$random];
$pool[$random] = array_pop($pool);
}
Just change 5 to whatever you need or use a variable.
This works if you have a pool of numbers to extract from, that's why we pop the last element and we replace the number we extracted already to avoid duplicates. We have to count the elements in the pool each time because it shrinks by one element on each iteration. You could probably save the initial value and decrement it based on $i if your pool is not a native array so you don't waste time counting and you just do basich math.

Create numbers within an array that add up to a set amount

I'm fairly new to PHP - programming in general. So basically what I need to accomplish is, create an array of x amount of numbers (created randomly) whose value add up to n:
Let's say, I have to create 4 numbers that add up to 30. I just need the first random dataset. The 4 and 30 here are variables which will be set by the user.
Essentially something like
x = amount of numbers;
n = sum of all x's combined;
// create x random numbers which all add up to n;
$row = array(5, 7, 10, 8) // these add up to 30
Also, no duplicates are allowed and all numbers have to be positive integers.
I need the values within an array. I have been messing around with it sometime, however, my knowledge is fairly limited. Any help will be greatly appreciated.
First off, this is a really cool problem. I'm almost sure that my approach doesn't even distribute the numbers perfectly, but it should be better than some of the other approaches here.
I decided to build the array from the lowest number up (and shuffle them at the end). This allows me to always choose a random range that will allows yield valid results. Since the numbers must always be increasing, I solved for the highest possible number that ensures that a valid solution still exists (ie, if n=4 and max=31, if the first number was picked to be 7, then it wouldn't be possible to pick numbers greater than 7 such that the sum of 4 numbers would be equal to 31).
$n = 4;
$max = 31;
$array = array();
$current_min = 1;
while( $n > 1 ) {
//solve for the highest possible number that would allow for $n many random numbers
$current_max = floor( ($max/$n) - (($n-1)/2) );
if( $current_max < $current_min ) throw new Exception( "Can't use combination" );
$new_rand = rand( $current_min, $current_max ); //get a new rand
$max -= $new_rand; //drop the max
$current_min = $new_rand + 1; //bump up the new min
$n--; //drop the n
$array[] = $new_rand; //add rand to array
}
$array[] = $max; //we know what the last element must be
shuffle( $array );
EDIT: For large values of $n you'll end up with a lot of grouped values towards the end of the array, since there is a good chance you will get a random value near the max value forcing the rest to be very close together. A possible fix is to have a weighted rand, but that's beyond me.
I'm not sure whether I understood you correctly, but try this:
$n = 4;
$max = 30;
$array = array();
do {
$random = mt_rand(0, $max);
if (!in_array($random, $array)) {
$array[] = $random;
$n--;
}
} while (n > 0);
sorry i missed 'no duplicates' too
-so need to tack on a 'deduplicator' ...i put it in the other question
To generate a series of random numbers with a fixed sum:
make a series of random numbers (of largest practical magnitude to hide granularity...)
calculate their sum
multiply each in series by desiredsum/sum
(basicaly to scale a random series to its new size)
Then there is rounding error to adjust for:
recalculate sum and its difference
from desired sum
add the sumdiff to a random element
in series if it doesnt result in a
negative, if it does loop to another
random element until fine.
to be ultratight instead add or
subtract 1 bit to random elements
until sumdiff=0
Some non-randomness resulting from doing it like this is if the magnitude of the source randoms is too small causing granularity in the result.
I dont have php, but here's a shot -
$n = ; //size of array
$targsum = ; //target sum
$ceiling = 0x3fff; //biggish number for rands
$sizedrands = array();
$firstsum=0;
$finsum=0;
//make rands, sum size
for( $count=$n; $count>0; $count--)
{ $arand=rand( 0, $ceiling );
$sizedrands($count)=$arand;
$firstsum+=$arand; }
//resize, sum resize
for( $count=$n; $count>0; $count--)
{ $sizedrands($count)=($sizedrands($count)*$targsum)/$firstsum;
$finsum+=$sizedrands($count);
}
//redistribute parts of rounding error randomly until done
$roundup=$targsum-$finsum;
$rounder=1; if($roundup<0){ $rounder=-1; }
while( $roundup!=0 )
{ $arand=rand( 0, $n );
if( ($rounder+$sizedrands($arand) ) > 0 )
{ $sizedrands($arand)+=$rounder;
$roundup-=$rounder; }
}
Hope this will help you more....
Approch-1
$aRandomarray = array();
for($i=0;$i<100;$i++)
{
$iRandomValue = mt_rand(1000, 999);
if (!in_array($iRandomValue , $aRandomarray)) {
$aRandomarray[$i] = $iRandomValue;
}
}
Approch-2
$aRandomarray = array();
for($i=0;$i<100;$i++)
{
$iRandomValue = mt_rand(100, 999);
$sRandom .= $iRandomValue;
}
array_push($aRandomarray, $sRandom);

Categories