How do I solve this problem statement using PHP? - php

Suppose a number is given which is of positive integer type, e.g: 312. Please help me to write a program in PHP which convert that given number to a new number having same number of digits and all the digits of the new number must be equal to any of the digits of the given number (e.g: 333, 111, 222 by either decrementing or incrementing each digit by 1 at a time only). But print only that sequence of digits which takes lesser number of steps to generate the sequence and also print the number of steps taken to generate that sequence.
Explanation:
Input: A positive integer N (e.g: 312)
converting the number(312) to the sequence of 3
3 2 2
3 3 2
3 3 3
here number of steps = 3
Now, converting the number(312) to the sequence of 1
2 1 2
1 1 2
1 1 1
here number of steps = 3
and finally converting the number(312) to the sequence of 2
2 1 2
2 2 2
here number of steps = 2
So, Output: 222
Number of steps: 2
Here's what I tried but lost
<?php
$num = 312;
$arr_num = array_map('intval', str_split($num));
//steps taken for each sequence will be stored in this array
$steps = array();
//printing number
for($i = 0; $i < count($arr_num); $i++)
echo $arr_num[$i];
//calculation
for($i = 0; $i < count($arr_num); $i++) {
$count = 0;
for($j = 0; $j < count($arr_num); $j++) {
if($arr_num[$i] == $arr_num[$j])
++$j;
elseif($arr_num[$i] > $arr_num[$j]) {
while($arr_num[$j] != $arr[$i]) {
$arr_num[$j] += 1;
$count++;
}
}
else {
while($arr_num[$j] != $arr_num[$i]) {
$arr_num[$j] -= 1;
$count++;
}
}
}
//pushing the count to steps array for each sequence
array_push($steps, $count);
}
//I am stuck here...can't find the further solution
?>

This works (according to my very quick testing)):
$intIn = 312;
# function changeDigits( $intIn ) { // uncomment for function
$digits = str_split( $intIn ); // convert to array of digits
$numerOfDigits = count($digits);
$numberOfSteps = array();
# check each digit in number
for ($i=0; $i < $numerOfDigits; $i++) {
$numberOfSteps[$i] = 0;
$currentDigit = $digits[$i];
# count the number of inc/decrements to change the other digits to this digit
foreach($digits as $otherDigit) {
if ($currentDigit > $otherDigit) $numberOfSteps[$i] += $currentDigit - $otherDigit;
if ($currentDigit < $otherDigit) $numberOfSteps[$i] += $otherDigit - $currentDigit;
}
}
$digitKey = array_search( min($numberOfSteps), $numberOfSteps );
echo 'Number of Steps: ' . $numberOfSteps[$digitKey] . PHP_EOL; // (or '<br>')
echo 'New number = ' . str_repeat( $digits[$digitKey], $numerOfDigits );
#}
# changeDigits(312);

Demo
I devepled this code. please have a look once
<?php
function find_output($input)
{
$digits = str_split($input);
foreach ($digits as $index => $d) {
$new_array = $digits;
unset($new_array[$index]);
$sum = 0;
foreach ($new_array as $value) {
$sum += abs($d - $value);
}
$final_array[$d] = $sum;
}
$steps = min($final_array);
echo "steps : " . $steps . '<br>';
$final_value = array_search(min($final_array), $final_array);
echo "Output: " . implode(array_fill(0, count($digits), $final_value));
}
find_output(819);
?>

