Generate an array in PHP of random number not close to the X previous element - php

I want to generate in PHP an array of random numbers, but each number should not be the same as any of the X (for example 2 ) numbers bofore it and not even close to any of them by a define range (for example 5).
So for example:
I need numbers between 1 and 100
i've set my "range" to 5
the first two generated number are 20 and 50.
the third number will be a random number between 1 and 100, excluding all the numbers between 15 and 25, and between 45 and 55.
I can't figure out a function to achieve it. Ideally I want to call something like this:
getRandomNumbers( $min, $max, $previous, $range);
where $previous is the number of previous elements to take in consideration when generating the next one and $range is the "proximity" to those number where I don't want the next number to be.
I hope I explained in a decent way my request. :) Please, add a comment if you have any question about it.

I just came up with this:
function getRandomNumbers($min, $max, $previous, $range) {
static $generated = array();
$chunk = array_slice($generated, -$previous);
// Added this infinite loop check to save you some headache.
if (((($max - $min + 1) / (($range * 2) + 1)) + 1) <= $previous) {
die("Values set have the potential of running into an infinite loop. Min: $min, Max: $max, Previous: $previous, Range: $range");
}
while(true) {
$number = rand($min, $max);
$found = true;
foreach ($chunk as $value) {
if (in_array($number, range($value-$range, $value+$range))) {
$found = false;
}
}
if ($found) {
$generated[] = $number;
return $number;
}
}
}
Test it using this:
for ($i = 1; $i < 25; $i++) {
echo getRandomNumbers(1, 100, 5, 5) . "<br />";
}
PHPFiddle Link: http://phpfiddle.org/main/code/51ke-4qzs
Edit: Added a check to prevent a possible infinite loop. For example: if you set the following values:
$min = 1;
$max = 100;
$previous = 5;
$range = 12;
echo getRandomNumbers($min, $max, $previous, $range);
Then let's say, in a really unfortunate situation it would generate 13, 38, 63 and 88. So the 5th number cannot be anything between 1 and 25, 26 and 50, 51 and 75, 76 and 100. So it would result in an infinite loop. I've updated the PHPFiddle link as well.

getRandomNumbers( $previous, $range ) {
//I'm assuming that previous will be an array of your previous X that you don't want to be close to
$num = getRandomNumber() //However you are doing this now
foreach( $previous as $key => $value ) {
if ( ( $value - $range ) > $num && ( $value + $range ) < $num ) {
return getRandomNumbers($previous, $range);
}
}
//You need to also replace a value in previous
return num;
}

Related

Getting nth-child with an offset in PHP with modulus

When iterating through a loop, I've used the modulus operator in an if statement to obtain nth results pretty easily like this:
// Get 5th item in series
if ($variable->array_item % 5 == 0) {
echo $variable->array_item;
}
How do you do get the 5th item in a series with an offset of 3 (ie, 3,8,13,18,23,etc.)?
I've seen a couple of methods but I'm looking for a canonical answer and I really don't see one on S.O. right now.
Your code specifically requests numbers that are evenly divisible by 5, whereas what you want are numbers 3, 8, 13, 18, 23, etc. This is easy enough to do using almost identical code to what you have:
// set up some test data
$testArray = [];
for ($i = 1; $i <= 30; ++$i) {
$testArray[$i] = "Testing {$i}";
}
// here's where the actual work happens
foreach ($testArray as $key => $value) {
if ($key % 5 == 3) { // <-- note 3, not 0
echo "Found $value\n";
}
}
$iterator = 0;
$step = 3;
while($iterator < count($collection))
{
echo $collection[$iterator]
$iterator += $step
}

How to generate random numbers to produce a non-standard distributionin PHP

