Trying to display a random generated string on my page - php
I'm trying to display a random generated string on my page (php), but I have absolutely no idea how to do this.
I only want the following letters and digits to be used:
B C D F G H J K M P Q R T V W X Y Z 2 3 4 6 7 8 9
In the following format:
XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
Can anyone help me out, and give me a script which I can put on my page? Help would be really appreciated!
I tried this but it's not even displaying on my page for some odd reason.
$tokens = 'BCDFGHJKMPQRTVWXYZ2346789';
$serial = '';
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < 5; $j++) {
$serial .= $tokens[rand(0, 35)];
}
if ($i < 3) {
$serial .= '-';
}
}
echo $serial;
You were almost there. Here's a few fixes to your code;
<?php
$tokens = 'BCDFGHJKMPQRTVWXYZ2346789';
$serial = '';
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < 5; $j++) {
$serial .= $tokens[rand(0, strlen($tokens) - 1)];
}
if ($i < 4) {
$serial .= '-';
}
}
echo $serial;
?>
I can't say for sure why your page isn't showing, but in your original code you were missing <?php at the top of the page.
Edit: Here's a quick explanation of some of the changes I made to your code.
Your code had rand(0, 35). But since you may change the characters in $tokens in the future, it's better to simply calculate the length of the $tokens using strlen($tokens) - 1 (the -1 being important because strlen() starts counting at 1, whereas $tokens[INDEX] starts counting at 0).
Your code had if ($i < 3), but you actually want four dashes, so I changed it to if ($i < 4).
<?php
$charsPerGroup = 5;
$groups = 5;
$groupDelimiter = '-';
$tokens = explode(' ', 'B C D F G H J K M P Q R T V W X Y Z 2 3 4 6 7 8 9'); // from your question, format this however you want
$tokens = array_flip($tokens);
$resultArray = array();
for($i=0;$i<$groups;$i++) {
$resultArray[] = join(array_rand($tokens, $charsPerGroup));
}
echo join($groupDelimiter, $resultArray);
<?php
$enters = explode(' ', "B C D F G H J K M P Q R T V W X Y Z 2 3 4 6 7 8 9");
$entry = rand(0,count($enters)-1);
echo $enters[$entry];
$output = "";
for($i=1; $i++; $i<=25) {
$entry = rand(0,count($enters)-1);
$output .= $enters[$entry] . ($i % 5 == 0 && $i < 25 ? '-' : '' );
}
echo $output;
?>
Related
Find the highest product in 4 directions in a matrix
I got this challenge to find the highest product of 4 consecutive numbers on a 20x20 matrix of integers. The numbers are read line by line from a file separated by a space. The products can be in horizontal, vertical and diagonal in both directions My "solution" gives the wrong answer. EDIT: I've updated the code to work without file input and added sample data; also fixed one of my mistakes that were pointed out in the comments $data = [ [89,32,92,64,81,2,20,33,44,1,70,75,39,62,76,35,16,77,22,27], [53,11,6,95,41,51,31,59,8,23,19,13,61,91,48,69,84,52,66,24], [93,72,85,97,21,79,56,5,45,3,65,30,83,87,43,7,34,0,4,14], [29,17,49,9,82,90,55,67,15,63,54,94,12,28,96,37,58,98,86,78], [74,40,50,60,26,99,80,18,10,46,36,68,25,57,47,71,42,73,88,38], [50,22,6,26,18,53,52,5,46,2,89,77,83,48,4,58,45,28,84,81], [49,82,31,14,69,17,91,54,34,40,0,33,30,95,60,44,29,24,85,16], [27,11,76,39,15,86,92,74,99,59,94,12,55,57,38,96,47,32,78,75], [51,20,87,42,62,41,7,35,23,21,71,25,67,97,80,90,88,64,13,70], [19,9,56,43,68,93,65,98,36,3,61,63,10,72,8,73,1,66,79,37], [22,58,52,12,3,41,28,72,42,74,76,64,59,35,85,78,14,27,53,88], [46,80,5,96,7,68,61,69,67,34,36,40,82,26,75,50,29,91,10,2], [30,39,19,48,33,93,1,45,66,98,0,23,62,25,51,71,56,77,24,21], [79,87,94,60,8,32,13,65,4,92,73,9,31,37,17,84,15,90,86,20], [95,6,81,70,47,16,44,83,49,43,55,54,18,63,38,11,97,89,99,57], [95,78,64,58,7,17,53,28,74,86,6,12,54,85,21,94,16,69,25,68], [13,20,41,97,1,2,80,30,0,84,67,45,93,96,82,92,62,33,18,44], [60,77,31,70,76,36,59,38,15,3,91,46,65,73,49,11,8,35,5,52], [61,66,79,40,26,72,89,71,75,99,22,9,43,32,14,81,98,88,87,83], [10,4,23,19,56,57,51,47,50,27,90,63,42,29,24,55,48,37,39,34] ]; $matrix = []; //maximums in possible directions $maxes = [0, 0, 0, 0]; //while ($line = trim(fgets(STDIN))) { while ($line = current($data)) { //the horizontal maxes can be calculated while loading //$array = explode(" ", $line); $array = $line; $hMax = array_product(array_slice($array, 0, 4)); for ($i = 1; $i < (count($array)-4); $i++) { $max = array_product(array_slice($array, $i, 4)); if($max > $hMax) { $hMax = $max; } } if ( $hMax > $maxes[0] ) { $maxes[0] = $hMax; } $matrix[] = $array; next($data); } // the last 3 rows can be skipped for($i = 0; $i < (count($matrix)-4); $i++) { for ($j = 0; $j < (count($matrix[$i])-1); $j++) { $vMax = 1; // vertical $dlMax = 1; // diagonal left $drMax = 1; // diagonal rigth for ($k = 0; $k < 5; $k++) { $vMax *= $matrix[$i + $k][$j]; if ( $j < (count($matrix[$i]) - 4) ) { $drMax *= $matrix[$i + $k][$j + $k]; } if ( $j > 3 ) { $dlMax *= $matrix[$i + $k][$j - $k]; } } if ( $maxes[1] < $vMax ) $maxes[1] = $vMax; // the index used to be 1 - my first mistake if ( $maxes[2] < $dlMax ) $maxes[2] = $dlMax; // the index used to be 1 - my first mistake if ( $maxes[3] < $drMax ) $maxes[3] = $drMax; // the index used to be 1 - my first mistake } } sort($maxes); echo end($maxes).PHP_EOL; Where did my approach go wrong, and how can it be sped up? Are there any math tricks that can be applied here (besides checking for zeros)? EDIT: the solution that the code gives for the current data is 4912231320 is it correct?
I've found 2 major errors, and now the result is a plausible 67352832 I'm considering it solved for that reason, but if anyone comes up with some math trick that simplifies or makes it faster I'll give up the accepted answer. The first mistake was for ($k = 0; $k < 5; $k++) { It should've been for ($k = 0; $k < 4; $k++) { since we are only counting 4 numbers at once, thats why the result was so large compared to 10^8 The second was if ( $j > 3 ) { which should've been if ( $j > 2 ) { which will now include one more diagonal possibility
We can consider the four directions a bottom- or right-most cell can be the last of in a sequence. If m[i][j][k][d] is the highest total for a sequence of length k coming from direction d, then: m[i][j][1][d] = data[i][j] for all d m[i][j][k]['E'] = data[i][j] * m[i][j - 1][k - 1]['E'] m[i][j][k]['NE'] = data[i][j] * m[i - 1][j - 1][k - 1]['NE'] m[i][j][k]['N'] = data[i][j] * m[i - 1][j][k - 1]['N'] m[i][j][k]['NW'] = data[i][j] * m[i - 1][j + 1][k - 1]['NW'] If we traverse north to south, east to west, the needed cells should have already been calculated, and, clearly, we're looking for max(m[i][j][4][d]) for all i, j, d
Creating 1000 digit within 10 loops only
Is it possible to create 1000 numbers from 0000 to 9999 using only 10 loops? for ($i=0; $i < 10; $i++) { # code... $numberList .= ""; } echo $numberList; result: 0000, 0001, 0002, ... 9999 UPDATES I need to minimize the code because I have a not so good server. I am working on huge list of numbers. Example: 1000-1999, 2000-2999, ... 9000-9999 and also xxx-1000 to xxx-19999, xxx-2000 to xxx-2999, ... xxx-9000 to xxx-9999
Is it helpful to do it like this? $numberList = array(); for($i = 0; i < 10; i++){ for($j = 0; j < 10; j++){ for($k = 0; k < 10; k++){ for($l = 0; l < 10; l++){ $numberList[] = i . j . k . l; } } } } In this way you will have all 4 digits even the most significant zeros like '0001'.
PHP array_rand weird behaviour
I was trying to create a simple password generator and noted that array_rand() returns the same results. Here is the code: <?php function generatePass() { $password = ''; $a = explode(' ', 'q w e r t y u i o p a s d f g h j k l z x c v b n m'); for($i=0; $i < rand(1,200); $i++) { $password .= $a[array_rand($a)]; } return $password; } $r = 0; while ($r <= 10000) { #generating 10 000 passwords $total[] = generatePass(); $r++; } echo '<pre>'; print_r($total); echo '</pre>'; ?> The $total array basically contains the same results repeated over and over again; if I refresh the page, only the order of elements changes, and not their values. The question is: is this an expected behaviour or am I doing something wrong? Thak you for your attention.
Reseed the random number generator with srand() just prior to calling array_rand. srand(); $password .= $a[array_rand($a)];
I think it should be your PHP version. I just copied your code into my localhost server and it worked fine. I'm using PHP 5.5.9-1ubuntu4.7, you should try it or a newer version. By the way, if you can't update your PHP version, use this modified version of your code: <?php function generatePass() { $password = ''; // Put all letters into an array. $letters = array('q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'); for($i=0; $i < rand(1,200); $i++) { // Select a random letter with rand() command inside the brackets of the array. $password .= $letters[rand(0,25)]; } return $password; } $r = 0; while ($r <= 10000) { #generating 10 000 passwords $total[] = generatePass(); $r++; } echo '<pre>'; print_r($total); echo '</pre>'; ?>
Seeding the random generator isn't needed since version 4.2.0 Try using mt_rand() for a better generation. http://php.net/manual/en/function.mt-rand.php Edit: I think you actually want $a = explode(' ', 'q w e r t y u i o p a s d f g h j k l z x c v b n m'); $end = mt_rand(1,200); $password = ''; for($i=0; $i < $end; $i++) { $password .= $a[array_rand($a)]; }
I took the time for you and wrote the generator. I got it to generate 10000 unique passwords and code is efficient: <?php function generatePass() { $password = ''; $lib = 'q w e r t y u i o p a s d f g h j k l z x c v b n m'; $a = explode(' ', $lib); //remove random char for($i=0; $i < mt_rand(1,49); $i++) { shuffle($a); //get Random Char $password .= $a[mt_rand(0,count($a)-1)]; } return $password; } $len = 10000; // total number of numbers $range = array(); foreach(range(0, $len - 1) as $i){ while(in_array($num = generatePass(), $range)){} $range[] = $num; } echo '<pre>'; print_r($range); echo '</pre>';
comparing two strings for percentage match
I am trying to compare a user submitted string to a string of a database record and see how close they are in terms of % i have found this rather interesting code which looks like a good solution Function Compare(ByVal str1 As String, ByVal str2 As String) As Double Dim count As Integer = If(str1.Length > str2.Length, str1.Length, str2.Length) Dim hits As Integer = 0 Dim i, j As Integer : i = 0 : j = 0 For i = 0 To str1.Length - 1 If str1.Chars(i) = " " Then i += 1 : j = str2.IndexOf(" "c, j) + 1 : hits += 1 While j < str2.Length AndAlso str2.Chars(j) <> " "c If str1.Chars(i) = str2.Chars(j) Then hits += 1 j += 1 Exit While Else j += 1 End If End While If Not (j < str2.Length AndAlso str2.Chars(j) <> " "c) Then j -= 1 End If Next Return Math.Round((hits / count), 2) End Function firstly can anyone tell me what the language is used above, and can anyone help me convert it to php please? i've tried to convert it but ran in to a bit of trouble early on function compare($str1,$str2) as $double { $count = if(strlen($str1) > strlen($str2), strlen($str1) > strlen($str2)); $hits = 0; $i - 0; $j = 0; for($i = 0; $i < strlen($str1); $i++) { if($str1[$i] == " ") { $i .= "1"; } } } any help with this would be hugely appreciated
As an option, then, try something like this: $teststr = "This is a test."; $dbstr = "This was a test."; $percent = (1 - levenshtein($teststr, $dbstr)/max( strlen($teststr),strlen($dbstr) ) ) * 100; print "Percent match".$percent."\n"; Percent match: 92.857142857143 Far more info at: http://us3.php.net//manual/en/function.levenshtein.php
Generating HTML table from PHP array
I don't understand this. I need to solve seemingly simple problem, and yet it's beyond my logic. I need to write a function: table_columns($input, $cols) which would output a table(example): $input = array('apple', 'orange', 'monkey', 'potato', 'cheese', 'badger', 'turnip'); $cols = 2; Expected output: <table> <tr> <td>apple</td> <td>cheese</td> </tr> <tr> <td>orange</td> <td>badger</td> </tr> <tr> <td>monkey</td> <td>turnip</td> </tr> <tr> <td>potato</td> <td></td> </tr> </table>
Think about it like this. Say you have an array of items like this: a, b, c, d, e, f, g, h, i, j, k With columns set to 2, you'd need to render them in this order: a g b h 0 6 1 7 2 8 3 9 4 10 5 c i ---> a g b h c i d j e k f d j e k f With three columns: a e i b f j 0 4 8 1 5 9 2 6 10 3 7 c g k ---> a e i b f j c g k d h d h So, roughly: function cells ($input, $cols) { $num = count($input); $perColumn = ceil($num / $cols); for ($i = 0; $i < $perColumn; $i++) { echo "<tr>"; for ($j = 0; $j < $cols; $j++) { // you'll need to put a check to see you haven't gone past the // end of the array here... echo "<td>" . $input[$j * $perColumn + $i] . "</td>"; } echo "</tr>"; } }
$input = array_chunk($input, $cols); $html = '<table>'; foreach($input as $tr){ html .= '<tr>'; for($i = 0; $i < $cols; $i++) $html .= '<td>'.(isset($tr[$i]) ? $tr[$i] : '').'</td>'; $html .= '</tr>'; } $html .= '</table>';
Try this function: function table_columns($input, $cols) { int $i = 0; echo "<table><tr>"; foreach ( $input as $cell ) { echo "<td>".$cell."</td>"; $i++; if($i == $cols) { $i = 0; echo "</tr><tr>"; } } echo "</tr></table>"; } I hope it solves your problem. [EDIT: Fixed the mistakes, was in a hurry]