permutation/generate combination prefix and suffix - php

I have an array of prefixes, an array of base words and an array of suffixes. I would like to see every combination that can be made.
Example:
prefixes: 1 2
words: hello test
suffixes: _x _y
Results:
1hello_x
1hello_y
1hello
1test_x
1test_y
1test
1_x
1_y
1
2hello_x
2hello_y
2hello
2test_x
2test_y
2test
2_x
2_y
2
hello_x
hello_y
hello
test_x
test_y
test
_x
_y
y
How can I do this?
Edit: Thanks for all the responses, I am going through the solutions but it seems like if there are no prefixes, then it will fail for combination. It should still go through the base words and suffixes, even without any prefixes.

function combineAll ($prefixes, $words, $suffixes)
{
$combinations = array ();
foreach ($prefixes as $prefix)
{
foreach ($words as $word)
{
foreach ($suffixes as $suffix)
{
$combinations[] = $prefix.$word.$suffix;
}
}
}
return $combinations;
}

for each $prefix in $prefixes {
for each $base in $basewords {
for each $suffix in $suffixes {
echo $prefix.$base.$suffix."\n"
}}}
This will do what you want, I believe there is no builtin function to do this in php (Though there is in python)

this should get you started:
http://ask.amoeba.co.in/php-combinations-of-array-elements/
//$a = array("1", "2");
$b = array("hello", "test");
$c = array("_x", "_y");
if(is_array($a)){
$aG = array($a,$b, $c);
}else{
$aG = array($b, $c);
}
$codes = array();
$pos = 0;
generateCodes($aG);
function generateCodes($arr) {
global $codes, $pos;
if(count($arr)) {
for($i=0; $i<count($arr[0]); $i++) {
$tmp = $arr;
$codes[$pos] = $arr[0][$i];
$tarr = array_shift($tmp);
$pos++;
generateCodes($tmp);
}
} else {
echo join("", $codes)."<br/>";
}
$pos--;
}
result:
1hello_x1hello_y1test_x1test_y2hello_x2hello_y2test_x2test_y

Related

How to recursively combine array in php

I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);

Checking a for progression in a list of variables

Let's say I want to check for simple mathematical progression. I understand I can do it like this:
if ($a<$b and $b<$c and $c<$d and $d<$e and $e<$f) { echo OK; }
Is there a way to do it in a more convenient way? Like so
if ($a..$f isprog(<)) { echo OK; }
I don 't know if I get your problem right. But propably the solution for your progression could be the SplHeap object of the SPL delivered with php.
$stack = new SplMaxHeap();
$stack->insert(1);
$stack->insert(3);
$stack->insert(2);
$stack->insert(4);
$stack->insert(5);
foreach ($stack as $value) {
echo $value . "\n";
}
// output will be: 5, 4, 3, 2, 1
I havent heard of something like this, but how about using simple function:
function checkProgress($vars){ //to make it easie i assume that vars can be given in an array
$result = true;
for ($i=0; $i<= count($vars); $i++){
if ($i>0 && $vars[$i] > $vars[$i-1]) continue;
$result = false;
}
return $result;
}
Solved it quick and dirty:
function ispositiveprogression($vars) {
$num=count($vars)-1;
while ($num) {
$result = true;
if ($vars[$num] > $vars[$num-1]) {
$num--;
}
else { $result = false; break; }
}
return $result;
}
Create an array of values, iterate over them and maintaining a flag that checks if the current element value is greater than / less than that of the next value. Unlike some of the solutions in this thread, this doesn't loop through the whole array. It stops looping when it discovers the first value that's not a progression. This will be a lot more faster if the operation involves a lot of numbers.
function checkIfProg($arr, $compare) {
$flag = true;
for ($i = 0, $c = count($arr); $i < $c; $i++) {
if ($compare == '<') {
if (isset($arr[$i + 1]) && $arr[$i] > $arr[$i + 1]) {
$flag = false;
break;
}
} elseif ($compare == '>') {
if (isset($arr[$i + 1]) && $arr[$i] < $arr[$i + 1]) {
$flag = false;
break;
}
}
}
return $flag;
}
Usage:
$a = 2;
$b = 3;
$c = 4;
$d = 5;
$e = 9;
$f = 22;
$arr = array($a, $b, $c, $d, $e, $f);
var_dump(checkIfProg($arr, '<')); // => bool(true)
If you want the array to be created dynamically, you could use some variable variable magic to achieve this:
$arr = array();
foreach (range('a','f') as $v) {
$arr[] = $$v;
}
This will create an array containing all the values of variables from $a ... $f.