<?php
class SeqSolver
{
public function solve($str_num)
{
if(!ctype_digit($str_num))
throw new Exception('Invalid input. Input string must contain digits between 0 and 9 only.');
$digits = str_split($str_num);
$length = count($digits);
foreach(array_unique($digits) as $digit)
$results[$digit] = $this->stepsToSequence($str_num, $digit);
//var_export($results);
$min_keys = array_keys($results, min($results));
// Prepare result
$result['input'] = $str_num;
foreach($min_keys as $key)
$result['solutions'][] = [
'sequence' => str_repeat($key, $length),
'steps' => $results[$key]
];
return $result;
}
public function stepsToSequence($str_num, $target_digit) {
$digits = str_split($str_num);
$steps = 0;
foreach($digits as $digit)
$steps += abs($digit - $target_digit);
return $steps;
}
}
Example use:
$solver = new SeqSolver;
foreach(['312', '334', '39'] as $input) {
$result = $solver->solve($input);
var_export($result);
echo "\n";
}
Output:
array (
'input' => '312',
'solutions' =>
array (
0 =>
array (
'sequence' => '222',
'steps' => 2,
),
),
)
array (
'input' => '334',
'solutions' =>
array (
0 =>
array (
'sequence' => '333',
'steps' => 1,
),
),
)
array (
'input' => '39',
'solutions' =>
array (
0 =>
array (
'sequence' => '33',
'steps' => 6,
),
1 =>
array (
'sequence' => '99',
'steps' => 6,
),
),
)

I think this will do the job.
<?php
$input = 312;
$input_array = [];
for($x=0;$x<3;$x++) {
array_push($input_array,strval($input)[$x]);
}
function equalize($input_array, $mark) {
$i = 0;
for($x=0;$x<count($input_array);$x++) {
$input_array[$x] = intval($input_array[$x]);
#print($input_array[$x]);
while($input_array[$x] != $mark) {
if($input_array[$x] < $mark) {
$input_array[$x] = $input_array[$x] + 1;
$i++;
}
else {
$input_array[$x] = $input_array[$x] - 1;
$i++;
}
}
}
$output_val = intval($input_array[0] .$input_array[1] .$input_array[2]);
return $output = [$output_val,$i];
}
#to first
$mark = $input_array[0];
$output = equalize($input_array, $mark);
#to second
$mark = $input_array[1];
$data = equalize($input_array, $mark);
if($data[1] < $output[1]) {
$output = $data;
}
#to last
$mark = $input_array[2];
$data = equalize($input_array, $mark);
if($data[1] < $output[1]) {
$output = $data;
}
echo 'Digit: ' .$output[0] .'<br/>';
echo 'Number of steps: ' .$output[1];
?>

Related

PHP Array Keep Data and Calculating By Its Index

I have a list of number in array. Here's my example data:
Person 1 => 20, 40, 50
Person 2 => 10, 20, 40
Person 3 => 20, 20, 30
I want to ask, how to put their scores to an array and calculate it by it index? My code to create this array:
$indeksarr = 1;
$temparr[$indeksarr] = array();
$num = 3;
while($grade = $query->fetch_array()) <-- basically get score from DB (only return score for each student)
{
for($i=1; $i <= $num; $i++)
{
$newdata = array($indeksarr => $grade);
$temparr[$indeksarr][] = $newdata;
$indeksarr++;
}
}
for($i=1; $i <= $num; $i++)
{
print_r($temparr[$i]);
}
My code result:
Result[1] = 20
Result[2] = 10
The result that I want:
Result[1] = 50 ( <- 20+10+20 ) <- all from array index 1
Result[2] = 80 ( <- 40+20+20 ) <- all from array index 2
Result[3] = 120 ( <- 50+40+30 ) <- all from array index 3
Any idea to fix my array?
Please try below code once, it might help for dynamic values also.
while ($grade = $query->fetch_array()) {
//$grdata = explode(",", $grade); // if those are comma separated values
$grdata = $grade;
for ($j = 0, $k = 1; $j < count($grdata); $j++, $k++) {
if (isset($temparr[$k])) {
$temparr[$k] = $temparr[$k] + $grdata[$j];
} else {
$temparr[$k] = $grdata[$j];
}
}
}
print_r($temparr);
biuld array like below
$persons = array('Person1'=>array(20,40,50),'Person2' => array(10, 20, 40),'Person3' => array(20, 20, 30));
//than perform below function
$array_sum = array_reduce($persons,"abb");
function abb($a,$b)
{
foreach($b as $key=>$value)
{
if(isset($a[$key]))
$a[$key] += $value;
else
$a[$key] = $value;
}
return $a;
}
var_dump($array_sum);
o/p
array (size=3)
0 => int 50
1 => int 80
2 => int 120
try this:
$result = array();
$start_index = 1;
$stop_index = 3;
while($grade = $query->fetch_array()) //<-- basically get score from DB (only return score for each student)
{
// grade = array('Person 1' => array(20,10,20));
$values = array_values($grade);
$result[$start_index] = array_sum($values[0]);
if ($start_index == $stop_index) break; // stop when it reach stop_index
$start_index++;
}
echo "<pre>";
print_r($result);
echo "</pre>";
die;
Here's a simple alternative using array_walk and array_sum:
$subTotal = [[0,0,0],[0,0,0],[0,0,0]];
$line = 0;
function walk($item, $key) {
global $subTotal;
global $line;
$subTotal[$key][$line] = $item;
}
$array = [
[20, 40, 50],
[10, 20, 40],
[20, 20, 30]
];
$finalArray = [];
array_walk($array[0], 'walk');
$line = 1;
array_walk($array[1], 'walk');
$line = 2;
array_walk($array[2], 'walk');
$finalArray[] = array_sum($subTotal[0]);
$finalArray[] = array_sum($subTotal[1]);
$finalArray[] = array_sum($subTotal[2]);
// Will print '50, 80, 120, '
foreach($finalArray as $total) {
echo $total.', ';
}
Hope this helps!

