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);
Related
I want to sort an array given, for example:
"1; -2; 3.5; 4"
But my function doesn't work and if i try var_dump() i only got the numbers unsorted.
Could anyone please help me to understand ?
I put this numbers in example, but if anyone could explain me how to do also if i don't want to put any numbers within my function and to compile directly, for example with that command :
-> php insertion_sort.php "1; -2; 3.5; 4".
Thank you in advance for your help.
function swap($a, $b) {
$tmp;
$tmp = $a;
$a = $b;
$b = $tmp;
}
function insertion_sort($array) {
$array = array(1, -2, 3.5, 4);
$length = count($array);
for ($i = 0; $i < $length; $i++) {
$i_min = $i;
for ($j = $i+1; $j < $length; $j++) {
if ($array[$j] < $array[$i_min]) {
$i_min = $j;
swap($j, $i_min);
}
}
}
}
?>
This if I remember correctly is a bubble sort
function my_sort(&$array)
{
for ($i=0; $i<count($array)-1; $i++){
for ($j=0; ($j<count($array)-$i-1); $j++){
if( $array[$j] > $array[$j+1]) {
// swap
$t = $array[$j];
$array[$j] = $array[$j+1];
$array[$j+1] = $t;
}
}
}
}
$array = [1,4, -2, 3.5];
my_sort($array);
print_r($array);
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);
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);
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();
This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 7 years ago.
I need to do a bubble sort algorithm in PHP.
I want to know whether any one has any good examples that I can use, or an open source library which can do this.
I have a few spaces in a set (array), i want to fill these spaces with object (a person), so no space can have a male and a female, this why i am trying to find out a bubble sort algorithm.
My plan is to fill in any of the available spaces regardless of the gender, and after that sort them separately.
Thanks.
function bubble_sort($arr) {
$size = count($arr)-1;
for ($i=0; $i<$size; $i++) {
for ($j=0; $j<$size-$i; $j++) {
$k = $j+1;
if ($arr[$k] < $arr[$j]) {
// Swap elements at indices: $j, $k
list($arr[$j], $arr[$k]) = array($arr[$k], $arr[$j]);
}
}
}
return $arr;
}
For example:
$arr = array(1,3,2,8,5,7,4,0);
print("Before sorting");
print_r($arr);
$arr = bubble_sort($arr);
print("After sorting by using bubble sort");
print_r($arr);
Using bubble sort is a very bad idea. It has complexity of O(n^2).
You should use php usort, which is actually a merge sort implementation and guaranteed O(n*log(n)) complexity.
A sample code from the PHP Manual -
function cmp( $a, $b ) {
if( $a->weight == $b->weight ){ return 0 ; }
return ($a->weight < $b->weight) ? -1 : 1;
}
usort($unsortedObjectArray,'cmp');
$numbers = array(1,3,2,5,2);
$array_size = count($numbers);
echo "Numbers before sort: ";
for ( $i = 0; $i < $array_size; $i++ )
echo $numbers[$i];
echo "n";
for ( $i = 0; $i < $array_size; $i++ )
{
for ($j = 0; $j < $array_size; $j++ )
{
if ($numbers[$i] < $numbers[$j])
{
$temp = $numbers[$i];
$numbers[$i] = $numbers[$j];
$numbers[$j] = $temp;
}
}
}
echo "Numbers after sort: ";
for( $i = 0; $i < $array_size; $i++ )
echo $numbers[$i];
echo "n";
function bubble_sort($arr) {
$n = count($arr);
do {
$swapped = false;
for ($i = 0; $i < $n - 1; $i++) {
// swap when out of order
if ($arr[$i] > $arr[$i + 1]) {
$temp = $arr[$i];
$arr[$i] = $arr[$i + 1];
$arr[$i + 1] = $temp;
$swapped = true;
}
}
$n--;
}
while ($swapped);
return $arr;
}
function bubbleSort(array $arr)
{
$n = sizeof($arr);
for ($i = 1; $i < $n; $i++) {
for ($j = $n - 1; $j >= $i; $j--) {
if($arr[$j-1] > $arr[$j]) {
$tmp = $arr[$j - 1];
$arr[$j - 1] = $arr[$j];
$arr[$j] = $tmp;
}
}
}
return $arr;
}
// Example:
$arr = array(255,1,22,3,45,5);
$result = bubbleSort($arr);
print_r($result);
//====================================================
//------- improved version----------------------------
//====================================================
function bubbleSortImproved(array $arr)
{
$n = sizeof($arr);
for ($i = 1; $i < $n; $i++) {
$flag = false;
for ($j = $n - 1; $j >= $i; $j--) {
if($arr[$j-1] > $arr[$j]) {
$tmp = $arr[$j - 1];
$arr[$j - 1] = $arr[$j];
$arr[$j] = $tmp;
$flag = true;
}
}
if (!$flag) {
break;
}
}
return $arr;
}
// Example:
$arr = array(255,1,22,3,45,5);
$result = bubbleSortImproved($arr);
print_r($result);
Improved Bubble Sorting enjoy :)
$sortarr = array(3,5,15,3,2,6,7,50,1,4,5,2,100,9,3,2,6,7,13,18);
echo "<pre>";
// Array to be sorted
print_r($sortarr);
// Sorted Array
print_r(bubble_sort($sortarr));
echo "<pre>";
function bubble_sort($sortarr){
// Bubble sorting
$array_count = count($sortarr);
for($x = 0; $x < $array_count; $x++){
for($a = 0 ; $a < $array_count - 1 ; $a++){
if($a < $array_count ){
if($sortarr[$a] > $sortarr[$a + 1] ){
swap($sortarr, $a, $a+1);
}
}
}
}
return $sortarr;
}
function swap(&$arr, $a, $b) {
$tmp = $arr[$a];
$arr[$a] = $arr[$b];
$arr[$b] = $tmp;
}
Maybe someone finds useful my version of Bubble Sort:
function BubbleSort(&$L)
{
$rm_key = count($L);
while( --$rm_key > -1 )#after this the very first time it will point to the last element
for($i=0; $i<$rm_key; $i++)
if( $L[$i] > $L[$i+1] )
list($L[$i],$L[$i+1]) = array($L[$i+1],$L[$i]);
}
I got the swap idea (using list) from above comment.