I've searched through a number of similar questions, but unfortunately I haven't been able to find an answer to this problem. I hope someone can point me in the right direction.
I need to come up with a PHP function which will produce a random number within a set range and mean. The range, in my case, will always be 1 to 100. The mean could be anything within the range.
For example...
r = f(x)
where...
r = the resulting random number
x = the mean
...running this function in a loop should produce random values where the average of the resulting values should be very close to x. (The more times we loop the closer we get to x)
Running the function in a loop, assuming x = 10, should produce a curve similar to this:
+
+ +
+ +
+ +
+ +
Where the curve starts at 1, peeks at 10, and ends at 100.
Unfortunately, I'm not well versed in statistics. Perhaps someone can help me word this problem correctly to find a solution?
interesting question. I'll sum it up:
We need a funcion f(x)
f returns an integer
if we run f a million times the average of the integer is x(or very close at least)
I am sure there are several approaches, but this uses the binomial distribution: http://en.wikipedia.org/wiki/Binomial_distribution
Here is the code:
function f($x){
$min = 0;
$max = 100;
$curve = 1.1;
$mean = $x;
$precision = 5; //higher is more precise but slower
$dist = array();
$lastval = $precision;
$belowsize = $mean-$min;
$abovesize = $max-$mean;
$belowfactor = pow(pow($curve,50),1/$belowsize);
$left = 0;
for($i = $min; $i< $mean; $i++){
$dist[$i] = round($lastval*$belowfactor);
$lastval = $lastval*$belowfactor;
$left += $dist[$i];
}
$dist[$mean] = round($lastval*$belowfactor);
$abovefactor = pow($left,1/$abovesize);
for($i = $mean+1; $i <= $max; $i++){
$dist[$i] = round($left-$left/$abovefactor);
$left = $left/$abovefactor;
}
$map = array();
foreach ($dist as $int => $quantity) {
for ($x = 0; $x < $quantity; $x++) {
$map[] = $int;
}
}
shuffle($map);
return current($map);
}
You can test it out like this(worked for me):
$results = array();
for($i = 0;$i<100;$i++){
$results[] = f(20);
}
$average = array_sum($results) / count($results);
echo $average;
It gives a distribution curve that looks like this:
I'm not sure if I got what you mean, even if I didn't this is still a pretty neat snippet:
<?php
function array_avg($array) { // Returns the average (mean) of the numbers in an array
return array_sum($array)/count($array);
}
function randomFromMean($x, $min = 1, $max = 100, $leniency = 3) {
/*
$x The number that you want to get close to
$min The minimum number in the range
$max Self-explanatory
$leniency How far off of $x can the result be
*/
$res = [mt_rand($min,$max)];
while (true) {
$res_avg = array_avg($res);
if ($res_avg >= ($x - $leniency) && $res_avg <= ($x + $leniency)) {
return $res;
break;
}
else if ($res_avg > $x && $res_avg < $max) {
array_push($res,mt_rand($min, $x));
}
else if ($res_avg > $min && $res_avg < $x) {
array_push($res, mt_rand($x,$max));
}
}
}
$res = randomFromMean(22); // This function returns an array of random numbers that have a mean close to the first param.
?>
If you then var_dump($res), You get something like this:
array (size=4)
0 => int 18
1 => int 54
2 => int 22
3 => int 4
EDIT: Using a low value for $leniency (like 1 or 2) will result in huge arrays, since testing, I recommend a leniency of around 3.

How to compress an array?

