Generating random values in PHP - php

I am quite a newbie when it comes to php and i wanted to try something but i have absolutely no idea how should i do this.. To be honest i am not sure if can explain this to you very clearly either.. Lets get started..
I have couple of letters for example a, b, c, d and e..
and for each one of them i have couples of two-charactered values like this:
a -> fg, dz, gc, bg
b -> zt, hg, oq, vg, gb
c -> lt, pr, cs, sh, pr
d -> kt, nt, as, pr
e -> zd, ke, cg, sq, mo, ld
Here comes the question:
I would like to get a random value for each time for example: dcbae
and for this the ultimate output should be something like this: ntshztdzld or asltvggcmo..
(After generating a random string with the charachters above (between a-e), i should generate another string that contains random values those are related with the each character..
This is not a homework or something similar.
Thanks in advance for your understanding..

Well, you would first create a map:
$map = Array(
"a" => Array("fg","dz","gc","bg"),
"b" => Array("zt","hg","oq","vg","gb"),
"c" => Array("lt","pr","cs","sh","pr"),
"d" => Array("kt","nt","as","pr"),
"e" => Array("zd","ke","cg","sq","mo","ld")
);
I notice that you have the same pair "pr" several times - if you want this encoding to be reversible, avoid duplicates.
Anyway, once you have that it's easy enough to loop through your input string and get a random output:
$input = "dcbae";
$len = strlen($input);
$output = "";
for( $i=0; $i<$len; $i++) {
$entry = &$map[$input[$i]];
if( isset($entry)) $output .= $entry[mt_rand(0,count($entry)-1)];
else $output .= "??";
}
$output is the result.

<?php
// Setup matching values
$encpairs[ 'a' ] = array( 'fg', 'dz', 'gc', 'bg' );
$encpairs[ 'b' ] = array( 'zt', 'hg', 'oq', 'vg', 'gb' );
$encpairs[ 'c' ] = array( 'lt', 'pr', 'cs', 'sh', 'pr' );
// etc. etc.
// Define input string
$my_string = 'abc';
// To randomly build input string
$my_string = '';
$last_key = '';
$key = '';
$keys = array_keys( $encpairs );
$ttl_keys = count( $keys ) -1;
// Generate the input string at random; change "5" to length you desire
for ( $j=0; $j < 5; $j++ ){
// Randomly select a key from $encpairs array (giving you one letter at random)
// The while loop ensures no two letters are used consecutively
while ( $key == $last_key ) {
$key =$keys[ rand(0, $ttl_keys ) ];
}
$last_key = $key;
$my_string .= $key;
}
// Determine input string length
$length = strlen( $my_string );
// Loop through each letter
$output = '';
for( $i=0; $i < $length; $i++ ){
shuffle( $encpairs[ $my_string[$i] ] );
$output.= $encpairs[ $my_string[$i] ][0]; // Added [0]
}

Start by initializing a second string outside of the loop. Convert your original string (to be encrypted) into an array, and then loop through the whole array and append to the second string.
So you get
$splitstr=str_split($original);
$final_string="";
$map=Array(/**/);
foreach($splitstr as $char)
{
$final_string.=$map[$char][rand(0,count($map[$char])-1)];
}
return $final_string;

Related

Find most common character in PHP String

I am looking for the most efficient way to find the most common character in a php string.
I have a string that looks like this:
"aaaaabcaab"
The result should be stored in the variable $total.
So in this case $total should be equal to a
You can use this function,
function getHighest($str){
$str = str_replace(' ', '', $str);//Trims all the spaces in the string
$arr = str_split(count_chars($str.trim($str), 3));
$hStr = "";
$occ = 0;
foreach ($arr as $value) {
$oc = substr_count ($str, $value);
if($occ < $oc){
$hStr = $value;
$occ = $oc;
}
}
return $hStr;
}
Te easiest way to achieve this is:
// split the string per character and count the number of occurrences
$totals = array_count_values( str_split( 'fcaaaaabcaab' ) );
// sort the totals so that the most frequent letter is first
arsort( $totals );
// show which letter occurred the most frequently
echo array_keys( $totals )[0];
// output
a
One thing to consider is what happens in the event of a tie:
// split the string per character and count the number of occurrences
$totals = array_count_values( str_split( 'paabb' ) );
// sort the totals so that the most frequent letter is first
arsort( $totals );
// show all letters and their frequency
print_r( $totals );
// output
Array
(
[b] => 2
[a] => 2
[p] => 1
)

array_rand wihout repeating in php

I'm working with my code that will allow the user to input a word and each letter of the word will give a meaning.
Example: User inputted a text "APPLE".
Output:
A - arc
P - priest
P - president
L - lion
E - escape
The meaning of every letter will be in array..
I already have my code here but the meaning are repeated.
Example:
A - **Arrow**
L - Love
A - **Arrow**
S - Soul
Here's my code
<?php
$chars = str_split("APPLE");
foreach($chars as $char){
if (substr($char, 0, 1) === 'A')
{
$meaning = array("Angel","Ancient","Arrow");
echo $meaning[array_rand($meaning)];
}
}
?>
You could unset it temporarily inside the loop so that you won't get dups. Example:
$chars = str_split("APPLE");
$words = array(
// its up to you what words you want to map
'A' => array("Angel","Ancient","Arrow"),
'E' => array('Elephat', 'Eardrum'),
'L' => array('Level', 'Laravel', 'Love'),
'S' => array('Sweet', 'Spicy', 'Savy'),
'P' => array('Powerful', 'Predictable', 'Pass', 'piss')
);
foreach($chars as $char){
$random_key = array_rand($words[$char]); // get random key
$key = $words[$char][$random_key]; // get the word
unset($words[$char][$random_key]); // unset it so that it will never be repeated
echo "$char - $key <br/>";
}
You could save a "cache" array of previously used terms. Example:
<?php
$chars = str_split("APPLE");
$used_terms = array();
foreach($chars as $char){
if (substr($char, 0, 1) === 'A') {
$meaning = array("Angel","Ancient","Arrow");
do {
$term = $meaning[array_rand($meaning)];
} while (in_array($term, $used_terms));
$used_terms[] = $term;
echo $term;
}
}
?>

Search associative array and print corresponding value in php

I have a dictionary like
UUU F
UUC F
CUU L
CUC L
UUA L
CUA L
UUG L
CUG L
AUU I
AUC I
AUA I
GUU V
GUC V
GUG V
GUA V
So Given a string I want to replace every 3 chars its respective char
I was thinking on using associative arrays:
$d = array();
$d['UUU']='F';
$d['UUC']='F';
$d['UUA']='L';
$d['CUU']='L';
$d['GUC']='V';
$d['GUG']='V';
$d['GUA']='V';
$d['UUG']='L';
$d['CUG']='L';
$s = "UUAGUAUUG";
$temp="";
for($i=0; $i<strlen($s)+1; $i++){
$temp .= $s[$i];
if($i%3==0){
echo $temp;
echo array_search($temp, $d);
$temp = "";
}
}
It should output LVL but have no success
Use str_split:
$s = 'UUAGUAUUG';
$split = str_split($s,3);
$translated = array();
foreach ($split as $bases) {
/**
* # supresses warnings if the array index doesn't exist
*/
$translated []= #$d[$bases];
}
echo join('',$translated);
I think this might work:
$temp = implode(array_map(function($a) { return $d[$a];}, str_split($s, 3)));
The basic solution is:
<?php
$dict = array(
'UUU' => 'F',
'UUC' => 'F',
'UUA' => 'L',
'CUU' => 'L',
'GUC' => 'V',
'GUG' => 'V',
'GUA' => 'V',
'UUG' => 'L',
'CUG' => 'L'
);
$before = "UUAGUAUUG";
$after = strtr($before, $dict);
Although you may be able to write a faster version that takes into account that you are replacing every three letters.
And I'm not 100% sure this will even work, given what kind of combinations can overlap over the 3-char barrier. Which leaves you with this rotten solution:
$after = str_replace('-', '',
strtr(preg_replace('/[A-Z]{3}/', '\0-', $before), $dict));
Seriously, don't try this at home. ;)
You're testing at the wrong time.
Change $i%3 == 0 to $i%3 == 2.
The reason here is that you have added to your temporary string first. That means you immediately check a string of length 1 ("U") and then clear it. Then you go around for another 3 times and you get "UAG", followed by "UAU". Neither of these are in your array.
What I don't understand is that you output the value of $temp each time this happens, so you should have picked up on this.
Change your for loop to this:
for($i=0; $i<strlen($s)+1; $i++){
$temp .= $s[$i];
if(($i+1)%3==0){
echo $d[$temp];
$temp = "";
}
}
Your i value starts from 0. And array_values does not give the expected answer.

"Unfolding" a String

I have a set of strings, each string has a variable number of segments separated by pipes (|), e.g.:
$string = 'abc|b|ac';
Each segment with more than one char should be expanded into all the possible one char combinations, for 3 segments the following "algorithm" works wonderfully:
$result = array();
$string = explode('|', 'abc|b|ac');
foreach (str_split($string[0]) as $i)
{
foreach (str_split($string[1]) as $j)
{
foreach (str_split($string[2]) as $k)
{
$result[] = implode('|', array($i, $j, $k)); // more...
}
}
}
print_r($result);
Output:
$result = array('a|b|a', 'a|b|c', 'b|b|a', 'b|b|c', 'c|b|a', 'c|b|c');
Obviously, for more than 3 segments the code starts to get extremely messy, since I need to add (and check) more and more inner loops. I tried coming up with a dynamic solution but I can't figure out how to generate the correct combination for all the segments (individually and as a whole). I also looked at some combinatorics source code but I'm unable to combine the different combinations of my segments.
I appreciate if anyone can point me in the right direction.
Recursion to the rescue (you might need to tweak a bit to cover edge cases, but it works):
function explodinator($str) {
$segments = explode('|', $str);
$pieces = array_map('str_split', $segments);
return e_helper($pieces);
}
function e_helper($pieces) {
if (count($pieces) == 1)
return $pieces[0];
$first = array_shift($pieces);
$subs = e_helper($pieces);
foreach($first as $char) {
foreach ($subs as $sub) {
$result[] = $char . '|' . $sub;
}
}
return $result;
}
print_r(explodinator('abc|b|ac'));
Outputs:
Array
(
[0] => a|b|a
[1] => a|b|c
[2] => b|b|a
[3] => b|b|c
[4] => c|b|a
[5] => c|b|c
)
As seen on ideone.
This looks like a job for recursive programming! :P
I first looked at this and thought it was going to be a on-liner (and probably is in perl).
There are other non-recursive ways (enumerate all combinations of indexes into segments then loop through, for example) but I think this is more interesting, and probably 'better'.
$str = explode('|', 'abc|b|ac');
$strlen = count( $str );
$results = array();
function splitAndForeach( $bchar , $oldindex, $tempthread) {
global $strlen, $str, $results;
$temp = $tempthread;
$newindex = $oldindex + 1;
if ( $bchar != '') { array_push($temp, $bchar ); }
if ( $newindex <= $strlen ){
print "starting foreach loop on string '".$str[$newindex-1]."' \n";
foreach(str_split( $str[$newindex - 1] ) as $c) {
print "Going into next depth ($newindex) of recursion on char $c \n";
splitAndForeach( $c , $newindex, $temp);
}
} else {
$found = implode('|', $temp);
print "Array length (max recursion depth) reached, result: $found \n";
array_push( $results, $found );
$temp = $tempthread;
$index = 0;
print "***************** Reset index to 0 *****************\n\n";
}
}
splitAndForeach('', 0, array() );
print "your results: \n";
print_r($results);
You could have two arrays: the alternatives and a current counter.
$alternatives = array(array('a', 'b', 'c'), array('b'), array('a', 'c'));
$counter = array(0, 0, 0);
Then, in a loop, you increment the "last digit" of the counter, and if that is equal to the number of alternatives for that position, you reset that "digit" to zero and increment the "digit" left to it. This works just like counting with decimal numbers.
The string for each step is built by concatenating the $alternatives[$i][$counter[$i]] for each digit.
You are finished when the "first digit" becomes as large as the number of alternatives for that digit.
Example: for the above variables, the counter would get the following values in the steps:
0,0,0
0,0,1
1,0,0 (overflow in the last two digit)
1,0,1
2,0,0 (overflow in the last two digits)
2,0,1
3,0,0 (finished, since the first "digit" has only 3 alternatives)

Replace non-specified array values with 0

I want to replace all array values with 0 except work and home.
Input:
$array = ['work', 'homework', 'home', 'sky', 'door']
My coding attempt:
$a = str_replace("work", "0", $array);
Expected output:
['work', 0, 'home', 0, 0]
Also my input data is coming from a user submission and the amount of array elements may be very large.
A bit more elegant and shorter solution.
$aArray = array('work','home','sky','door');
foreach($aArray as &$sValue)
{
if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}
The & operator is a pointer to the particular original string in the array. (instead of a copy of that string)
You can that way assign a new value to the string in the array. The only thing you may not do is anything that may disturb the order in the array, like unset() or key manipulation.
The resulting array of the example above will be
$aArray = array('work','home', 0, 0)
A loop will perform a series of actions many times. So, for each element in your array, you would check if it is equal to the one you want to change and if it is, change it. Also be sure to put quote marks around your strings
//Setup the array of string
$asting = array('work','home','sky','door')
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting);$i++){
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work' || $asting[$i] == 'home')
$asting[$i] = 0;
}
Here is some suggested reading:
http://www.php.net/manual/en/language.types.array.php
http://www.php.net/manual/en/language.control-structures.php
But if you are struggling on stuff such as looping, you may want to read some introductory programming material. Which should help you really understand what's going on.
A bit other and much quicker way, but true, need a loop:
//Setup the array of string
$asting = array('bar', 'market', 'work', 'home', 'sky', 'door');
//Setup the array of replacings
$replace = array('home', 'work');
//Loop them through str_replace() replacing with 0 or any other value...
foreach ($replace as $val) $asting = str_replace($val, 0, $asting);
//See what results brings:
print_r ($asting);
Will output:
Array
(
[0] => bar
[1] => market
[2] => 0
[3] => 0
[4] => sky
[5] => door
)
An alternative using array_map:
$original = array('work','home','sky','door');
$mapped = array_map(function($i){
$exclude = array('work','home');
return in_array($i, $exclude) ? 0 : $i;
}, $original);
you may try array_walk function:
function zeros(&$value)
{
if ($value != 'home' && $value != 'work'){$value = 0;}
}
$asting = array('work','home','sky','door','march');
array_walk($asting, 'zeros');
print_r($asting);
You can also give array as a parameter 1 and 2 on str_replace...
Just a small point to the for loop. Many dont realize the second comparing task is done every new iteration. So if it was a case of big array or calculation you could optimize loop a bit by doing:
for ($i = 0, $c = count($asting); $i < $c; $i++) {...}
You may also want to see http://php.net/manual/en/function.array-replace.php for original problem unless the code really is final :)
Try This
$your_array = array('work','home','sky','door');
$rep = array('home', 'work');
foreach($rep as $key=>$val){
$key = array_search($val, $your_array);
$your_array[$key] = 0;
}
print_r($your_array);
There are a few techniques on this page that make zero iterated function calls -- which is good performance-wise. For best maintainability, I recommend separating your list of targeted string as a lookup array. By modifying the original array values by reference, you can swiftly replace whole strings and null coalesce non-targeted values to 0.
Code: (Demo)
$array = ['work', 'homework', 'home', 'sky', 'door'];
$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);
foreach ($array as &$v) {
$v = $lookup[$v] ?? 0;
}
var_export($array);
Output:
array (
0 => 'work',
1 => 0,
2 => 'home',
3 => 0,
4 => 0,
)
You can very easily, cleanly extend your list of targeted strings by merely extending $keep.
If you don't want a classic loop, you can use the same technique without modifying the original array. (Demo)
var_export(
array_map(fn($v) => $lookup[$v] ?? 0, $array)
);
this my final code
//Setup the array of string
$asting = array('work','home','sky','door','march');
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
$asting[$i] = 20;
} elseif($asting[$i] == 'home'){
$asting[$i] = 30;
}else{
$asting[$i] = 0;
}
echo $asting[$i]."<br><br>";
$total += $asting[$i];
}
echo $total;

Categories