Shuffling php string - php

How can I shuffle the php string?
I want to show all of the string in the shuffled output.
example input : abc
output :
abc
acb
bac
bca
cab
cba
my code :
function permutations() {
global $running;
global $characters;
global $bitmask;
if (count($running) == count($characters)) {
printf("%s\n", implode($running));
} else {
for ($i=0; $i<count($characters); $i++) {
if ( (($bitmask>>$i)&1) == 0 ) {
array_push($running, $characters[$i]);
$bitmask |= (1<<$i);
permutations();
array_pop($running);
}
}
}
}
fscanf(STDIN, '%s', $raw_input);
$characters = str_split($raw_input);
$running = array();
$bitmask = 0;
permutations();
always get error for the fscanf()

This is sample function for shuffling any characters. You can use only shuffle_string function for your purpose.
// direct function for shuffling characters of any string
function shuffle_string ($string) {
$string_len = strlen($string);
permute($string, 0, $string_len);
}
// to generate and echo all N! permutations of $string.
function permute($string, $i, $n) {
if ($i == $n) {
echo "$string\n";
} else {
for ($j = $i; $j < $n; $j++) {
swap($string, $i, $j);
permute($string, $i+1, $n);
swap($string, $i, $j); // backtracking.
}
}
}
// to swap the character at position $i and $j of $string.
function swap(&$string, $i, $j) {
$temp = $string[$i];
$string[$i] = $string[$j];
$string[$j] = $temp;
}
shuffle_string('Hey');

Hope this will help:
<?php
function permutations($set)
{
$solutions=array();
$n=count($set);
$p=array_keys($set);
$i=1;
while ($i<$n)
{
if ($p[$i]>0)
{
$p[$i]--;
$j=0;
if ($i%2==1)
$j=$p[$i];
//swap
$tmp=$set[$j];
$set[$j]=$set[$i];
$set[$i]=$tmp;
$i=1;
$solutions[]=$set;
}
elseif ($p[$i]==0)
{
$p[$i]=$i;
$i++;
}
}
return $solutions;
}
$string = 'abc';
$string = str_split($string);
$all_per = permutations($string);
foreach($all_per as $key => $value){
$str[]= implode(',',$value);
}
print_r($str);

Related

Why the utf8 characters are seeming like question mark?

I have a form in my website. I am reviewing the form values on ui panel. Function is doing if the the word length is greater than 12 it puts a space to next to it. But when I print the value I am getting error if value is utf8.
$text= 'üğqwoweğofkeiasş övafevpğeüqrg qğekqrğofteölzfs';
function parser($str, $parse) {
$strlength = strlen($str);
$counter = 0;
$query = '';
if($strlength > $parse) {
for($i = 0; $i < $strlength; $i++) {
if($str[$i] != ' ') {
$counter++;
}
if($counter == $parse) {
$query.=$str[$i];
$query.=' ';
$counter = 0;
}
if($counter != $parse) {
$query.=$str[$i];
}
if($counter != $parse & $str[$i] == ' ') {
$counter = 0;
}
}
return $query;
}
else {
return $str;
}
}
echo parser($text,12);
Output is:
'üğqwoweğo ofkeiasş övafevpğe� üqrg qğekqrğoft teölzfs'
and it's not happening all the times just sometimes; I can't understand why is that.
Code:
function parser($string, $max_length = 12)
{
$chars = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
$i = 0;
foreach ($chars as $index => $char)
{
if ($char === ' ') { $i = 0; }
else { $i++; }
if ($i >= $max_length)
{
$chars[$index] = $char . ' ';
$i = 0;
}
}
return implode('', $chars);
}
$result = parser('üğqwoweğofkeiasş övafevpğeüqrg qğekqrğofteölzfs');
result: üğqwoweğofke iasş övafevpğeüqr g qğekqrğofteö lzfsuser

String compression in php