Lets say, I have an array with 1000 values (integers). And I need from this array to have an array with f.e. 400 values (the number can be changed, f.e. 150, etc.).
So I need to return each 2.5th array value, i.e. 1st, 3rd, 6th, 8th, 11th, etc.
Is this somehow possible?
I dont need a code, I just need some way, how to do it.
EDITED:
My array is array of elevations (from another array with GPS coordinates). And I want to draw a 2D model of elevation. Lets say, my map will always have 400px width. 1px = 1 point of elevation. Thats why I need each 2.5th elevation value...
Like this:
You don't want the 2.5th one. You effectively want to divide the set into blocks of five and get the first and third from each set.
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
You want the first and third columns.
This is PHP, so we've got 0-based arrays.
We can divide it into groups of 5 using the modulo operator %. We can then see if the return value is 0 (i.e. it's in the first column) or 2 (i.e. it's in the third column).
I'm going to presume your array has numeric keys starting from 0.
// PHP 5.6
$filtered = array_filter($array, function($value, $key) {
$mod = $key % 5;
return ($mod === 0) || ($mod === 2);
}, ARRAY_FILTER_USE_BOTH);
// pre-PHP 5.6
$filtered = array();
foreach ($array as $key => $value) {
$mod = $key % 5;
if (($mod === 0) || ($mod === 2)) {
$filtered[$key] = $value;
}
}
var_dump($filtered);
How about using the modulo % operator?
Say you want to make 1000 into 200 values, loop through all the items in the array and keep a counter, if the counter % 5 == 0 then put that value into a new array, or if != 0 then remove from array. We use modulo 5 because 1000 / 200 = 5.
Below is the way to start with. It does not ensure that first and last elements are included in the output and, probably, has some other glitches. But since you requested the idea, here you go—array_reduce:
$a=[1,2,3,4,5,6,7,8,9,10,11,12]
$step = 2.5;
$i = 0;
$r = array_reduce($a, function($memo, $curr) use(&$i, $step) {
if($i === round($step * count($memo))) {
$memo[] = $curr;
}
$i++;
return $memo;
}, []);
print_r($r);
/*
Array
(
[0] => 1
[1] => 4
[2] => 6
[3] => 9
[4] => 11
)
*/
Hope it helps.
This should be pretty close to what you seem to be looking for. It will collect whichever values are closest (rounding down) to the float values.
$list = range(1,1000);
$targetSize = 300;
$new = array();
$step = count($list) / $targetSize;
$curStep = 0;
for( $i = 0; $i < count($list); $i++ ) {
$curStep++;
if( $curStep > $step ) {
$new[] = $list[ floor($i) ];
$curStep -= $step;
}
}
So this is it:
$arr = range(1, 1387); // f.e.
$cnt = 296; // f.e.
$new = array();
$max = count($arr);
$step = $max / $cnt;
for ($i = 0; $i < $max; $i += $step) {
$new[] = round($arr[(int)$i]);
}

PHP rand() exclude certain numbers

