Change variable value and push it after loop - php

I have code like this
$jumlahcolspan = array();//new array
$horizontaldeep = 5;
$level = array(5,4,3,8,7);//old array
for ($j = 0; $j < $horizontaldeep; $j++) {
$jml = 1;
for ($i = $j + 1; $i < $horizontaldeep; $i++) {
$jml = $level[$i] * $jml;
}
array_push($jumlahcolspan, $jml);
}
To put it simple, what I want to get is to multiply old array value which index start from $i+1 to the last and push it to another array.
So, its some thing like this
old array: [5, 4, 3, 8, 7]
new array: [4*3*8*7, 3*8*7, 7, 1]
I've tried this but it doesn't work also
for ($j = 0; $j < $horizontaldeep; $j++) {
$jml = 1;
for ($i = $j + 1; $i < $horizontaldeep; $i++) {
global $jml;
$jml = $level[$i] * $jml;
}
array_push($jumlahcolspan, $jml);
}
Tried this too but not work also.
for ($j = 0; $j < $horizontaldeep; $j++) {
array_push($jumlahcolspan, array_product(array_slice($level, $j+1)));
}
Note: now I'm reviewing my full code. May be something not right in my code.
I think the problem is related to $jml variable but I can't figure how to solve that. Can anyone help me?

One approach would be to use a Recursive Function to achieve that goal. The Recursive Function below demonstrates how. And, by the way, you may as well quick-test it here.
<?php
$oldArray = [5,4,3,8,7];
function arrayMatrixMultiply(array $old, array &$newArray=[]){
$result = 1;
foreach($old as $key=>$value){
if($key != 0){
$result*=$value;
}
}
$newArray[] = $result;
array_splice($old, 0, 1);
if(!empty($old)){
// JUST RECURSE TILL THE $oldArray BECOMES EMPTY
arrayMatrixMultiply($old, $newArray);
}
return $newArray;
}
$newArray = arrayMatrixMultiply($oldArray);
var_dump($newArray);
// PRODUCES::
array (size=5)
0 => int 672
1 => int 168
2 => int 56
3 => int 7

Related

Create two-dimensional array by using 2 loops

I need to create two-dimensional array by using 2 loops.
Array must look like this: [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
This is what I tried, but I wanted to see better solution and to know is my solution bad.
<?php
$arr = [];
$elem = 1;
for ($i = 0; $i <= 2; $i++) {
for ($j = 1; $j <= 3; $j++) {
$arr[$i][] = $elem++;
}
}
?>
$number = range(1,9);
print_r (array_chunk($number,3));
Others have shown you some clever ways, but keeping it simple in case you are just starting out with programming.... In the inner loop, create a temporary array, then outside the inner loop but inside the outer, add it to your main array.
$arr = [];
$elem = 1;
for ($i = 0; $i <= 2; $i++) {
$t = []; #Init empty temp array
for ($j = 1; $j <= 3; $j++) {
$t[] = $elem++;
}
$arr[] = $t;
}
One of hundreds options:
$arr = [
range(1, 3),
range(4, 6),
range(7, 9),
];
print_r($arr);
one method: this method use "temp variables".
<?php
$arr_inner = [];
$arr_main = [];
$elem=1;
for ($i = 0; $i <= 2; $i++) {
for ($j = 0; $j <= 2; $j++) {
$elem =$elem +1;
$arr_inner[$j] = $elem;
}
$arr_main[$i] = $arr_inner;
unset($arr_inner);
}
?>

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
}
}
}

PHP key value pairs, where key is a dynamic variable and value is an array?

I am trying to create a 2D array where $multiples[$i] = array(multiples of $i), $i = 1,2,3...
function getMultiples($factor, $start = 0, 10)
{
$multiples = array();
for($i = $factor + $start; $i < 10; $i+=$factor)
$multiples[] = $i;
return $multiples;
}
for($i = 2; $i < 10; $i++)
{
$start = 0 ;
$multiples[$i] = getMultiples($i, $start, 10);
}
However, when I var_dump
$multiples[2] = array(0 => 2)
$multiples[3] = array(0 => 3)
$multiples[4] = array(0 => 4)
...
Each element of $values has been intialized with only the first multiple in each array.
I've tested this with non-numerical key values and it works fine. Static key values also work. The dynamic key value $i seems to the problem, what is going on here?
If you want to get the multiples of a number, you need to update the getMultiples as following:
function getMultiples($factor, $start = 0, $max)
{
$multiples = array();
for($i = 2; $i < $max; $i++)
$multiples[] = $i*$factor;
return $multiples;
}
What we change?
Loop 10 or $max time for($i = $factor + $start; $i < 10; $i+=$factor) to for($i = 2; $i < $max; $i++).
Find multiple $multiples[] = $i; to $multiples[] = $i*$factor;