Generate distinct random numbers using procedural code

I have been trying to generate distinct random numbers using procedural code. But i am failing to do it. Please help me in this regard. thanks in advance.
<?php
$rnd_array = array(0,0,0,0,0,0,0,0,0,0);
$a = 1;
for ($i=0; $a <= 10 ; $i++)
{
echo $rnd = rand() % 10;
echo "\t \t";
for ($j=0; $j < 10 ; $j++)
{
if ($rnd == $rnd_array[$j])
{
$flag = true;
break;
}
else
{
$flag = false;
}
}
if ($flag == false)
{
$rnd_array[$a] = $rnd;
$a++;
}
}
echo "<br> <br>";
for ($k=0; $k < 10 ; $k++)
{
echo $rnd_array[$k];
echo "\t \t";
}
?>
I would use a somewhat different logic - start with an empty array, generate a random number, put it into the array if the array doesn't already contain it. Repeat until your array contains as many elements as you want it to.
Here's a simple example:
$num = 10;
$min = 1;
$max = 100;
$array = [];
while (count($array) < $num) {
$random = mt_rand($min, $max);
if (!in_array($random, $array)) {
$array[] = $random;
}
}
10 distincts random numbers
<?php
$numbers = array();
$i = 0;
while($i < 10){
$new = rand();
$known = false;
foreach($numbers as $key => $value){
if($value == $new ){
$known = true;
break;
}
}
if(!$known){
$numbers[$i]=$new;
$i++;
}
}
var_dump($numbers);
?>
Because array length is equal to range of generated random value
$rnd_array = range(0,9);
shuffle($rnd_array);
print_r($rnd_array);
Array
(
[0] => 9
[1] => 0
[2] => 5
[3] => 3
[4] => 6
[5] => 4
[6] => 2
[7] => 7
[8] => 1
[9] => 8
)

Duplicate values multi array