I have this:
<?php $n = rand(1,1600); echo $n ?>
I want to exclude from random numbers let's say 234, 1578 ,763 , 1274 and other numbers. How would I do that?
<?php
while( in_array( ($n = mt_rand(1,1600)), array(234, 1578 ,763 , 1274) ) );
Try like this
do {
$n = rand(1,1600);
} while(in_array($n, array(234, 1578 ,763 , 1274 ));
echo $n;
Check if the number is one that you don't want, if it is get a new random number.
function getRandomNumber() {
do {
$n = mt_rand(1,1600);
} while(in_array($n, array(234,1578, 763, 1274)));
return $n;
}
Always use cryptographically strong algorithms for generating random numbers:
/**
* #param int $from From number
* #param int $to To number
* #param array $excluded Additionally exclude numbers
* #return int
*/
function randomNumber($from, $to, array $excluded = [])
{
$func = function_exists('random_int') ? 'random_int' : 'mt_rand';
do {
$number = $func($from, $to);
} while (in_array($number, $excluded, true));
return $number;
}
var_dump(randomNumber(1, 100));
var_dump(randomNumber(1, 10, [5, 6, 7, 8]));
var_dump(randomNumber(1, 100, range(10, 90)));
I'd also recommend using the paragonie/random_compat library for compatibility in case of using multiple PHP versions.
Or avoid making loops with random (possibly infinite) running time:
/**
* Returns a random integer between $min and $max (inclusive) and
* excludes integers in $exarr, returns false if no such number
* exists.
*
* $exarr is assumed to be sorted in increasing order and each
* element should be unique.
*/
function random_exclude($min, $max, $exarr = array()) {
if ($max - count($exarr) < $min) {
return false;
}
// $pos is the position that the random number will take
// of all allowed positions
$pos = rand(0, $max - $min - count($exarr));
// $num being the random number
$num = $min;
// while $pos > 0, step to the next position
// and decrease if the next position is available
for ($i = 0; $i < count($exarr); $i += 1) {
// if $num is on an excluded position, skip it
if ($num == $exarr[$i]) {
$num += 1;
continue;
}
$dif = $exarr[$i] - $num;
// if the position is after the next excluded number,
// go to the next excluded number
if ($pos >= $dif) {
$num += $dif;
// -1 because we're now at an excluded position
$pos -= $dif - 1;
} else {
// otherwise, return the free position
return $num + $pos;
}
}
// return the number plus the open positions we still had to go
return $num + $pos;
}
This function chooses a random position and walks the exclusion array to find the free position. It's running time depends on the amount of numbers to exclude. If you want to exclude certain ranges, you may want to adapt the algorithm to take this into account.
As the volume of "blacklisted" integers approaches the volume of the full range of integers, it becomes increasingly compelling to take the advice of #regenschein.
A non-iterative approach might look like this:
$range = range(1, 1600);
$blacklist = [234, 1578, 763, 1274]; // 4 blacklisted versus 1600 full range is NOT compelling
$valids = array_diff($range, $blacklist);
echo array_values($valids)[rand(0, count($valids) - 1)];
// or
echo $valids[array_rand($valids)];
// the two approaches use different randomizers
Or if you'd be just as happy shuffling, you could do:
$blacklist = [234, 1578, 763, 1274];
$range = range(1, 1600);
$valids = array_diff($range, $blacklist);
shuffle($valids);
echo $valids[0];
*Note array_diff() is particularly great if you want to pass multiple blacklist arrays -- just comma-separate them.
For example:
var_export($valids = array_diff(range(1, 100), range(5, 50), range(61, 99), [55]));
Output:
array (
0 => 1,
1 => 2,
2 => 3,
3 => 4,
50 => 51,
51 => 52,
52 => 53,
53 => 54,
55 => 56,
56 => 57,
57 => 58,
58 => 59,
59 => 60,
99 => 100,
)
Another solution for this could be as follows:
function random_number($min, $max, $exclude)
{
$number = rand($min, $max);
if(in_array($number, $exclude))
{
random_number($min, $max, $exclude);
} else {
return $number;
}
}
$number = random_number(1,10, [2,5,6]);
I know this is a bit old,but I think what the op tries to do is shuffle the integers. If so the following method is better
$array = array(1,2,3,4,5,6,7);
shuffle($array);
This code will randomize the order of the array's exact elements without repetition and return the result inside the array itself.
You could create an array with valid numbers.
Then, your random number generation should return the index into that array.
If you don't have too many numbers to exclude, it is easier and faster to just retry if you find an unwanted number:
$n = 0;
while (in_array($n, array(0, 234, 1578 ,763 , 1274))) {
$n = rand(1,1600);
}
echo $n;

PHP: Next Available Value in an Array, starting with a non-indexed value

I've been stumped on this PHP issue for about a day now. Basically, we have an array of hours formatted in 24-hour format, and an arbitrary value ($hour) (also a 24-hour). The problem is, we need to take $hour, and get the next available value in the array, starting with the value that immediately proceeds $hour.
The array might look something like:
$goodHours = array('8,9,10,11,12,19,20,21).
Then the hour value might be:
$hour = 14;
So, we need some way to know that 19 is the next best time. Additionally, we might also need to get the second, third, or fourth (etc) available value.
The issue seems to be that because 14 isn't a value in the array, there is not index to reference that would let us increment to the next value.
To make things simpler, I've taken $goodHours and repeated the values several times just so I don't have to deal with going back to the start (maybe not the best way to do it, but a quick fix).
I have a feeling this is something simple I'm missing, but I would be so appreciative if anyone could shed some light.
Erik
You could use a for loop to iterate over the array, until you find the first that is greater than the one you're searching :
$goodHours = array(8,9,10,11,12,19,20,21);
$hour = 14;
$length = count($goodHours);
for ($i = 0 ; $i < $length ; $i++) {
if ($goodHours[$i] >= $hour) {
echo "$i => {$goodHours[$i]}";
break;
}
}
Would give you :
5 => 19
And, to get the item you were searching for, and some after that one, you could use something like this :
$goodHours = array(8,9,10,11,12,19,20,21);
$hour = 14;
$numToFind = 2;
$firstIndex = -1;
$length = count($goodHours);
for ($i = 0 ; $i < $length ; $i++) {
if ($goodHours[$i] >= $hour) {
$firstIndex = $i;
break;
}
}
if ($firstIndex >= 0) {
$nbDisplayed = 0;
for ($i=$firstIndex ; $i<$length && $nbDisplayed<$numToFind ; $i++, $nbDisplayed++) {
echo "$i => {$goodHours[$i]}<br />";
}
}
Which would give you the following output :
5 => 19
6 => 20
Basically, here, the idea is to :
advance in the array, until you find the first item that is >= to what you are looking for
get out of that first loop, when found
If a matching item was found
loop over the array, until either its end,
or you've found as many items as you were looking for.
You can also use the SPL FilterIterator. Though it's not the fastest solution there is, it has the advantage that you can "prepare" the iterator somewhere/anywhere and then pass it to a function/method that doesn't have to know how the iterator works on the inside, i.e. you could pass a completely different iterator the next time.
class GreaterThanFilterIterator extends FilterIterator {
protected $threshold;
public function __construct($threshold, Iterator $it) {
$this->threshold = $threshold;
parent::__construct($it);
}
public function accept() {
return $this->threshold < parent::current();
}
}
function doSomething($it) {
// no knowledge of the FilterIterator here
foreach($it as $v) {
echo $v, "\n";
}
}
$goodHours = array(8,9,10,11,12,19,20,21);
$it = new GreaterThanFilterIterator(14, new ArrayIterator($goodHours));
doSomething($it);
prints
19
20
21
As $goodHours is already sorted, that's something easy:
$next = 0;
foreach($goodHours as $test)
if($test > $hour && $next = $test)
break;
After that four-liner (that can be written in a smaller number of lines naturally), $next is either 0 if $hour could not be matched in $goodHours or it contains the value that immediately proceeds $hour. That is what you asked for.
This only works when $goodHours is sorted, in case it's not, you can sort it by using the asort() function.
Try this function:
function nextValueGreaterThan($haystack, $needle, $n=1) {
sort($haystack);
foreach ($haystack as $val) {
if ($val >= $needle) {
$n--;
if ($n <= 0) {
return $val;
}
}
}
}
$goodHours = array(8,9,10,11,12,19,20,21);
echo nextValueGreaterThan($goodHours, 14); // 19
echo nextValueGreaterThan($goodHours, 14, 3); // 21
Here's an answer similar to the rest of these, including an optional "offset" parameter, that gets your n'th item past the de-facto first one.
class GoodHours {
private $hours = array(8,9,10,11,12,19,20,21);
public function getGoodHour($hour, $offset = 0) {
$length = count($this->hours);
for ($i = 0 ; $i < $length && $this->hours[$i] < $hour ; $i++)
; // do nothing
return $this->hours[($i + $offset) % $length];
}
}
// some test values
$good = new GoodHours();
$x = $good->getGoodHour(5); // 8
$x = $good->getGoodHour(5,1); // 9
$x = $good->getGoodHour(5,2); // 10
$x = $good->getGoodHour(10); // 10
$x = $good->getGoodHour(10,1); // 11
$x = $good->getGoodHour(10,2); // 12
$x = $good->getGoodHour(21); // 21
$x = $good->getGoodHour(21,1); // 8
$x = $good->getGoodHour(21,2); // 9
$x = $good->getGoodHour(21); // 8
$x = $good->getGoodHour(22,1); // 9
$x = $good->getGoodHour(22,2); // 10

Categories