How to calculate Diagonal difference in PHP?

I have a N*N Matrix.Now i want to know the diagonal difference of this Matrix.What will be the best approach of this solution?
I am trying with given approach:
Such as it is 3*3 Matrix say it is:
11 15 85
66 72 21
14 21 47
the diagonal simple formula will be:
firstD= (11+72+47) = 130
secondD = (85+72+14)= 171
diagonalDiff = |firstD - secondD| = |130-171| = 41
If I count every row such as first to find out firstD (First row's first value + Sec row's Sec value + Third row's third value+..).This is my thinking.
Can anyone tell me best approaches?
Try this:
$arr = array(
array(11, 15, 85),
array(66, 72, 21),
array(14, 21, 47),
);
$arrDiag = count($arr);
$firstD = 0;
$secondD = 0;
$i = 0;
for($j = 0; $j < $arrDiag; $j++){
$firstD += $arr[$i++][$j];
$secondD += $arr[$arrDiag - $i][$j];
}
echo abs($firstD - $secondD);//41
Model your matrix with a multi-dimensional array and iterate through it. The easiest way should be the following:
<?
$matrix = array(array(1,2,3),array(4,5,6),array(7,8,9)); //Insert or define your matrix here..
$n = count($matrix); //Size of matrix, thanks to VolkerK
$firstD = 0;
$lastD = 0;
for($i = 0; $i < $n; $i++){
$firstD += $matrix[$i][$i];
$lastD += $matrix[$i][$n-$i-1];
}
echo $firstD."\n";
echo $lastD;
Here is a pseudo code for your problem using one simple loop:
// $array - predefined 2 dimentional array with $N rows and $N columns
$result = 0;
for ($i=0;$i<$N;$i++) {
$result += ($array[$i,$i] - &array[$i,$N-$i-1]);
}
return echo abs($result);
that way you can do the calculation in one pass, and do a diff between two elements in each row insead of calculation the sum of each diagonal
Try this:
function diagonalDifference($arr) {
$left = 0;
$right = 0;
$i = 0;
foreach($arr as $ar){
$left+= $ar[0+$i];
$right+= $ar[count($ar) - (1+$i)];
$i++;
}
return abs($left - $right);
}
Try this
$result=0;
for($i=0;$i<=count($arr)-1;$i++){
$result= $result+($arr[$i][$i])-($arr[(count($arr)-1-$i)] [$i]);
}
return abs($result);
This is the code you need:
$first = 0;
$second = 0;
for($i = 0; $i < N; $i++) {
for($j = 0; $j < N; $j++) {
if($i == $j) {
$first += $matrix[$i][$j];
} else if($i + $j == N) {
$second += $matrix[$i][$j];
}
}
}
$diagonalDiff = abs($first - $second);
Where $matrix is a N*N array
Just using the function array_reduce:
function diagonalDifference($arr) {
$i = 0;
$n = count($arr);
return abs(array_reduce($arr,
function ($c, $str) use (&$i, $n ) {
$i++;
return $c + $str[$i-1] - $str[$n-$i];
}, 0));
}
demo
you can try this :
$first_diag=$second_diag=0;
$matrix=array(array(11,15,85),array(66,72,21),array(14,21,47));
foreach($matrix as $index=>$sub_array){
$first_diag +=$sub_array[$index];
$second_diag +=$sub_array[count($matrix)-1-$index];
}
print abs ($first_diag-$second_diag);
For one you can use a matrix library like Math_Matrix. But if this is the only operation you are gona need then it's best to write a generalized function for this using the same method you quoted yourself.
function diagonalDiff($n){
$firstD = 0;
$secondD = 0;
for($i=0;$i<$n;$i++){
for($j=0;$j<$n;$j++){
if($i == $j) {
$first += $matrix[$i][$j];
} else if($i + $j == $n) {
$secondD += $matrix[$i][$j];
}
}
}
return abs($firstD-$secondD);
}
Should give you the answer you need for a matrix of a given size $n. (Only square Matrixes ofcourse :) )
Another better solution and it's easy to understand:
<?php
$arr = array(
array(11, 15, 85),
array(66, 72, 21),
array(14, 21, 47),
);
$arrDiag = count($arr);
$firstD = 0;
$secondD = 0;
$i = 0;
for($j = 0; $j < $arrDiag; $j++){
$i++;
$firstD += $arr[$j][$j];
$secondD += $arr[$arrDiag - $i][$j];
}
echo abs($firstD - $secondD);
?>
DEMO
Recently solved this question in Hacker Rank.
<?php
$m=array(array(3,4,-1,11,2),
array(-3,2,1,6,9),
array(3,4,6,5,-2),
array(1,9,9,7,-3),
array(12,9,16,7,-3));
echo count($m)."<br>";
$i=0;
$j=0;
$ek=0;
$k=0;
$n=1;
$es=count($m)-1;
for($i=0;$i<count($m);$i++)
{
for($j=0;$j<count($m);$j++)
{
echo $m[$i][$j]." ";
}
echo "<br>";
}
echo "<br>";
for($k=0;$k<count($m);$k++)
{
for($n=0;$n<count($m);$n++)
{
if($k==$n){
$ek=$ek+$m[$k][$n];
}
}
echo "<br>";
}
echo "<hr>";
$p=0;
for($k=0;$k<count($m);$k++)
{
echo $m[$k][$es-$p]."<br> ";
$p++;
}
?>
Sorry I used different variable names, I had to take this to my vs code.
$b = array(
array(1,2,5),
array(3,4,5),
array(3,4,5)
);
//So for each diag
echo $b[0][0] + $b[1][1] + $b[2][2]; //to sum the first diag
echo $b[0][2] + $b[1][1] + $b[2][0]; //to sum the second diag
//notice the pattern 00, 11, 22 vs 02,11, 20. hence why I have written the function below
function difference($b){
$d1 = 0;
$d2 = 0;
$count = count($b);
for($i=0; $i<$count; $i++){
$d1 += $b[$i][$i];
$d2 += $b[$i][$count-1-$i];
}
return abs($d1 - $d2);
}
I had the same issue, the instructions was given by the site, mislead me. However, I solved it in this way,
$n = count and store the length of input array
//define variables to store first diagonals and second diagonals
$fd = 0;
$sd = 0;
//loop through the 2D array with $i increment
$j = get an array from the main array
//in each iteration
$pd += get the values from the left to the right and add;
$sd += get the values from the right to the left and add;
}
find absolute difference between the sums using built in abs function and return it;
I think this would help someone

