Related
Coding in PHP, I currently have an array of 100 values, which looks like this:
$cmassarray = array(630.00,629.70,629.40,629.10,628.80,628.50,628.20,627.90,627.60,627.30,627.00,
626.70,626.40,626.10,625.80,625.50,625.20,624.90,624.60,624.30,624.00,623.70,
623.40,623.10,622.80,622.50,622.20,621.90,621.60,621.30,621.00,620.70,620.40,
620.10,619.80,619.50,619.20,618.90,618.60,618.30,618.00,617.70,617.40,617.10,
616.80,616.50,616.20,615.90,615.60,615.30,615.00,614.70,614.40,614.10,613.80,
613.50,613.20,612.90,612.60,612.30,612.00,611.70,611.40,611.10,610.80,610.50,
610.20,609.90,609.60,609.30,609.00,608.70,608.40,608.10,607.80,607.50,607.20,
606.90,606.60,606.30,606.00,605.70,605.40,605.10,604.80,604.50,604.20,603.90,
603.60,603.30,603.00,602.70,602.40,602.10,601.80,601.50,601.20,600.90,600.60,
600.30,600.00);
All of the steps are the same length, and I may need to change them (and/or the max/min values) at a future stage, so I would like to find a way to avoid having to re-calculate them manually and type them each time.
If I know the maximum value is 630.00 and the minimum value is 600.00, and that I have 100 steps, would it be possible to create an array specifying that each value is an increment on this equation?
x (array value) = 600+((Max-Min)/100)*y)
where y is the incremental step in the scale.
Thank you for any help!
An alternative to using loops and all that would be range
$start=630;
$stop=600;
$steps=100;
$cmassarray=range( $start, $stop, ( ( $start-$stop ) / $steps ) );
You might want to have a look at the range function, which takes an optional third argument for step. This argument you can easily derive from your maximum, minimum and amount of steps. Here's an example:
$max = 630;
$min = 600;
$steps = 100;
$step = ($max - $min) / $steps;
$your_result = range( $max, $min, $step );
Start with this code:
$max = 630;
$min = 600;
$steps = 100;
$step = ($max - $min) / $steps;
$ar = [];
for ($i = $max; $i >= $min; $i -= $step) {
$ar[] = $i;
}
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.
I need to generate x amount of random odd numbers, within a given range.
I know this can be achieved with simple looping, but I'm unsure which approach would be the best, and is there a better mathematical way of solving this.
EDIT: Also I cannot have the same number more than once.
Generate x integer values over half the range, and for each value double it and add 1.
ANSWERING REVISED QUESTION: 1) Generate a list of candidates in range, shuffle them, and then take the first x. Or 2) generate values as per my original recommendation, and reject and retry if the generated value is in the list of already generated values.
The first will work better if x is a substantial fraction of the range, the latter if x is small relative to the range.
ADDENDUM: Should have thought of this approach earlier, it's based on conditional probability. I don't know php (I came at this from the "random" tag), so I'll express it as pseudo-code:
generate(x, upper_limit)
loop with index i from upper_limit downto 1 by 2
p_value = x / floor((i + 1) / 2)
if rand <= p_value
include i in selected set
decrement x
return/exit if x <= 0
end if
end loop
end generate
x is the desired number of values to generate, upper_limit is the largest odd number in the range, and rand generates a uniformly distributed random number between zero and one. Basically, it steps through the candidate set of odd numbers and accepts or rejects each one based how many values you still need and how many candidates still remain.
I've tested this and it really works. It requires less intermediate storage than shuffling and fewer iterations than the original acceptance/rejection.
Generate a list of elements in the range, remove the element you want in your random series. Repeat x times.
Or you can generate an array with the odd numbers in the range, then do a shuffle
Generation is easy:
$range_array = array();
for( $i = 0; $i < $max_value; $i++){
$range_array[] .= $i*2 + 1;
}
Shuffle
shuffle( $range_array );
splice out the x first elements.
$result = array_slice( $range_array, 0, $x );
This is a complete solution.
function mt_rands($min_rand, $max_rand, $num_rand){
if(!is_integer($min_rand) or !is_integer($max_rand)){
return false;
}
if($min_rand >= $max_rand){
return false;
}
if(!is_integer($num_rand) or ($num_rand < 1)){
return false;
}
if($num_rand <= ($max_rand - $min_rand)){
return false;
}
$rands = array();
while(count($rands) < $num_rand){
$loops = 0;
do{
++$loops; // loop limiter, use it if you want to
$rand = mt_rand($min_rand, $max_rand);
}while(in_array($rand, $rands, true));
$rands[] = $rand;
}
return $rands;
}
// let's see how it went
var_export($rands = mt_rands(0, 50, 5));
Code is not tested. Just wrote it. Can be improved a bit but it's up to you.
This code generates 5 odd unique numbers in the interval [1, 20]. Change $min, $max and $n = 5 according to your needs.
<?php
function odd_filter($x)
{
if (($x % 2) == 1)
{
return true;
}
return false;
}
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$min = 1;
$max = 20;
//number of random numbers
$n = 5;
if (($max - $min + 1)/2 < $n)
{
print "iterval [$min, $max] is too short to generate $n odd numbers!\n";
exit(1);
}
$result = array();
for ($i = 0; $i < $n; ++$i)
{
$x = rand($min, $max);
//not exists in the hash and is odd
if(!isset($result{$x}) && odd_filter($x))
{
$result[$x] = 1;
}
else//new iteration needed
{
--$i;
}
}
$result = array_keys($result);
var_dump($result);
I need to create a random number with x amount of digits.
So lets say x is 5, I need a number to be eg. 35562
If x is 3, then it would throw back something like; 463
Could someone show me how this is done?
You can use rand() together with pow() to make this happen:
$digits = 3;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);
This will output a number between 100 and 999. This because 10^2 = 100 and 10^3 = 1000 and then you need to subtract it with one to get it in the desired range.
If 005 also is a valid example you'd use the following code to pad it with leading zeros:
$digits = 3;
echo str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);
I usually just use RAND() http://php.net/manual/en/function.rand.php
e.g.
rand ( 10000 , 99999 );
for your 5 digit random number
Here is a simple solution without any loops or any hassle which will
allow you to create random string with characters, numbers or even with special symbols.
$randomNum = substr(str_shuffle("0123456789"), 0, $x);
where $x can be number of digits
Eg.
substr(str_shuffle("0123456789"), 0, 5);
Results after a couple of executions
98450
79324
23017
04317
26479
You can use the same code to generate random string also, like this
$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTVWXYZ"), 0, $x);
Results with $x = 11
FgHmqpTR3Ox
O9BsNgcPJDb
1v8Aw5b6H7f
haH40dmAxZf
0EpvHL5lTKr
You can use rand($min, $max) for that exact purpose.
In order to limit the values to values with x digits you can use the following:
$x = 3; // Amount of digits
$min = pow(10,$x);
$max = pow(10,$x+1)-1);
$value = rand($min, $max);
Treat your number as a list of digits and just append a random digit each time:
function n_digit_random($digits) {
$temp = "";
for ($i = 0; $i < $digits; $i++) {
$temp .= rand(0, 9);
}
return (int)$temp;
}
Or a purely numerical solution:
function n_digit_random($digits)
return rand(pow(10, $digits - 1) - 1, pow(10, $digits) - 1);
}
the simplest way i can think of is using rand function with str_pad
<?php
echo str_pad(rand(0,999), 5, "0", STR_PAD_LEFT);
?>
In above example , it will generate random number in range 0 to 999.
And having 5 digits.
function random_numbers($digits) {
$min = pow(10, $digits - 1);
$max = pow(10, $digits) - 1;
return mt_rand($min, $max);
}
Tested here.
rand(1000, 9999); works more faster than x4 times rand(0,9);
benchmark:
rand(1000, 9999) : 0.147 sec.
rand(0,9)x4 times : 0.547 sec.
both functions was running in 100000 iterations to make results more explicit
Well you can use as simple php function mt_rand(2000,9000) which can generate a 4 digit random number
mt_rand(2000,9000)
You can generate any x-digit random number with mt_rand() function.
mt_rand() is faster than rand().
Syntax : mt_rand() or mt_rand($min , $max).
Example : <?php echo mt_rand(); ?>
read more
do it with a loop:
function randomWithLength($length){
$number = '';
for ($i = 0; $i < $length; $i++){
$number .= rand(0,9);
}
return (int)$number;
}
rand or mt_rand will do...
usage:
rand(min, max);
mt_rand(min, max);
function random_number($size = 5)
{
$random_number='';
$count=0;
while ($count < $size )
{
$random_digit = mt_rand(0, 9);
$random_number .= $random_digit;
$count++;
}
return $random_number;
}
Following is simple method to generate specific length verification code. Length can be specified, by default, it generates 4 digit code.
function get_sms_token($length = 4) {
return rand(
((int) str_pad(1, $length, 0, STR_PAD_RIGHT)),
((int) str_pad(9, $length, 9, STR_PAD_RIGHT))
);
}
echo get_sms_token(6);
this simple script will do
$x = 4;//want number of digits for the random number
$sum = 0;
for($i=0;$i<$x;$i++)
{
$sum = $sum + rand(0,9)*pow(10,$i);
}
echo $sum;
This is another simple solution to generate random number of N digits:
$number_of_digits = 10;
echo substr(number_format(time() * mt_rand(),0,'',''),0,$number_of_digits);
Check it here: http://codepad.org/pyVvNiof
function rand_number_available($already_mem_array,$boundary_min,$boundary_max,$digits_num)
{
$already_mem_array_dim = count($already_mem_array); // dimension of array, that contain occupied elements
// --- creating Boundaries and possible Errors
if( empty($digits_num) ){
$boundary_dim = $boundary_max - $boundary_min;
if($boundary_dim <= 0){
$error = -1; // Error that might happen. Difference between $boundary_max and $boundary_min must be positive
}else{
$error = -2; // Error that might happen. All numbers between, $boundary_min and $boundary_max , are occupied, by $already_mem_array
}
}else{
if($digits_num < 0){ // Error. If exist, $digits_num must be, 1,2,3 or higher
$error = -3;
}elseif($digits_num == 1){ // if 'one-figure' number
$error = -4; // Error that might happen. All 'one-figure' numbers are occupied, by $already_mem_array
$boundary_min = 0;
$boundary_max = 9;
$boundary_dim = $boundary_max-$boundary_min;
}elseif($digits_num == 2){ // if 'two-figure' number
$error = -5; // Error that might happen. All 'two-figure' numbers are occupied, by $already_mem_array
$boundary_min = 10;
$boundary_max = 99;
$boundary_dim = $boundary_max-$boundary_min;
}elseif($digits_num>2){ // if 'X-figure' number. X>2
$error = -6; // Error that might happen. All 'X-figure' numbers are occupied, by $already_mem_array. Unlikely to happen
$boundary_min = pow(10, $digits_num-1); // stepenovanje - graduation
$boundary_max = pow(10, $digits_num)-1;
$boundary_dim = $boundary_max-$boundary_min;
}
}
// -------------------------------------------------------------------
// --- creating response ---------------------------------------------
if( ($already_mem_array_dim <= $boundary_dim) && $boundary_dim>0 ){ // go here only if, there are AVAILABLE numbers to extract, and [difference] $boundary_dim , is positive
do{
$num = rand($boundary_min,$boundary_max);
}while( in_array($num, $already_mem_array) );
$result = $num;
}else{
$result = $error; // Limit that happened
}
return $result;
// -------------------------------------------------------------------
}
This function works perfectly with no repeats and desired number of digits.
$digits = '';
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0; $i < $length; $i++){
global $digits;
$digits .= $numbers[$i];
}
return $digits;
}
You can call the function and pass the number of digits for example:
randomDigits(4);
sample results:
4957 8710 6730 6082 2987 2041 6721
Original script got from this gist
Please not that rand() does not generate a cryptographically secure value according to the docs:
http://php.net/manual/en/function.rand.php
This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.
Instead it is better to use random_int(), available on PHP 7 (See: http://php.net/manual/en/function.random-int.php).
So to extend #Marcus's answer, you should use:
function generateSecureRandomNumber($digits): int {
return random_int(pow(10, $digits - 1), pow(10, $digits) - 1);
}
function generateSecureRandomNumberWithPadding($digits): string {
$randomNumber = random_int(0, pow(10, $digits) - 1);
return str_pad($randomNumber, $digits, '0', STR_PAD_LEFT);
}
Note that using rand() is fine if you don't need a secure random number.
The following code generates a 4 digits random number:
echo sprintf( "%04d", rand(0,9999));
you people really likes to complicate things :)
the real problem is that the OP wants to, probably, add that to the end of some really big number. if not, there is no need I can think of for that to be required. as left zeros in any number is just, well, left zeroes.
so, just append the larger portion of that number as a math sum, not string.
e.g.
$x = "102384129" . complex_3_digit_random_string();
simply becomes
$x = 102384129000 + rand(0, 999);
done.
I am having mathematics oriented question.Here i like to get the all possible combinations
and looking to store in array.
For example:-
1 digit = 10 (0,1,2,3,....9)
2 digit = 100 (00,01,02,03,...)
I am having formula to find number of possibilities i.e 10^n -1.But i don't know how can i get the values.
function get_combinations(5){
//10^5 -1 = 99999 values
}
the function result should be
00000,00001,00010,00100,....
in array
not like
0,1,2,....00,01,03,...99999
EDIT
I also like to mix some alphabets with the number
results like
0000a,000a1,000z1,00001,00000,....
Thanks in advance
$n = ???;
$array = range(0, pow(10, $n)-1);
yes, there is no integer start with zero
so, dun bother to construct an array start with leading zero,
when you need to output str_pad can be applied
function get_combinations($n)
{
return range(0, pow(10, $n)-1);
}
$array = get_combinations(5);
$pad = strlen(max($array));
// to output
echo str_pad($array[0], $pad, 0, STR_PAD_LEFT);
$result = array();
$count = pow(10,$x);
for ($i = 0, $i < $count, $i++) {
$result[] = str_repeat('0', $x - strlen($i)) . $i;
}
You can't have an integer that is 0000 because that is just 0.
To get all numbers from 0 to 9 use the range() function:
$array = range(0,9); // array(0,1,2,3,4,5,6,7,8,9)
And alike for bigger numbers.
If you want them as strings use sprintf or related to reformat that array.
Or just use a for( loop :)
How about:
$n = 3;
function format($x) {
global $n;
return sprintf("%0${n}d", $x);
}
$arr = array_map('format', range(0, pow(10,$n)-1));
function get_combinations($exp){
$max = pow(10, $exp) - 1;
for ($i = 0; $i <= $max; $i++) $comb[] = str_pad($i, $exp, '0', STR_PAD_LEFT);
return $comb;
}