Here is my input
aaaabbaaaababbbcccccccccccc
And this is my expected output
a4b2a4b1a1b3c12
I tried like doing foreach and then concating the count of values. It seems like brutforcing. Is there any way to do it efficiently in php .
Help pls
You can use regular expression to get the result
preg_match_all('/(.)\1*/', $str, $m, PREG_SET_ORDER);
$m = array_map(function($i) { return $i[1] . strlen($i[0]); } , $m);
echo implode('', $m); // a4b2a4b1a1b3c12
demo
Here's an example of how to do it with a few for loops (encoding and decoding):
$input = 'aaaabbaaaababbbcccccccccccc';
$encoded = SillyEncoding::encode($input);
$decoded = SillyEncoding::decode($encoded);
echo "input = \t", var_export($input, true), "\n";
echo "encoded = \t", var_export($encoded, true), "\n";
echo "decoded = \t", var_export($decoded, true), "\n";
Output:
input = 'aaaabbaaaababbbcccccccccccc'
encoded = 'a4b2a4b1a1b3c12'
decoded = 'aaaabbaaaababbbcccccccccccc'
The SillyEncoding class:
class SillyEncoding
{
private static $digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
static function encode($string)
{
$output = '';
if (strlen($string) > 0) {
$count = 0;
$char = $string[0];
for ($i = 0; isset($string[$i]); ++$i) {
if (isset(self::$digits[$string[$i]])) {
throw new \InvalidArgumentException(sprintf('The input string must not contain a digit at offset %d, got "%s"', $i, $string[$i]));
}
if ($string[$i] === $char) {
++$count;
} else {
$output .= "{$char}{$count}";
$count = 1;
$char = $string[$i];
}
if (!isset($string[$i + 1])) {
$output .= "{$char}{$count}";
}
}
}
return $output;
}
static function decode($string)
{
$output = '';
$length = strlen($string);
if ($length > 0) {
$char = $string[0];
$count = null;
if ($length < 2) {
throw new \InvalidArgumentException(sprintf('Input string must be empty or at least 2 bytes long, got %d bytes', $length));
}
if (isset(self::$digits[$string[0]])) {
throw new \InvalidArgumentException(sprintf('Input string must not start with a digit, got "%s"', $string[0]));
}
for ($i = 1; isset($string[$i]); ++$i) {
$isDigit = isset(self::$digits[$string[$i]]);
if ($isDigit) {
$count .= $string[$i];
}
if (!$isDigit || !isset($string[$i + 1])) {
if (null === $count) {
throw new \InvalidArgumentException(sprintf('Expected a digit at offset %d, got "%s"', $i, $string[$i]));
}
$count = (int) $count;
for ($j = 0; $j < $count; ++$j) {
$output .= $char;
}
$char = $string[$i];
$count = null;
}
}
}
return $output;
}
}
A few things to note:
this isn't an efficient compression algorithm - it might reduce the size if there are many repeated characters, but if you feed it "normal" text the output will be about twice the size of the input
the input cannot contain any digits whatsoever (OP: "the input will be strictly alphabets")
$str = str_split('aaaabbaaaababbbcccccccccccc');
$count = 0;
$a=$result=$b='';
for ($i=0; $i <= count($str); $i++) {
if($a==$str[$i]){
$count++;
$result = $a.$count;
} else{
if ($count > 0) {
$b .= $result;
}
$count = 1;
$a = $str[$i];
$result = $a.$count;
}
}
print_r($b);
See result

php code to reverse a string using paramaterized function

Below is my Code to Reverse a String..
The code runs well but I need to wrap this code inside Paramaterized function
in which user pass a string inside function and get return output.
<?php
$string = trim("This");
$len =strlen($string);
$stringExp = str_split($string);
for ($i = $len-1; $i >=0;$i--)
{
echo $stringExp[$i];
}
?>
for Ex -
I want above string reversal code logic like below function...
<?php
$str = "rahul";
echo reverse($str);
function reverse($str)
{
for ($i = 0, $j = strlen($str) - 1; $i < $j; $i++, $j--) {
$tmp = $str[$i];
$str[$i] = $str[$j];
$str[$j] = $tmp;
}
return $str;
}
?>
Simply try this
$str = "rahul";
echo reverse($str);
function reverse($str)
{
$tmp = '';
for($i = (strlen($str)-1);$i >= 0; $i--) {
$tmp .= $str[$i];
}
return $tmp;
}
There is strev() function which does it but if you need write your own here is the code
$str = "abcde";
function reverse ($str)
{
$output = '';
for ($i = strlen($str)-1; $i >= 0 ; --$i) {
$output .= $str[$i];
}
return $output;
}
echo reverse($str);

Replacing char with number

