heres my code
while($x <= $num) {
$code = rand(1,666666).rand(2,88888888);
$INC = qry_run("Insert into ms_code2 (code) Values(".$code.")");
$x++;
}
the main problem is when this loop work sometimes it generate 14 number sometimes 10 and sometimes 12
I won't get into a discussion about how "random" we can ever really get, I am pretty sure this will generate a number random enough! :)
function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(0, 9);
}
return $result;
}
..and of course then it's just echo randomNumber(14);
You can use this simple trick to generate (n) number of random numbers
function generateCode($limit){
$code = 0;
for($i = 0; $i < $limit; $i++) { $code .= mt_rand(0, 9); }
return $code;
}
echo generateCode(14);
This above function returns 14 random digits.
A simplest one could be this also, Here we are using array_map and range to iterate over callback function and maintain a string.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$string="";
array_map(function($value) use(&$string){
$string.=mt_rand(0, 9);
}, range(0,13));
echo $string;
Related
I don't really know how to go about but it really pretty for me in achievement like each rand_string to each index.
My code:
function rand_string($length) {
$str="";
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0; $i < $length; $i++) {
$str .= $chars[rand(0, $size-1)];
}
return $str;
}
$pcode = rand_string(4);
for ($b = 0; $b < 3; $b++) {
echo $pcode[$b];
}
I am expecting something like: 9cwm cZnu c9e4 in the output. Can I achieve this in PHP?
Currently, with my code, I get a string from rand_string in each index like 9cw.
Your code works, you only need to call rand_string inside your second loop in order to get something like 9cwm cZnu c9e4 (what you have described in your question).
Here is a working example:
function rand_string($length) {
$str="";
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
// call rand_string inside for loop
for ($b = 0; $b<3; $b++) {
echo rand_string(4).' ';
}
Try it online
The generation of the string actually works in your code. You aren't calling/printing the function correctly. Just call the function three times and print all the results (with spaces in between). Instead of printing you could join it together in a string and remove the last space.
<?php
function rand_string($length) {
$str="";
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
for ($b = 0; $b<3; $b++)
{
echo rand_string(4)." ";
}
If you don't mind using a completely different approach, limited to 32 chars :
return substr(md5(mt_rand().time()), 0, $length);
It's not super random but you get the picture...
Thanks to CM and user2693053 for bringing stuff to my attention (updated answer)
using mt_rand() instead of rand()
md5() length of 32...
Hello there i am making a program which will let me help generate a random string with a specified limit and random strings of *&# but then the combination of *&# should not repeat.
Ex: if I input 3 then the O/P should be
#**
**#
**#
It should generate a random string of length 3 up to 3 rows with different patterns also the pattern should not repeat. I am using the below code but not able to attain it.
$n = 3;
for($i = 0; $i < n; $i++)
{
for($j=0;$j<=$n;j++)
{
echo "*#";
}
echo "<br />";
}
But I am not able to generate the output, where is my logic failing?
If you want to make sure the same pattern doesn't show up more than once you'll have to keep a record of the generated strings. In the most basic form it could look like this:
public function generate() {
$amount = 3; // The amount of strings you want.
$generated_strings = []; // Keep a record of the generated strings.
do {
$random = $this->generateRandomString(); // Generate a random string
if(!in_array($random, $generated_strings)) { // Keep the record if its not already present.
$generated_strings[] = $random;
}
} while(sizeof($generated_strings) !== $amount); // Repeat this process until you have three strings.
print_r($generated_strings);
}
public function generateRandomString($length = 3) {
$characters = '*&#';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Not necessarily the most optimized algorithm but it should work.
I am using a string generator, somewhat random, combining the chars you have provided. The second part is filling the output array with generated strings that are not already present.
<?php
function randomize($n) {
$s = '';
for ($i = 0; $i < $n; $i++) {
$s. = (rand(0, 10) < 5 ? '*' : '#');
}
return $s;
}
$n = 3;
$output = array();
for ($i = 0; $i < $n; $i++) {
$tmp = randomize($n);
while (in_array($tmp, $output)) {
$tmp = randomize($n);
}
$output[] = $tmp;
}
print_r($output);
Visible here
You can use a while loop and array unique to do this.
I first have an array with possible chars.
Then I loop until result array is desired lenght.
I use array unique to remove any duplicates inside the loop.
I use rand(0,2) to "select" a random character from possible characters array.
$arr = ["*", "&", "#"];
$res = array();
$n =7;
While(count($res) != $n){
$temp="";
For($i=0;$i<$n;$i++){
$temp .= $arr[Rand(0,count($arr)-1)];
}
$res[] = $temp;
$res = array_unique($res);
}
Var_dump($res);
https://3v4l.org/Ko4Wd
Updated with out of scope details not clearly specified by OP.
I'm trying to create a generator for a lotto that I play very often.
The lotto is a 5 number draw, ranging from number 1-50 and the same number cannot appear again.
My current approach to do this is using array_rand() but after some reading I noticed that I should not use array_rand() for this purpose, instead I should be using random_int().
My current approach below:
$numbers = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50);
for ($i = 0; $i <= 4; $i++) {
$number = array_rand($numbers);
unset($numbers[$number]);
if ($number == 0) {
$number = array_rand($numbers);
unset($numbers[$number]);
}
$out1[] = array("<div class=\"number\">$number</div>");
}
As you can see above, this works and it generates 5 numbers without duplicating because I unset the number after it's been drawn.
My question is:
How can I do the same as above but using random_int()instead?
To clarify: Use random_int() to generate a random number but ensure that it doesnt generate the same number again in that run.
$numbers = array(); // Create an empty array
while (count($numbers) < 5) { // While less than 5 items in the array repeat the following
$random = random_int(1,50); // Generate a random number
if (!in_array($random, $numbers)) { // Check if the random number is already in the array, and if it is not then:
$numbers[] = $random; // add the random number to the array
}
}
foreach ($numbers as $n) { // Loop over your array and output with your added HTML
echo "<div class=\"number\">$n</div>";
}
Here's the way:
$out = [];
$used = [];
for ($i = 0; $i <= 4; $i++) {
do {
$randInt = random_int(1, 50);
} while (in_array($randInt, $used));
$used[] = $randInt;
$out[] = "<div class=\"number\">$randInt</div>";
}
I'm trying to find a way to replace any duplicated value but the only solution I have found so far is array_unique which doesn't really work for me as I need the duplicate to be replaced by another number which itself is not a duplicate.
function generate_random_numbers($rows, $delimiter)
{
$numbers = array();
for($i = 0; $i < $delimiter; $i++)
{
$numbers[$i] = rand(1, $rows);
if(in_array($i, $numbers))
{
$numbers[$i] = rand(1, $row);
}
}
return $numbers;
}
$numbers = generate_random_numbers(20, 10);
print_r($numbers);
would anyone help me out on this one please?
You can do this way easier and faster.
Just create an array for all possible numbers with range(). Then shuffle() the array and take an array_slice() as big as you want.
<?php
function generate_random_numbers($max, $amount) {
if($amount > $max)
return [];
$numbers = range(1, $max);
shuffle($numbers);
return array_slice($numbers, 0, $amount);
}
$numbers = generate_random_numbers(20, 10);
print_r($numbers);
?>
And if you want to get 490 unique elements from a range from 1 - 500, 10'000 times:
My version: ~ 0.7 secs
Your version: Order 2 birthday cakes, you will need them.
You are inserting a random number and then, if it is already in the array (which it MUST be because you just inserted it), you use a new random number, which might be a duplicate. So, you have to get a number that is not a duplicate:
do {
$num = rand(1,$rows);
} while(!in_array($num, $numbers));
Now, you know that $num is not in $numbers, so you can insert it:
$numbers[] = $num;
You were pretty close.
The if-clause needs to be a loop, to get new random number.
(Also your in_array was slightly wrong)
function generate_random_numbers($rows, $delimiter) {
$numbers = array();
for($i = 0; $i < $delimiter; $i++) {
do {
$number = rand(1, $rows);
}
while(in_array($number, $numbers));
$numbers[] = $number;
}
return $numbers;
}
I am trying to make random numbers that are exactly 15 characters long and positive using php. I tried rand(100000000000000, 900000000000000) but it still generates negatives and numbers less than 15. Is there another function I am missing that can do this, or should I just use rand(0, 9) 15 times and concatenate the results?
$i = 0;
$tmp = mt_rand(1,9);
do {
$tmp .= mt_rand(0, 9);
} while(++$i < 14);
echo $tmp;
You are using a 32 bit platform. To handle these integers, you need a 64bits platform.
You can do the rand two times and save it as a string, like this:
$num1 = rand(100000,999999);
$num2 = rand(100000,999999);
$num3 = rand(100,999);
$endString = $num1.$num2.$num3;
PS. I like tiggers solution better than mine.
Keep in mind that this will return a string, not an actual integer value.
function randNum($length)
{
$str = mt_rand(1, 9); // first number (0 not allowed)
for ($i = 1; $i < $length; $i++)
$str .= mt_rand(0, 9);
return $str;
}
echo randNum(15);
Here you go.
function moreRand($len) {
$str = mt_rand(1,9);
for($i=0;$i<$len-1;$i++) {
$str .= mt_rand(0, 9);
}
return $str;
}
echo moreRand(15);
Edit: If you want to shave .00045s off your execution time,
function randNum() { return abs(rand(100000000000000, 900000000000000)); }