php find number range of array

i have an array like this:
$d=array('good'=>10,'very good'=>20,'bad'=>1);
i want to find key from it when 13 number closest vlaue of array.
for example 16 close to 20 in $d array .
like result:
key:very good
value:20
Code
$d=array('good'=>10,'very good'=>20,'bad'=>1);
$find=13;
foreach(array_chunk($find, 5) as $val) {
echo reset($val) . "-" . end($val);
}
sorry for my english.
This is not very pretty code, but I think it does what you want it to.
$d=array('good'=>10,'very good'=>20,'bad'=>1);
$closest = array('int' => -1, 'key' => null);
$find = 16;
foreach($d as $k=>$v) {
if ($closest['int'] == -1) { $closest['int'] = abs($find-$v); $closest['key'] = $k; continue; }
if (abs($find - $v) < $closest['int']) {
$closest['int'] = abs($find-$v);
$closest['key'] = $k;
}
}
echo "key:".$closest['key']."
value:".$d[$closest['key']];
You can try
$d = array('good' => 10,'very good' => 20,'bad' => 1);
vprintf("Find:%d, Closest: %d, Grade: %s\n",findClosest($d,13));
vprintf("Find:%d, Closest: %d, Grade: %s\n",findClosest($d,16));
Output
Find:13, Closest: 10, Grade: good
Find:16, Closest: 20, Grade: very good
Function Used
function findClosest($array, $find) {
$map = array_map(function ($v) use($find) {
return abs($v - $find);
}, $array);
asort($map);
return array($find,$array[key($map)],key($map));
}
try code
$d = array('good'=>10,'very good'=>20,'bad'=>1);
$find=13;
$result = get_closest($d , $find);
echo $result;
function get_closest($array = array(), $key){
$new_arr = array();
foreach($array AS $index=>$arr){
if($key < $arr) {
$new_arr[$index] = $arr - $key;
}
else{
$new_arr[$index] = $key - $arr;
}
}
$min_val = min($new_arr);
$res = array_search( $min_val , $new_arr);
return $res;
}
thanks
you can use array_values function to get all values as $a, then you can sort $a.After sort you can find two numbers between $find, then you can compare those two numbers.

PHP Combine two strings

Is there a way in php to make two strings combine to one? I want to combine strings with the same size together?
$string1 = "apple"
$string2 = "block"
//FUNCTION STUFF HERE
$output = "abplpolcek";
You could try this:
$output='';
for($i=0;$i<strlen($string1);$i++)
{
$output.=$string1[$i];
$output.=$string2[$i];
}
echo $output;
Or you can write a simple function like this:
function funnyConcatStrings($str1, $str2)
{
$output='';
$leng=strlen($str1);
if(strlen($str1)==strlen($str2))
{
for($i=0;$i<$leng;$i++)
{
$output.=$str1[$i];
$output.=$str2[$i];
}
}
else
{
$output='Strings were not equal.\n';
}
return $output;
}
// Use it like this:
$mashedString=funnyConcatStrings($string1, $string2);
// or
echo funnyConcatStrings($string1, $string2);
$str_length = 5;
$output = '';
for($i = 0; $i < $str_length; $i++)
{
$output .= $string1[$i] . $string2[$i];
}
use for instance $string1[0] ( letter 'a' ) to access the first letter and make a for loop
Really easy;
$a = 'abcdef';
$b = 'ghijkl';
$l = strlen($a);
$s='';
for($i=0;$i<$l;$i++)$s .= $a[$i] + $b[$i];
echo $s;
1.) Check if the string have the same lengts with strlen
2.) Then you can iterate through the string and access them as an array
$string = 'test123';
echo $string[0] -> 't'
Then you can combine the string and safe them in a new variable.
This will work for strings that are different lenght as well
$string1 = "apple";
$string2 = "block";
$arr1 = str_split($string1);
$arr2 = str_split($string2);
if(count($arr1) > 0)
{
foreach($arr1 as $key => $value)
{
$_tmp[] = $value;
if(isset($arr2[$key]))
{
$_tmp[] = $arr2[$key];
}
}
}
else
{
$key = 0;
}
if($key + 1 < count($arr2))
{
for($i = $key + 1; $i < count($arr2); $i++)
{
$_tmp[] = $arr2[$key];
}
}
echo implode("", $_tmp);
echo str_shuffle("apple" . "block");
result: aekbplopcl

how to write function Max($array) which returns the maximum value contained in $array or some array nested within $array