How to find duplicate values in an array without using array_count_values

I am trying to find duplicated values/string in an array using for loop
<?php
$b=array('a','b','c','a','b');
$c=count($b);
$d=array();
for($i=0;$i<=($c-1);$i++)
{
for($j=1;$j<=($c-1);$j++)
{
if($b[$i]!=$b[$j])
{
$flag=1;
}
}
if($flag==1)
{
$d[$i]=$b[$i];
}
}
print_R($d);
?>
where is my mistake? I have used array $d to display non duplicate values.....
NOTE: I need to try this only with for loop - I know how to do it using array functions.
You should reverse your test, because there are almost always values, which are different from the one you're testing. And you must reset your $flag before the inner loop, otherwise it will always be true.
When you want to find unique values, you can just test against $d only. If the value is already in $d, skip it.
$c1 = count($b);
for ($i = 0; $i < $c1; $i++) {
$dup = 0;
$c2 = count($d);
for ($j = 0; $j < $c2; $j++) {
if ($b[$i] == $d[$j])
$dup = 1;
}
if (!$dup)
$d[] = $b[$i];
}
print_r($d);
If you want to find values, which don't have duplicates instead
for ($i = 0; $i < $c; $i++) {
$dup = 0;
for ($j = 0; $j < $c; $j++) {
if ($i != $j && $b[$i] == $b[$j])
$dup = 1;
}
if (!$dup)
$d[] = $b[$i];
}
function has_dupes($array){
$dupe = array();
foreach($array as $val){
if(++$dupe[$val] > 1)
return true;
}
return false;
}
could do something like this.. this would check for dupes, then u can print the uniques
Why are you making a simple task complex .. simply
$b = array('a','b','c','a','b');
var_dump(customCount($b));
Output
array (size=3)
'a' => int 2 //duplicate
'b' => int 2 //duplicate
'c' => int 1
Function Used
function customCount($array) {
$temp = array();
foreach ( $array as $v ) {
isset($temp[$v]) or $temp[$v] = 0;
$temp[$v] ++;
}
return $temp ;
}

Categories