Combining and Permuting items of two different arrays in PHP - php

How do I return all possible combinations [12345], [12354] up to [54312], [54321] without having to run 120 for...loop as in the case of combining a 2-item array in the code below?
To return all possible combinations from the given array $word = [1,2],
//break the array into 2 separate arrays
$arr1 = $word[0]; $arr2 = $word[1];
//computer for first array item...each item will have 2 loops
for($i=0; $i<count($arr1); $i++){
for($j=0; $j<count($arr2); $j++){
$ret = $arr1[$i] . $arr2[$j]; array_push($result, $ret);
}
}
//computer for second array item..each item will have 2 loops
for($i=0; $i<count($arr2); $i++){
for($j=0; $j<count($arr1); $j++){
$ret = $arr2[$i] . $arr1[$j]; array_push($result, $ret);
}
}
//display the result
for ($i = 0; $i < count($result); $i++){
echo result([$i];
}
The above code works well.
But for a 5-item array [1,2,3,4,5], it will require about (5 items * 24 loops) = 120 loops.

As seen, you wanted to split 2 strings into chars and obtain all combination by 2 chars: first form blank1 and second from blank2.
Instead of doing the combination manually use a regular for-loop.
$result = array();
for ($i = 0; $i < count($blank1); $i++)
{
for ($j = 0; $j < count($blank2); $j++)
{
//set combination
$aux = $blank1[$i].$blank2[$j];
array_push($result, $aux);
}
}
//result should be populated with combination of 2
//just list it and use as need
for ($i = 0; $i < count($result); $i++)
{
echo $result[$i];
}
//same with stored or checking on db : use loops
For multiple combination, use more nested loops
eg: [blank1][blank2][blank1] - 3 combination
$result = array();
//1
for ($i = 0; $i < count($blank1); $i++)
{
//2
for ($j = 0; $j < count($blank2); $j++)
{
//3
for ($k = 0; $k < count($blank1); $k++)
{
//set combination
$aux = $blank1[$i].$blank2[$j].$blank1[$k];
array_push($result, $aux);
}
}
}
Same as any number you wanted ! It will be a little annoying if have to write many loops but note while can be used with an adequate algorithm. But for the moment just keep as simple as you can and get the desired result.

Related

How to compare every value in a for loop?

I have a multidimentional array of 5 items and I want that my loop would compare it like:
1 -> 2, 1 -> 3, 1 -> 4, 1 -> 5, 2->1, 2->3, 2->4, 2->5......// so on and 5 -> 4 in the end.
The problem is that after my array $i value matches 1 and $j value matches 3, the unset is done and the $i value becomes 2 (which is correct) and $j value becomes 4 instead of 3. Could someone tell me why and what I'm doing wrong?
My loop is:
for ($i = 0; $i <= count($myArray); $i++) {
for ($j = $i+1; $j <= count($myArray); $j++) {
if (
// condition 1
&& // condition 2
) {
unset($myArray[$i]);
$i++;
}
}
}
I think that's the problem is when you unset the element in the array, you increment the counter of the loop $i. In this way, the elements of the array that are not configured are removed, this empty array position will be maintained, it will not be reordered, you will have to do it manually or using array_values ​​method.
In the last tour of the array, it will break because you are comparing the number of array elements as equal. You must use index < count($array)
The code would be like this:
for ($i = 0; $i < count($myArray); $i++) {
for ($j = $i+1; $j < count($myArray); $j++) {
if (
// condition 1
&& // condition 2
) {
unset($myArray[$i]);
// $i++;
}
}
}
try something like this
for ($i = 0; $i <= count($myArray); $i++) {
for ($j = 0; $j <= count($myArray); $j++) {
if ($j!=$i)
{
if (
// condition 1
&& // condition 2
) {
unset($myArray[$i]);
$i++;
}
}
}
}
$temp = $myArray;
for ($i = 0; $i <= count($myArray); $i++)
{
for ($j = $i + 1; $j <= count($myArray); $j++)
{
if (
// condition 1
&& // condition 2
)
{
unset($temp[$i]);
$i++;
}
}
}
print_r($temp);
Your result is in $temp. So here indexes wont get hampered, you actually are applying all operation on $temp and normally traversing $myArray.
To be honest, I do not know why nobody has yet advise to use nested foreach, since you all noticed there was a problem with array size.
foreach ($numbers as $number_horizontal_parsing) {
foreach ($numbers as $number_vertical_parsing) {
if ($number_horizontal_parsing != $number_vertical_parsing) {
//do your stuff in your case it seems you want to compare both variables
}
}
}

Optimizing generating an array of pairs from an array without duplicates in PHP

I'm generating a big array of pairs from a 1D array, the code has to check and eliminate strictly all duplicates (i.e. if [1,2] exists, then no [2,1] to be produced). For example:
arr = [1,2,3]
pairs = [[1,2],[1,3],[2,3]]
My solution currently takes 60 seconds to generate an array of size N=460 (result will be around 110,000 pairs). The code is below:
private function generateAllCombination($scripts)
{
$combinations = [];
$pairsIndex = '';
for ($i = 0; $i < count($scripts) - 1; $i++) {
for ($j = 0; $j < count($scripts); $j++) {
// pairs must consist of tuples with distinct values
if ($i != $j) {
$pair = array(
$scripts[$i],
$scripts[$j]
);
// only add unique tuples
$pairTuple = '[' . $i . ',' . $j. ']';
$pairTupleRev = '[' . $j . ',' . $i . ']';
if (strpos($pairsIndex, $pairTuple) === false) {
$combinations[] = $pair;
if ($j > $i) {
$pairsIndex .= $pairTupleRev;
}
}
else {
$pairsIndex = str_replace($pairTuple, '', $pairsIndex);
}
}
}
}
return $combinations;
}
I reckon the checking of duplicates is killing it in the 2D nested loop, but not sure how to optimize it efficiently. Any recommendation would be much appreciated.
If arr does not contain duplicates, then you just have to begin the second loop from the next index:
for ($i = 0; $i < count($scripts) - 1; $i++) {
for ($j = $i + 1; $j < count($scripts); $j++) {
//no need to check, just make a pair

Php getting all combinations for a n dimensional array

I have an array of route elements (point1, point2, ...) to provide to a map engine.
I don't know how many points I have. Each point is an array of possible addresses.
I need to perform a check for every combination possible of these points, but only one successful check is required.
My array looks like something akin to:
$point[0] = array($address1, $address2, $adress3);
$point[1] = array($address1, $address2);
$point[2] = array($address1, $address2, $adress3, $adress4);
$point[n] = ...
I want to perform a test for combination: $point[0][0] - $point[1][0] - $point[2][0], $point[0][1] - $point[1][0] - $point[2][0], and so on ! :)
The first successful test (route found) should end the function.
I'm trying to do something with recursion but have spent many hours on this without success.
If I got you right, you want to have a "cartesian product".
This is an example function for it:
It first checks, if there are any subvalues in one of the subarrays and then it creates an array with all possible arraycombinations and returns it.
<?php
function array_cartesian_product($arrays)
{
$result = array();
$arrays = array_values($arrays);
$sizeIn = sizeof($arrays);
$size = $sizeIn > 0 ? 1 : 0;
foreach ($arrays as $array)
$size = $size * sizeof($array);
for ($i = 0; $i < $size; $i ++)
{
$result[$i] = array();
for ($j = 0; $j < $sizeIn; $j ++)
array_push($result[$i], current($arrays[$j]));
for ($j = ($sizeIn -1); $j >= 0; $j --)
{
if (next($arrays[$j]))
break;
elseif (isset ($arrays[$j]))
reset($arrays[$j]);
}
}
return $result;
}
?>

how to Copy Values From 1dimensional array to 2dimensional array?

How do I copy data from 1d array to 2d array?
Suppose
there is an array namely a[10000] with values like
[ 1,2,3,55,66,77,88, ... ... , 9999]
values may be repeated ...
Now I want to convert this array which holds 10,000 values right now into 2 dimensional array
that has 100 rows and 100 columns.
After that
Is it possible to implement a SELECTION SORT on a 2 dimensional array?
for($i = 0; $i<100; $i++)
{
for($j = 0; $j<100; $j++)
{
$indice = $j + 100 * $i;
$newArray[ $i ][ $j ] = $oldArray[ $indice ];
}
}
You can try something like this:
assuming $a = array(1,2,3,4,5....1000)
$b = 0;
$c = 0;
foreach ($a as $new_number){
if ($b < 100){
$b ++;
} else {
$b = 1;
$c ++;
}
$new_array[$c][$b] = $new_number;
}
Define two loops and do some multiplication
for ($i=0; $i< 100; $i++) {
for ($j=0; $j< 100; $j++) {
$twoDarray[$i][$j] = $oneDarray[$i*100 + $j];
}
}
For sorting a multidimensional array you use array_multisort.
Here's the manual page: http://www.php.net/manual/en/function.array-multisort.php
Just more one variant:
foreach($a as $k=>$v){
$b[(int)($k/100)][$k%100] = $v;
}

php array output problem

In php is there a function to increment the
values of subsequent values twice(*2) in an array
column based on an initial value?
$beta = array(
array('5', '1''1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2'),
array('5','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2')
);
/*Example: '5' will be '10' (5*2 =10 and output 10 to web)
'2' will be '4' (2*2 = 4 and output 4 to web)
The next '2' will be '16' (4*2 = 8 and output 8 to web)
The next '2' will be '32' (8*2 = 16 and output 16 to web)
And so forth? */
Furthermore is there an easier way to construct this array, cause I firmly believe there is, but not something too complicated in terms of construct such that a noob will not understand it, again thanks.
[Disclaimer: I have spent 3 days trying to understand arrays, I now understand them; however, I am still new and am currently having some issues when trying to manipulate the values in my array and output them to the web.And I am still pretty sure I have a lot to read and learn, so please no flamers, I just need some help, found this problem in this C++ book:
[http://books.google.com/books?id=4Fn_P7tdOZgC&pg=PT424&lpg=PT424&dq=subsequent+++column+is+twice+the+value&source=bl&ots=gSvQ_LhxoI&sig=dG_Ilf1iLO86lqX936cT1PpkPc8&hl=en&ei=OEEBS_eODYyotgOFtJD3CQ&sa=X&oi=book_result&ct=result&resnum=1&ved=0CAgQ6AEwAA#v=onepage&q=subsequent%20%20%20column%20is%20twice%20the%20value&f=false][1]
You can try array_map:
<?php
function increase($n) {
return is_array($n) ? array_map('increase', $n) : $n * 2;
}
$new_beta = array_map("increase", $beta);
As for constructing the array, there are other methods to do so but I believe this is the most performent and clean.
Here is an answer for each question in that section of the book, enjoy!
<?php
// Declare an array alpha of 10 rows and 20 columns of type int
// Initialise the array alpha to 0
$alpha = array(array());
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
$alpha[$i][$j] = 0;
}
}
// Store 1 in the first row and 2 in the remaining rows
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
if($i == 0)
{
$alpha[$i][$j] = 1;
}
else
{
$alpha[$i][$j] = 2;
}
}
}
// Store 5 in the first column, and make sure that the value in
// each subsequent column is twice the value in the previous column
// (Beware this doesn't build off the initial value of 5 in the first
// column but the previously set values above)
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
if($j == 0)
{
$alpha[$i][$j] = 5;
}
else
{
if($j - 1 >= 1)
{
$alpha[$i][$j] = $alpha[$i][$j-1] * 2;
}
}
}
}
// Print the array alpha one row per line
print "Printing the array alpha one row per line:<br/>";
for($i = 0; $i < 10; $i++)
{
for($j = 0; $j < 20; $j++)
{
print "[". $alpha[$i][$j] ."] ";
}
print "<br/>";
}
print "<br/>";
// Print the array alpha one column per line
print "Printing the array alpha one column per line:<br/>";
for($j = 0; $j < 20; $j++)
{
for($i = 0; $i < 10; $i++)
{
print "[". $alpha[$i][$j] ."] ";
}
print "<br/>";
}
?>

Categories