Eg:
$array= array(array(141,151,161),2,3,array(101,202,array(303,606)));
output :606
What you need is to recursively go through your array ; which means the max function, which is not recursive, will not be "enough".
But, if you take a look at the users's notes on the manual page of max, you'll find this note from tim, who proposes this recursive function (quoting) :
function multimax( $array ) {
// use foreach to iterate over our input array.
foreach( $array as $value ) {
// check if $value is an array...
if( is_array($value) ) {
// ... $value is an array so recursively pass it into multimax() to
// determine it's highest value.
$subvalue = multimax($value);
// if the returned $subvalue is greater than our current highest value,
// set it as our $return value.
if( $subvalue > $return ) {
$return = $subvalue;
}
} elseif($value > $return) {
// ... $value is not an array so set the return variable if it's greater
// than our highest value so far.
$return = $value;
}
}
// return (what should be) the highest value from any dimension.
return $return;
}
Using it on your array :
$arr= array(array(141,151,161),2,3,array(101,202,array(303,404)));
$max = multimax($arr);
var_dump($max);
Gives :
int 404
Of course, this will require a bit more testing -- but it should at least be a start.
(Going through the users' notes on manual pages is always a good idea : if you're having a problem, chances are someone else has already had that problem ;-) )
Same idea as Pascal's solution, only shorter thanks to the Standard PHP Library
$arr= array(array(141,151,161),2,3,array(101,202,array(303,404)));
echo rmax($arr);
function rmax(array $arr) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
// initialize $max
$it->next(); $max = $it->current();
// "iterate" over all values
foreach($it as $v) {
if ( $v > $max ) {
$max = $v;
}
}
return $max;
}
http://www.java2s.com/Code/Php/Data-Structure/FindtheMaximumValueinaMultidimensionalArray.htm
function recursive_array_max($a) {
foreach ($a as $value) {
if (is_array($value)) {
$value = recursive_array_max($value);
}
if (!(isset($max))) {
$max = $value;
} else {
$max = $value > $max ? $value : $max;
}
}
return $max;
}
$dimensional = array(
7,
array(3, 5),
array(5, 4, 7, array(3, 4, 6), 6),
14,
2,
array(5, 4, 3)
);
$max = recursive_array_max($dimensional);
$arr = array(array(141,151,161), 2, 3, array(101, 202, array(303,404)));
$callback = function ($value, $key) use (&$maximo) {
if( $value > $maximo){
$maximo = $value;
}
};
array_walk_recursive($arr, $callback);
echo '<pre>'; print_r($maximo);``
A more elegant solution:
function MaxArray($arr)
{
function findMax($currentValue, $currentKey)
{
global $maxValue;
$maxValue = ($currentValue > $maxValue ? $currentValue : $maxValue);
}
array_walk_recursive($arr, 'findMax');
return $GLOBALS['maxValue'];
}
It's very simple
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$max = max(iterator_to_array($iterator, false));
Finding the max avoiding too much recursion :
function array_max(array $array) {
$context = func_get_args();
$max = -INF;
while (!empty($context)) {
$array = array_pop($context);
while (!empty($array)) {
$value = array_pop($array);
if (is_array($value)) {
array_push($context, $value);
}
elseif ($max < $value) {
$max = $value;
}
}
}
return $max;
}
A more general method avoiding too much recursion :
function array_reduce_recursive($default, array $array, $callback = null) {
$context = func_get_args();
$count = func_num_args();
if (is_callable(func_get_arg($count - 1))) {
$callback = array_pop($context);
}
else {
$callback = create_function('$x, $y', 'return $x < $y ? $y : $x;');
}
$reduced = array_shift($context);
while (!empty($context)) {
$array = array_pop($context);
while (!empty($array)) {
$value = array_pop($array);
if (is_array($value)) {
array_push($context, $value);
}
else {
$reduced = $callback($reduced, $value);
}
}
}
return $reduced;
}
function array_max_recursive() {
$args = func_get_args();
$callback = create_function('$x, $y', 'return $x < $y ? $y : $x;');
return array_reduce_recursive(-INF, $args, $callback);
}
By this way you can specify the callback method if you are looking for something else than the biggest number. Also this method takes several arrays.
The end way is less efficient of course.
With this you have a full compatibility with lot of PHP version.
function MaxArray($arr) {
$maximum = 0;
foreach ($arr as $value) {
if (is_array($value)) {
//print_r($value);
$tmaximum = MaxArray($value);
if($tmaximum > $maximum){
$maximum = $tmaximum;
}
}
else
{
//echo $value.'\n';
if($value > $maximum){
$maximum = $value;
}
}
}
return $maximum;
}

Categories