I am trying to get a list of all substring of input.
for input=a, substrings {'','a'}
for input=ab, substrings {'','a','b','ab','ba'}
for input=abc, substrings {'','a','b','c','ab','bc','ca','ba','cb','ac','abc','acb','bac','bca','cab','cba'}
and so on.
The code I tried is here
function get_substr($string){
$array=str_split($string);
static $k=0;
for ($i=0; $i <count($array) ; $i++) {
for ($j=0; $j <count($array) ; $j++) {
$new_array[$k]=substr($string, $i, $j - $i + 1);
$k++;
}
}
return($new_array);
}
and i have o/p of this code as below
Please suggest me what changes I need or any alternative idea to do this work.
function find_posible_substr($input){
$input_len = strlen($input);
$possubstr = array();
$i = 0;
while($i < $input_len){
$j = 0;
while($j < $input_len){
$possubstr[] = substr($input, $j, $i + 1);
if(substr($input, $j, $i + 1) == $input){
break;
}
$j++;
}
$i++;
}
return $possubstr;
}
I don't know if you are still on this problem. But I want to share mine anyway.
If the input is abc then the output will be as below.
Array
(
[0] => a
[1] => b
[2] => c
[3] => ab
[4] => bc
[5] => c
[6] => abc
)
<?php
// function to generate and print all N! permutations of $str. (N = strlen($str)).
function permute($str,$i = null,$n = null) {
if(is_null($n)) $n = mb_strlen($str);
if(is_null($i)) $i = 0;
if ($i == $n)
print "$str \n";
else {
for ($j = $i; $j < $n; $j++) {
swap($str,$i,$j);
permute($str, $i+1, $n);
swap($str,$i,$j); // backtrack.
}
}
}
// function to swap the char at pos $i and $j of $str.
function swap(&$str,$i,$j) {
$temp = $str[$i];
$str[$i] = $str[$j];
$str[$j] = $temp;
}
$str = "hey";
permute($str); // call the function.
see this SO answer
$str = "abcd";
$str_arr = str_split($str);
for($i = 0; $i <= count($str_arr)-1 ;$i++){
for($j = $i+1 ; $j <= count($str_arr) ; $j++){
for($k = $i; $k <= $j-1; $k++){
$subsrt1.= $str_arr[$k];
}
$substr[] = $subsrt1;
$subsrt1 = '';
}
}
print_r($substr);
Related
I have created an array dynamically like this way
$names = array();
for ($i = 0; $i < 100; $i++) {
$names[] = $i;
}
then created part
$parts = count($names) / 20;
and created a sub array then loop through the parts
$j = 0;
for ($i = 0; $i < $parts; $i++) {
echo "Part" . $i."<br>";
$newarray = array_slice($names, $j, 20);
for ($i = 0; $i < count($newarray); $i++) {
echo $i;
}
$j = $j + 20;
}
The problem is that this code displays from zero to 19 It doesn't display the other parts
Both the inner and outer loops use the same control variable $i, so just change the inner one...
$j = 0;
for ($i = 0; $i < $parts; $i++) {
echo "Part" . $i."<br>";
$newarray = array_slice($names, $j, 20);
for ($i1 = 0; $i1 < count($newarray); $i1++) {
echo $i1;
}
$j = $j + 20;
}
I wanted to have a way to get all combinations for all given numbers with given array length.
In my project the array size usually is 7. So I write a test code like this to see if I can get all needed combinations. The important part is every result array must be unique and maximum array size must be 7.
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7];
$arraysize = 7;
$subset = [];
$count = count($numbers);
for ($i = 0; $i < $count; $i++) {
$subset[] = $numbers[$i];
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
$subset[] = $numbers[$i] . $numbers[$j];
}
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
for ($k=$j; $k < $count; $k++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k];
}
}
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
for ($k=$j; $k < $count; $k++) {
for ($l=$k; $l < $count; $l++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k] . $numbers[$l];
}
}
}
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
for ($k=$j; $k < $count; $k++) {
for ($l=$k; $l < $count; $l++) {
for ($m=$l; $m < $count; $m++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k] . $numbers[$l] . $numbers[$m];
}
}
}
}
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
for ($k=$j; $k < $count; $k++) {
for ($l=$k; $l < $count; $l++) {
for ($m=$l; $m < $count; $m++) {
for ($n=$m; $n < $count; $n++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k] . $numbers[$l] . $numbers[$m] . $numbers[$n];
}
}
}
}
}
}
for ($i=0; $i < $count; $i++) {
for ($j=$i; $j < $count; $j++) {
for ($k=$j; $k < $count; $k++) {
for ($l=$k; $l < $count; $l++) {
for ($m=$l; $m < $count; $m++) {
for ($n=$m; $n < $count; $n++) {
for ($o=$n; $o < $count; $o++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k] . $numbers[$l] . $numbers[$m] . $numbers[$n] . $numbers[$o];
}
}
}
}
}
}
}
echo "<pre>";
print_r($subset);
echo "</pre>";
?>
When I run this code I get the combinations like I wanted (I make the combinations as string to see the results clearly but normally every result item in $subset array must be array)
With this code I can get all unique combinations.
But as you can see this code is ugly. I tried to make this a recursive function but I failed. Could anyone point me to right direction to get the exact same results like this? (every item in $subset array normally must be an array that contains digits)
You can simplify this logic (and make the code less ugly) without needing to go recursive by using:
for ($i = 0; $i < $count; $i++) {
$subset[] = $numbers[$i];
for ($j=$i; $j < $count; $j++) {
$subset[] = $numbers[$i] . $numbers[$j];
for ($k=$j; $k < $count; $k++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k];
for ($l=$k; $l < $count; $l++) {
$subset[] = $numbers[$i] . $numbers[$j] . $numbers[$k] . $numbers[$l];
}
}
}
}
the following will work in all cases even if you have duplicate numbers in your array
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14);
sort($array); //in case it 's not sorted
$array = array_slice($array,-7);
$num = count($array );
$total = pow(2, $num);
$result= array();
$element='';
for ($i = 0; $i < $total; $i++)
{
for ($j = 0; $j < $num; $j++)
{
if (pow(2, $j) & $i)
{
$element=$element.$array [$j];
}
}
$result[]=$element;
$element='';
}
print_r($result);
This implementation returns all the combinations of all items (77 = 823542 combinations of 7 items):
function combine_all(array $numbers) {
$count = count($numbers);
$result = array_map('strval', $numbers);
for($i = 1; $i < $count; ++$i) {
$combinations = array_slice($result, pow($count, $i-1));
foreach($numbers as $number) {
foreach($combinations as $combination) {
$result[] = $number . ',' . $combination;
}
}
}
return $result;
}
When using print_r to output the data, it can perform very slowly:
$array = array_fill(0, pow(7,7), '');
$t = microtime(true);
echo '<pre>';
print_r($array);
echo '</pre>';
echo microtime(true) - $t;
// 0.75329303741455
$t = microtime(true);
echo '<pre>';
print_r( combine_all(array(1,2,3,4,5,6,7)) );
echo '</pre>';
echo microtime(true) - $t;
// 1.7037351131439
$t = microtime(true);
combine_all(array(1,2,3,4,5,6,7));
echo microtime(true) - $t;
//0.75869607925415
To restrict the items number, use the array_slice function:
combine_all(array_slice($numbers, 0, 7));
If you really want a recursive function, you could do something like this:
function combine_all(array $numbers, $cnt=null, $baseCombination=null) {
if( $baseCombination === null ) {
$cnt = count($numbers);
}
if( $cnt > 0 ) {
$result = array();
foreach($numbers as $number) {
$combination = $number . ',' . $baseCombination;
$result[] = $combination;
$result = array_merge($result, combine_all($numbers, $cnt-1, $combination));
}
return $result;
}
return array();
}
But it takes too much memory.
I finally found out a way to add recursive function to create unique combinations from given numbers:
$numbers = [1, 2, 3, 4, 5, 6, 7];
function subsetSumRecursive($numbers, $arraySize, $level = 1, $i = 0, $addThis = [])
{
// If this is the last layer, use a different method to pass the number.
if ($level == $arraySize) {
$result = [];
for (; $i < count($numbers); $i++) {
$result[] = array_merge($addThis, array($numbers[$i]));
}
return $result;
}
$result = [];
$nextLevel = $level + 1;
for (; $i < count($numbers); $i++) {
// Add the data given from upper level to current iterated number and pass
// the new data to a deeper level.
$newAdd = array_merge($addThis, array($numbers[$i]));
$temp = subsetSumRecursive($numbers, $arraySize, $nextLevel, $i, $newAdd);
$result = array_merge($result, $temp);
}
return $result;
}
echo "<pre>";
print_r(subsetSumRecursive($numbers, 7));
echo "</pre>";
Here I need an array of all the numbers generated by permutation and also here i am giving n and k from a html form.
function combination_number($k,$n){
$n = intval($n);
$k = intval($k);
if ($k > $n){
return 0;
} elseif ($n == $k) {
return 1;
} else {
if ($k >= $n - $k){
$l = $k+1;
for ($i = $l+1 ; $i <= $n ; $i++)
$l *= $i;
$m = 1;
for ($i = 2 ; $i <= $n-$k ; $i++)
$m *= $i;
} else {
$l = ($n-$k) + 1;
for ($i = $l+1 ; $i <= $n ; $i++)
$l *= $i;
$m = 1;
for ($i = 2 ; $i <= $k ; $i++)
$m *= $i;
}
}
return $l/$m;
}
function array_combination($le, $set){
$lk = combination_number($le, count($set));
$ret = array_fill(0, $lk, array_fill(0, $le, '') );
$temp = array();
for ($i = 0 ; $i < $le ; $i++)
$temp[$i] = $i;
$ret[0] = $temp;
for ($i = 1 ; $i < $lk ; $i++){
if ($temp[$le-1] != count($set)-1){
$temp[$le-1]++;
} else {
$od = -1;
for ($j = $le-2 ; $j >= 0 ; $j--)
if ($temp[$j]+1 != $temp[$j+1]){
$od = $j;
break;
}
if ($od == -1)
break;
$temp[$od]++;
for ($j = $od+1 ; $j < $le ; $j++)
$temp[$j] = $temp[$od]+$j-$od;
}
$ret[$i] = $temp;
}
for ($i = 0 ; $i < $lk ; $i++)
for ($j = 0 ; $j < $le ; $j++)
$ret[$i][$j] = $set[$ret[$i][$j]];
return $ret;
}
$number = $_REQUEST['number'];
for($i=0;$i<$number;$i++)
{
$arr[$i]=$i+1;
}
$k = $_REQUEST['select'];
$permutations = array_combination($k, $arr);
echo "<pre>";
print_r($permutations);
This code is working but its not giving all the numbers generated by Permutation. I need those numbers also. Please tell me how can i get those? Please help.
I'm not sure if it is the best solution, but this seems to do what you want
function array_combination($le, $set){
// Your existing code
// …
for ($i = 0 ; $i < $lk ; $i++)
for ($j = 0 ; $j < $le ; $j++)
$ret[$i][$j] = $set[$ret[$i][$j]];
// Changes start here
$desiredArray = $ret;
foreach($ret as $innerArray)
{
$desiredArray[] = array_reverse($innerArray);
}
return $desiredArray;
}
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.
I writting assignment about heap sort in php. I am in a little bit difficult situation. Please help me. Any one who suggest me the code.
Thanks in advance.
Have you googled this???
Check this out.
Heap Sorting in PHP
<?php
function build_heap(&$array, $i, $t){
$tmp_var = $array[$i];
$j = $i * 2 + 1;
while ($j <= $t) {
if($j < $t)
if($array[$j] < $array[$j + 1]) {
$j = $j + 1;
}
if($tmp_var < $array[$j]) {
$array[$i] = $array[$j];
$i = $j;
$j = 2 * $i + 1;
} else {
$j = $t + 1;
}
}
$array[$i] = $tmp_var;
}
function heap_sort(&$array) {
//This will heapify the array
$init = (int)floor((count($array) - 1) / 2);
// Thanks jimHuang for bug report
for($i=$init; $i >= 0; $i--){
$count = count($array) - 1;
build_heap($array, $i, $count);
}
//swaping of nodes
for ($i = (count($array) - 1); $i >= 1; $i--) {
$tmp_var = $array[0];
$array [0] = $array [$i];
$array [$i] = $tmp_var;
build_heap($array, 0, $i - 1);
}
}
// Demo
$array = array(9,8,7,6,5,4,3,2,1,0,10,1000,0);
heap_sort($array);
print_r($array);
?>