As the title states I'm searching for a unique solution in multi arrays. PHP is not my world so I can't make up a good and fast solution.
I basically get this from the database: http://pastebin.com/vYhFCuYw .
I want to check on the 'id' key, and if the array contains a duplicate 'id', then the 'aantal' should be added to each other.
So basically the output has to be this: http://pastebin.com/0TXRrwLs .
Thanks in advance!
EDIT
As asked, attempt 1 out of many:
function checkDuplicates($array) {
$temp = array();
foreach($array as $k) {
foreach ($array as $v) {
$t_id = $k['id'];
$t_naam = $k['naam'];
$t_percentage = $k['percentage'];
$t_aantal = $k['aantal'];
if ($k['id'] == $v['id']) {
$t_aantal += $k['aantal'];
array_push($temp, array(
'id' => $t_id,
'naam' => $t_naam,
'percentage' => $t_percentage,
'aantal' => $t_aantal,
)
);
}
}
}
return $temp;
}
How about this code, each 'aantal' has initial value of 1, and duplicated id have their aantal incremented mutually, and duplicated id's are not suppressed. As your first array index is 0-based numeric, so we don't consider this dimension as a hash array, but rather a normal array.
UPDATED: id's can be duplicated 2 times, 3 times, 4 times, ...
<?php
//
// duplicate elements are not suppressed:
//
function checkDuplicates($xarr) {
//
$xarrDone = array();
//
$n = count($xarr);
//
for($i = 0; $i < $n; $i++)
{
if(! isset($xarrDone[$i]))
{
$id0 = $xarr[$i]['id'];
$hasId0 = array();
for($j = $i + 1; $j < $n; $j++)
{
if($xarr[$j]['id'] == $id0)
{
$hasId0[] = $j;
}
}
$n1 = count($hasId0);
if($n1 > 0)
{
$xarr[$i]['aantal'] += $n1;
$xarrDone[$i] = true;
for($j = 0; $j < $n1; $j++)
{
$xarr[$hasId0[$j]]['aantal'] += $n1;
$xarrDone[$hasId0[$j]] = true;
}
}
}
}
//
return $xarr;
}
//
// duplicate elements are suppressed:
//
function checkDuplicates2Unique($xarr) {
//
$xarrDone = array();
$xarrNew = array();
//
$n = count($xarr);
//
for($i = 0; $i < $n; $i++)
{
if(! isset($xarrDone[$i]))
{
$id0 = $xarr[$i]['id'];
$hasId0 = array();
for($j = $i + 1; $j < $n; $j++)
{
if($xarr[$j]['id'] == $id0)
{
$hasId0[] = $j;
}
}
$n1 = count($hasId0);
if($n1 > 0)
{
$xarr[$i]['aantal'] += $n1;
for($j = 0; $j < $n1; $j++)
{
$xarrDone[$hasId0[$j]] = true;
}
}
$xarrNew[] = $xarr[$i];
$xarrDone[$i] = true;
}
}
//
return $xarrNew;
}
//
// main test:
//
$xarr0 = array(
array(
'id' => 6
, 'naam' => 'Aardmonnik'
, 'percentage' => '8,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel 8 Bruin'
, 'percentage' => '8,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel ppBruin'
, 'percentage' => '9,00%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => 'Achel ppBruin'
, 'percentage' => '9,00%'
, 'aantal' => 1
)
, array(
'id' => 3
, 'naam' => 'IV Saison'
, 'percentage' => '6,5%'
, 'aantal' => 1
)
, array(
'id' => 34
, 'naam' => '3 Schténg'
, 'percentage' => '6,00%'
, 'aantal' => 1
)
);
//
echo "<pre>
Original:
";
print_r($xarr0);
//
echo "</pre>";
//
$xarr = checkDuplicates($xarr0);
//
echo "<pre>
Modified:
";
print_r($xarr);
//
$xarr = checkDuplicates2Unique($xarr0);
//
echo "<pre>
Modified Unique:
";
print_r($xarr);
//
echo "</pre>";
?>
?
checkDuplicates(): keep duplicated id's.
checkDuplicates2Unique(): delete duplicated id's to get unique id's.
Try using php's array_unique function: http://php.net/manual/en/function.array-unique.php
It should work on arrays
Otherwise (if you can sort the array -> faster):
<?php
$db = array(....); // your data
function remove_duplicates (array $arr) {
usort($arr, function ($a, $b) {
return $a['id'] < $b['id'];
});
$result = array();
$last_id = null;
$last_index = -1;
for ($i=0; $i<count($arr); ++$i) {
if ($arr[$i]['id'] == $last_id) {
result[$last_index]['aantai'] += 1;
continue;
}
$last_id = $arr[$i]['id'];
$last_index = count($result);
$result[] = $arr[$i];
}
return $result;
}
?>
Only loop over the input once, then copy the element when the id is new, else add the value:
function checkDuplicates($array) {
$temp = array();
// Only loop through the input once
foreach($array as $k) {
// Use the id as array index
if (array_key_exists($k['id'], $temp) {
// Only check id and add aantal?
$temp[$k['id']['aantal'] += $k['aantal'];
} else {
// Copy the element to the output
$temp[$k['id']] = $k;
}
}
return $temp;
}
Depending on your further code, you might need to reset the array indices by sort() or something.
Edit: sorry I forgot an index to $temp - the aantal field schould be correct now.

How to count occurances of strings in given string wothout using a predefined string functions?

Here is the small snippet to count the string occurrences of string without using string functions.
<?php
$str ='1234567891222222222233333332';
$count = 0;
$ones='';
$twos='';
$threes='';
while(isset($str[$count])){
//echo $str[$count];
if($str[$count]== 1)
$ones += count($str[$count]);
if($str[$count]== 2)
$twos += count($str[$count]);
if($str[$count]== 3)
$threes += count($str[$count]);
++$count;
}
echo 'total number of 1\'s = '.$ones.'<br/>';
echo 'total number of 2\'s = '.$twos.'<br/>';
echo 'total number of 3\'s = '.$threes.'<br/>';
?>
Please can anyone shorter the code in efficient way...
You can do this. I'm not sure why you're using count(), as you can just increment it.
$count = 0;
$countSizes = array();
while(isset($str[$count++])) {
$countSizes[ $str[$count] ]++;
}
$countSizes will now have the count of each number in the string respective to its index.
You can use array_count_values and str_split if your numbers range 0-9
$result = array_count_values(str_split($str));
Output
var_dump($result);
array (size=9)
1 => int 2
2 => int 12
3 => int 8
4 => int 1
5 => int 1
6 => int 1
7 => int 1
8 => int 1
9 => int 1
for($i=1;$i<=3;$i++){
preg_match_all ( $strn , $i, $matches);
//preg_match_all stores the found values in $matches, you can count them easily...
echo 'There is '.count($matches).' "'.$i.'".';
}
sounds like homework to me:
$counters = array_fill(0,10,0);
$count = 0;
while(isset($str[$count])){
$counters[$str[$count++]]++;
}
foreach($counters as $key => $value) {
echo "Total number of {$key}s = {$value}", PHP_EOL;
}
or even using
array_count_values(str_split($str));
if str_split() is permitted
Use:
<?php
$str ='1234567891222222222233333332';
$i=0;
$char1 = $str[$i];
$isExists = array();
$found_array = array();
while(!empty($char1)) {
if(in_array($char1, $isExists)) {
$i++;
$char1 = isset($str[$i]) ? $str[$i] : '';
continue;
};
$count = 0;
$j=0;
$char2 = $str[$j];
while(!empty($char2)) {
//echo "$char1 = $char2<br>";
if($char1==$char2) $count++;
$j++;
$char2 = isset($str[$j]) ? $str[$j] : '';
}
$isExists[] = $char1;
$found_array[$char1] = $count;
$i++;
$char1 = isset($str[$i]) ? $str[$i] : '';
}
foreach($found_array as $char=>$count) {
echo "total number of $char's = $count <br/>";
}
?>

Php recursion to get all possibilities of strings

Here is my code to get all possibilities:
$seq[1] = 'd';
$seq[2] = 'f';
$seq[3] = 'w';
$seq[4] = 's';
for($i = 1; $i < 5; $i++)
{
$s['length_1'][] = $seq[$i];
$c1++;
for($i2 = $i+1; $i2 < 5; $i2++)
{
$s['length_2'][] = $seq[$i].$seq[$i2];
$last = $seq[$i].$seq[$i2];
$c2++;
for($i3 = $i2+1; $i3 < 5; $i3++)
{
$s['length_3'][] = $last.$seq[$i3];
$last = $last.$seq[$i3];
$c3++;
for($i4 = $i3+1; $i4 < 5; $i4++)
{
$s['length_4'][] = $last.$seq[$i4];
$c4++;
}
}
}
}
for($i = 0; $i < $c1; $i++)
echo $s['length_1'][$i].'<br>';
for($i = 0; $i < $c2; $i++)
echo $s['length_2'][$i].'<br>';
for($i = 0; $i < $c3; $i++)
echo $s['length_3'][$i].'<br>';
for($i = 0; $i < $c4; $i++)
echo $s['length_4'][$i].'<br>';
But if I want to add more, then I will have to add one more loop. So, how can I do it with recursion? I try, I try, but I really can't do it.
Please help and post example as simple as possible.
Thank you.
One algorithm is here,
function getCombinations($base,$n){
$baselen = count($base);
if($baselen == 0){
return;
}
if($n == 1){
$return = array();
foreach($base as $b){
$return[] = array($b);
}
return $return;
}else{
//get one level lower combinations
$oneLevelLower = getCombinations($base,$n-1);
//for every one level lower combinations add one element to them that the last element of a combination is preceeded by the element which follows it in base array if there is none, does not add
$newCombs = array();
foreach($oneLevelLower as $oll){
$lastEl = $oll[$n-2];
$found = false;
foreach($base as $key => $b){
if($b == $lastEl){
$found = true;
continue;
//last element found
}
if($found == true){
//add to combinations with last element
if($key < $baselen){
$tmp = $oll;
$newCombination = array_slice($tmp,0);
$newCombination[]=$b;
$newCombs[] = array_slice($newCombination,0);
}
}
}
}
}
return $newCombs;
}
I know it is not efficent in any way, but using in small sets should not be a problem
first base parameter is an array containing elements to be considered when generating combinations.
for simple usage and output:
var_dump(getCombinations(array("a","b","c","d"),2));
and output is
array
0 =>
array
0 => string 'a' (length=1)
1 => string 'b' (length=1)
1 =>
array
0 => string 'a' (length=1)
1 => string 'c' (length=1)
2 =>
array
0 => string 'a' (length=1)
1 => string 'd' (length=1)
3 =>
array
0 => string 'b' (length=1)
1 => string 'c' (length=1)
4 =>
array
0 => string 'b' (length=1)
1 => string 'd' (length=1)
5 =>
array
0 => string 'c' (length=1)
1 => string 'd' (length=1)
To list all subsets of an array, using this combinations algorithm just execute
$base =array("a","b","c","d");
for($i = 1; $i<=4 ;$i++){
$comb = getCombinations($base,$i);
foreach($comb as $c){
echo implode(",",$c)."<br />";
}
}
And output is
a
b
c
d
a,b
a,c
a,d
b,c
b,d
c,d
a,b,c
a,b,d
a,c,d
b,c,d
a,b,c,d
Here's a simple algo. Iterate from 1 to 2count(array)-1. On each iteration, if j-th bit in a binary representation of the loop counter is equal to 1, include j-th element in a combination.
As PHP needs to be able to calculate 2count(array) as an integer, this may never exceed PHP_INT_MAX. On a 64-bit PHP installation your array cannot have more than 62 elements, as 262 stays below PHP_INT_MAX while 263 exceeds it.
EDIT: This computes all possible combinations, not permutations (ie, 'abc' = 'cba'). It does so by representing the original array in binary and "counting up" from 0 to the binary representation of the full array, effectively building a list of every possible unique combination.
$a = array('a', 'b', 'c', 'd');
$len = count($a);
$list = array();
for($i = 1; $i < (1 << $len); $i++) {
$c = '';
for($j = 0; $j < $len; $j++)
if($i & (1 << $j))
$c .= $a[$j];
$list[] = $c;
}
print_r($list);
Here it is:
<?php
function combinations($text,$space)
{
// $text is a variable which will contain all the characters/words of which we want to make all the possible combinations
// Let's make an array which will contain all the characters
$characters=explode(",", $text);
$x=count($characters);
$comb = fact($x);
// In this loop we will be creating all the possible combinations of the positions that are there in the array $characters
for ($y=1; $y<= $comb; $y++)
{
$ken = $y-1;
$f = 1;
$a = array();
for($iaz=1; $iaz<=$x; $iaz++)
{
$a[$iaz] = $iaz;
$f = $f*$iaz;
}
for($iaz=1; $iaz<=$x-1; $iaz++)
{
$f = $f/($x+1-$iaz);
$selnum = $iaz+$ken/$f;
$temp = $a[$selnum];
for($jin=$selnum; $jin>=$iaz+1; $jin--)
{
$a[$jin] = $a[$jin-1];
}
$a[$iaz] = $temp;
$ken = $ken%$f;
}
$t=1;
// Let’s start creating a word combination: we have all the necessary positions
$newtext="";
// Here is the while loop that creates the word combination
while ($t<=$x)
{
$newtext.=$characters[$a[$t]-1]."$space";
$t++;
}
$combinations[] = $newtext ;
}
return $combinations;
}
function fact($a){
if ($a==0) return 1;
else return $fact = $a * fact($a-1);
}
$a = combinations("d,f,w,s","");
foreach ($a as $v) {
echo "$v"."\n";
}
?>
Output:
dfws
dfsw
dwfs
dwsf
dsfw
dswf
fdws
fdsw
fwds
fwsd
fsdw
fswd
wdfs
wdsf
wfds
wfsd
wsdf
wsfd
sdfw
sdwf
sfdw
sfwd
swdf
swfd
Also, read this;
You can do this:
function combinations($arr) {
$combinations = array_fill(0, count($arr)+1, array());
$combinations[0] = array('');
for ($i = 0, $n = count($arr); $i < $n; ++$i) {
for ($l = $n-$i; $l > 0; --$l) {
$combinations[$l][] = implode('', array_slice($arr, $i, $l));
}
}
return $combinations;
}
Here’s an example:
$arr = array('d', 'f', 'w', 's');
var_dump(combinations($arr));
This produces the following array:
array(
array(''), // length=0
array('d', 'f', 'w', 's'), // length=1
array('df', 'fw', 'ws'), // length=2
array('dfw', 'fws'), // length=3
array('dfws') // length=4
)
A brief explanation:
For each i with 0 ≤ i < n, get all sub-arrays arr‍[i,‍i+‍l] with each possible length of 0 < l ≤ n - i.
Here is my function to print all possible character combinations:
function printCombinations($var, $begin = 0, $preText = "") {
for($i = $begin; $i < count($var); $i++) {
echo $preText . $var[$i] . "\n";
if(($i+1) < count($var))
printCombinations($var, $i+1, $preText . $var[$i]);
}
}
printCombinations(array('a','b','c','d','e'));
here is another way to do it in codeigniter/php.
`function recursiveCombinations($var,$n = '') {
$len = count($var);
if ($n == 0){
return array(array());
}
$arr = [];
for ($i = 0;$i<$len;$i++){
$m = $var[$i];
$remLst = array_slice($var, $i + 1);
$remainlst_combo = $this->recursiveCombinations($remLst, $n-1);
foreach ($remainlst_combo as $key => $val){
array_push($arr,array_merge(array($m),$val));
}
}
return $arr;
}
$arr = ['a','b','c','d','e','f','g','h','i','j','l','m','n','o','p'];
$n = $this->recursiveCombinations($arr,5);`

Categories