There is this code that I am doing
Example a string of this value
z12z
I want to generate it
0120
0121
0122
... until 0129
then
1120
1121
1122
... until 1129
until 9129 , its sort of like two four loop, but I got no idea how to implement this.
and the issue is z can be anywhere and it can be zzzz
where it will be
0000 until 9999
or it could also be z0z0, z could be anywhere. What kind of method should I use for such.
Thanks!
I am doing it with php
for every occurance of letter 'z' , i will need do a for loop to generate the possible number, from 0 to 9, you can say z is a for loop for 0 to 9, e.g z555 will yield 0555,1555,2555,3555,4555,5555,6555,7555,8555,9555 , issue is z can occur with a possibility of 0 to 4, like z555 , zz55,zzz5, zzzz, and z position is random , I need generate the possible z number output
z position could be 55z5 , 5z55 , 5zz5 . its does not have a fix position.
<?php
$numbers = array();
for ($i = 0; $i <= 9; $i++){
for ($j = 120; $j <= 129; $j++){
$numbers[] = $i . $j;
}
}
print_r('<pre>');
print_r($numbers);
A better answer that take the z char is:
<?php
function strReplaceNth($search, $replace, $subject, $nth)
{
$found = preg_match_all('/' . preg_quote($search) . '/', $subject, $matches, PREG_OFFSET_CAPTURE);
if (false !== $found && $found > $nth) {
return substr_replace($subject, $replace, $matches[0][$nth][1], strlen($search));
}
return $subject;
}
function cleanup($numbers, $char)
{
$tmp = array();
for ($i = 0; $i < count($numbers); $i++){
if (strpos($numbers[$i], $char) === false){
$tmp[] = $numbers[$i];
}
}
return $tmp;
}
function generateNumber($numbers, $char)
{
if (!is_array($numbers)){
if (strpos($numbers, $char) === false){
return array($numbers);
} else {
$tmp = $numbers;
$numbers = array();
for ($j = 0; $j <= 9; $j++){
$numbers[] = strReplaceNth($char, $j, $tmp, 0);
}
return generateNumber($numbers, $char);
}
} else {
for ($i = 0; $i < count($numbers); $i++){
if (strpos($numbers[$i], $char) === false){
return cleanup($numbers, $char);
} else {
$numbers = array_merge($numbers, generateNumber($numbers[$i], $char));
}
}
return generateNumber($numbers, $char);
}
}
function getCharPos($string, $char)
{
$pos = array();
for ($i = 0; $i < strlen($string); $i++){
if (substr($string, $i, 1) == $char){
$pos[] = $i;
}
}
return $pos;
}
$string = 'z12z';
$char = 'z';
$occurences = getCharPos($string, $char);
$numbers = array();
if (count($occurences) > 0){
$numbers = generateNumber($string, $char);
} else {
$numbers[] = $string;
}
print_r('<pre>');
print_r($numbers);die();

Cannot access the function return variable

cannot return function value, if i print inside the function the value had printed when i make return variable that that it will be return zero my code following
function permute($str,$i,$n) {
$b="";
if ($i == $n)
$b .=$str.",";
else {
for ($j = $i; $j < $n; $j++) {
swap($str,$i,$j);
permute($str, $i+1, $n);
swap($str,$i,$j); // backtrack.
}
}
return $b;
}
function swap(&$str,$i,$j) {
$temp = $str[$i];
$str[$i] = $str[$j];
$str[$j] = $temp;
}
$str = "375";
$test=permute($str,0,strlen($str));
echo $test;
function permute($str,$i,$n) {
....
$b . = permute($str, $i+1, $n);
....
return $b;
}
You are not using the result of inner call.
You have to use the return value in the loop
<?php
function permute($str,$i,$n){
$b=NULL;
if ($i == $n){
$b= $str.",";
}else {
for ($j = $i; $j < $n; $j++){
swap($str,$i,$j);
$b.=permute($str, $i+1, $n); //ERROR HERE
swap($str,$i,$j); // backtrack.
}
}
return $b;
}
This doesn't tell you exactly why your function was wrong, but this is how you would generate an array of possible permutations:
// permute prefix $s with set $r and store results in $a
function permute($r, array &$a, $s = '')
{
if (!strlen($r)) {
$a[] = $s; // store result
return;
}
for ($i = 0; $i < strlen($r); ++$i) {
// recurse
permute(substr_replace($tmp = $r, '', $i, 1), $a, $s . $r[$i]);
}
}
$str = "375";
$res = [];
permute($str, $res);
print_r($res);

Categories