How to generate a random pattern of *&# in PHP - php

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.

Related

Random string rules

I have a function that generates a random 3-character alpha-numeric string. I need to modify it in such a way that the new string consisted of 2 alpha and 2 numeric characters. The combination of numbers and letters can be random.
function generate_random($length = 3) {
$characters = '123456789ABCDEFGHJKLMNPRSTUVWXYZ';
$rand_str = '';
for ($p = 0; $p < $length; $p++) {
$rand_str .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $rand_str;
}
I need to modify it in such a way that the new string consisted of 2 alpha and 2 numeric characters. The combination of numbers and letters can be random. How do I do that?
I would personally do it this way:
function generate_random($countAlpha = 2, $countNumeric = 2, $randomize = true) {
$alpha = 'ABCDEFGHJKLMNPRSTUVWXYZ';
$numeric = '123456789';
$rand_str = '';
for ($p = 0; $p < $countAlpha; $p++) {
$rand_str .= $alpha[mt_rand(0, strlen($alpha)-1)];
}
for ($p = 0; $p < $countNumeric; $p++) {
$rand_str .= $numeric[mt_rand(0, strlen($numeric)-1)];
}
if($randomize) {
$rand_str = str_split($rand_str);
shuffle($rand_str);
return implode($rand_str);
}
return $rand_str;
}
Inside I have 2 for loops, each one based on parameters $countAlpha and $countNumeric. I also have a 3rd parameter, $randomize that will allow you to randomize the output if you wish.
You could separe numbers and letter. Then, append N values of each into an array, shuffle it, and the implode to get your string:
function generate_random($nNumbers = 2, $nAlpha = 2) {
// prepare data to use
$num = '123456789';
$numlen = strlen($num) - 1;
$alpha = 'ABCDEFGHJKLMNPRSTUVWXYZ';
$alphalen = strlen($alpha) - 1;
$out = []; // New array
// generate N numbers
for ($i = 0; $i < $nNumbers ; $i++) {
$out[] = $num[mt_rand(0, $numlen)];
}
// generate N letters
for ($i = 0; $i < $nAlpha ; $i++) {
$out[] = $alpha[mt_rand(0, $alphalen)];
}
shuffle($out); // Shuffle the array
return implode($out); // Convert to string
}
echo generate_random() ;
// echo generate_random(2, 4) ; // example

How do i rand string according to index size

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...

I want to generate thirty unique alphanumeric strings in PHP loop

<?php
// Set length of the string
$length = 30;
$random = substr(md5(rand()), 0, 15);
// Use for-loop to generate thirty unique alphanumeric strings
For($i=0; $i<$length;) {echo $random.$i++."<br />";
The code above generates something like 5523d651bfb642b0, 5523d651bfb642b1, 5523d651bfb642b2, 5523d651bfb642b3 etc. The next value is just too easily predictable. I want something totally different like when I refresh the page in the browser. If I remove loop and just echo $random, the page generates a totally different string every time I refresh the page. How do I generate something totally different like 5523d651bfb642b0, 2yyd00nngbh201km, 78gdfmpqg01597v etc using loop? Thanks.
function generateRandomString($length = 30) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$i = 0;
$times_to_run = 30;
while ($i++ < $times_to_run)
{
generateRandomString();
}
If you're using PHP 7, it's easy to generate a random string:
$bytes = random_bytes(5); //random. Increase input for more bytes
$code = bin2hex($bytes); // eg: 385e33f741
Before PHP 7, I would generate an alphanumeric code with a function
function getRandomString($length){
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
$result = '';
while(strlen($result)<$length) {
$result .= $chars{mt_rand(0,strlen($chars)-1)};
}
return $result;
}
To get a 10-character random code, you just call:
$randomString = getRandomString(10);
You can add more characters to $chars ofcourse

PHP: Transform string to another string

I would like to Convert simple string to another format based on below logic
Example 1 : if string is 3,4-8-7,5 then I need the set as (3,8,7),(4,8,5).
Example 2: If string is "4-5,6-4" then required set will be (4,5,4),(4,6,4).
More Clear Requirements:
if string is 5-6,7,8-2,3-1. It need to be divided first like [5] AND [(6) OR (7) OR (8)] AND [(2) OR (3)] AND [1]. Result must be All possible combination: (5,6,2,1),(5,6,3,1),(5,7,2,1),(5,7,3,1),(5,8,2,1),(5,8,3,1).
The Logic behind to building the set are we need to consider ',' as OR condition and '-' as AND condition.
I am trying my best using For loop but unable to find solution
$intermediate = array();
$arry_A = explode('-', '3,4-8-7,5');
for ($i = 0; $i < count($arry_A); $i++) {
$arry_B = explode(',', $arry_A[$i]);
for ($j = 0; $j < count($arry_B); $j++) {
if (count($intermediate) > 0) {
for ($k = 0; $k < count($intermediate); $k++) {
$intermediate[$k] = $intermediate[$k] . ',' . $arry_B[$j];
}
} elseif (count($intermediate) === 0) {
$intermediate[0] = $arry_B[$j];
}
}
}
echo $intermediate, should give final result.
Cool little exercise!
I would do it with the following code, which I will split up for readability:
I used an array as output, since it's easier to check than a string.
First, we initialize the $string and create the output array $solutions. We will calculate the maximum of possible combinations from the beginning ($results) and fill the $solutions array with empty arrays which will be filled later with the actual combinations.
$string = '3,4-8-7,5';
$solutions = array();
$results = substr_count($string,',')*2;
for($i = 0; $i < $results; $i++) {
array_push($solutions,array());
}
We will need two helper functions: checkSolutions which makes sure, that the combination does not yet exist more than $limit times. And numberOfORAfterwards which will calculate the position of an OR pattern in the $string so we can calculate how often a combination is allowed in the single steps of the walkthrough.
function checkSolutions($array,$solutions,$limit) {
$count = 0;
foreach($solutions as $solution) {
if($solution === $array) $count++;
}
if($count < $limit) return true;
else return false;
}
function numberOfORAfterwards($part,$parts) {
foreach($parts as $currPart) {
if($currPart === $part) $count = 0;
if(isset($count)) if(!ctype_digit($currPart)) $count++;
}
return $count;
}
Now the main part: We are going to loop over the "parts" of the $string a part are the digits between AND operations.
If you need further explanation on this loop, just leave a comment.
$length = 0;
// split by all AND operations
$parts = explode('-',$string);
foreach($parts as $part) {
if(ctype_digit($part)) {
// case AND x AND
foreach($solutions as &$solution) {
array_push($solution,$part);
}
} else {
// case x OR x ...
$digits = explode(',',$part);
foreach($digits as $digit) {
for($i = 0; $i < $results/count($digits); $i++) {
foreach($solutions as &$solution) {
if(count($solution) == $length) {
$test = $solution;
array_push($test,$digit);
$limit = numberOfORAfterwards($part,$parts);
echo $digit.' '.$limit.'<br>';
if(checkSolutions($test,$solutions,$limit)) {
array_push($solution,$digit);
break;
}
}
}
}
}
}
$length++;
}
print_r($solutions);
Some tests:
String: 3,4-8-7,5
Combinations: (3,8,7)(3,8,5)(4,8,7)(4,8,7)
String: 5-6,7,8-2,3-1
Combinations: (5,6,2,1)(5,6,3,1)(5,7,2,1)(5,7,3,1)(5,8,2,1)(5,8,2,1)
String: 2,1-4-3,2-7,8-9
Combinations: (2,4,3,7,9)(2,4,3,8,9)(2,4,2,7,9)(1,4,3,7,9)(1,4,2,8,9)(1,4,2,8,9)
String: 1,5-3,2-1
Combinations: (1,3,1)(1,2,1)(5,3,1)(5,3,1)

Looping function and saving to array

I'm quite new to php but learning fast, what I'm trying to do is loop a function which generates a random string of characters maybe 10 times and save each random string into an array.
function getRandom()
{
$length = 5;
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
return $randomString;
}
Here is my get random string function but now how would I loop it a set number of times and save $randomString into an array each time, any pointers would be great,
Just have to declare an array and save it. For eg:
$arr = array(); // declare the array
for($i = 0; $i < 10; $i++) {
$arr[] = getRandom();
}
var_dump($arr); // to check if you are getting the desired result
This should work:
$length = 5;
$data = array();
// Set the top value in this case I'm using 10
for ($i=0; $i <= 10; $i++) {
$data[$i] = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0,$length);
}
// Print to see new array
print_r($data)

Categories