Calculate sum of Primary and Secondary Diagonal in square matrix - php

I am currently calculating diagonal for n x n square matrix. I can able to calculate Primary diagonal with below code.
function calculateDiagonal($array) {
$length = count($array);
$primary = 0;
$secondary = 0;
for ($i = 0; $i < $length; $i++):
for ($j = 0; $j < $length; $j++):
if ($i == $j):
$primary += $array[$i][$j];
endif;
endfor;
endfor;
$totalSum = $primary + $secondary;
return $totalSum;
}
Can anyone help me to calculate sum of secondary diagonal.
check this as a reference.

Please try with this. You can do sum of diagonal with minimum iteration.
$a = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];
$n = 4;//nxn matrix
$d = $s = 0; //initialize both diagonal sum to 0
for ($i = 0; $i < $n; $i++) {
$d += $a[$i][$i];
$s += $a[$i][$n - $i - 1];
}
var_dump($d);//primary diagonal total
var_dump($s);//secondary diagonal total

Try this
function calculate2Diagonal($array) {
$length = count($array)-1;
$primary = 0;
$secondary = 0;
echo $length;
for ($i = $length; $i >= 0; $i--):
for ($j = $length; $j >=0; $j--):
if ($i == $j):
$primary += $array[$i][$j];
endif;
endfor;
endfor;
$totalSum = $primary + $secondary;
return $totalSum;
}
Only a for inverse ;)

Just using the function array_reduce:
function diagonalSum($arr) {
$i = 0;
$n = count($arr);
return array_reduce($arr,
function ($c, $str) use (&$i, $n ) {
$i++;
return $c + $str[$i-1] + $str[$n-$i];
}, 0);
}
demo

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);
}
?>

PHP sliding window - how many occurrences for sum => X

I use this code
function maxSum($arr, $n, $k)
{
$show=[];
$max_sum = PHP_INT_MIN ;
for ( $i = 0; $i < $n - $k + 1; $i++)
{
$current_sum = 0;
for ( $j = 0; $j < $k; $j++)
$current_sum = $current_sum +
$arr[$i + $j];
$max_sum = max($current_sum, $max_sum );
array_push($show,$max_sum);
}
return $show;
}
$arr = array(1, 4, 2, 10, 2, 3, 1, 0, 2);
$k = 3;
$n = count($arr);
print_r(maxSum($arr, $n, $k));
It works fine to find sums of 3 array items. Now I would like to do the opposite - to find how many array items should I sum to get 10 or close to 10.
Help is appreciated.

PHP Find a pair of elements from an array whose sum equals a given number

I have an array with n numbers from -10 to 10 (without 0). Implement function which returns quantity of pairs from the array which sum gives 0.
For example:
$input = array (3, 6, -3, 5, -10, 3, 10, 1, 7, -1, -9, -8, 7, 7, -7, -2, -7);
The right answer is 5 (pairs are bolded)
I made something like this but it gives me 10 pairs:
$length = count($input) - 1;
$count = 0;
for ($i = 0; $i <= $length; $i++) {
for ($j = $i + 1; $j <= $length; $j++) {
if ($input[$i] + $input[$j] == 0) {
$count++;
}
}
}
echo $count;
<?php
$input = array (3, 6, -3, 5, -10, 3, 10, 1, 7, -1, -9, -8, 7, 7, -7, -2, -7);
$length = count($input) - 1;
$count = 0;
for ($i = 0; $i <= $length; $i++){
$flag[$i]=0;
}
for ($i = 0; $i <= $length; $i++) {
for ($j = $i + 1; $j <= $length; $j++) {
if ($input[$i] + $input[$j] == 0 && $flag[$i]==0 && $flag[$j]==0) {
$count++;
$flag[$i]=1;
$flag[$j]=1;
}
}
}
echo $count;
?>
The correct code is given above. Since you have to mark the elements which are already used in making pair. For example, you have two +3 and one -3, which makes 2 pairs since you didn't mark it, that it has already made a pair with existing one.
You did two for loops, so you are counting the pairs twice. You can do some test, every input array you insert in the function will return an even number. Then do $count = $count/2; at final.
You need to define why its not working - it is but its finding 7 + -7 6 times: So you need to flag that this match has been found like the below code - with some added output so you can see what is happening:
$input = array (3, 6, -3, 5, -10, 3, 10, 1, 7, -1, -9, -8, 7, 7, -7, -2, -7);
$length = count($input) - 1;
$count = 0;
$matched = array();
for ($i = 0; $i < count($input); $i++) {
echo "<br />Group ".$i.": <strong>".$input[$i]."</strong>, ";
$groupmatch = 0;
$matchon = "";
for ($j = $i + 1; $j < count($input); $j++) {
echo $input[$j].", ";
$check = $input[$i] ."+". $input[$j];
if ($input[$i] + $input[$j] == 0 && !array_search($check,$matched)) {
$count++;
$groupmatch++;
$matchon .= $check.", ";
array_push($matched, $check);
}
}
echo "<br />Groupmatch: ".$groupmatch."<br/>";
echo $matchon."<br />";
}
echo $count;

sort numbers in php,

hi i am using php to learn algorithms, i wanted to convert this psuedocode into php,
for i = 1 to n − 1
minval = A[i]
minindex = i
for j = i to n
if (A[j] < minval)
minval = A[j]
minindex = j
exchange A[i] and A[minindex]
this the corresponding code in php
$A = array(1, 4, 2, 3, 70, 10, 7 );
$n = sizeof($A);
for ($i = 0; $i == $n - 1; $i++){
for ($j = $i + 1; $j == $n; $j++){
if ($A[$i] > $A[$j]){
$temp = $A[$j];
$A[$j] = $A[$i];
$A[$i] = $temp;
}
}
}
print_r($A);
print_r is outputting the array as its original order, why my algorithms doents reorder the array ?
You should check your forloops :
for ($i = 0; $i == $n - 1; $i++){
for ($j = $i + 1; $j == $n; $j++){
should be
for ($i = 0; $i < $n - 1; $i++){
for ($j = $i + 1; $j < $n; $j++){
As the second argument in for is a requirement to continue the loop.

push array into an array in php

I have this snippet where I am trying to generate array of array of array of random numbers.
function generateRandomNumbers($pACount, $pBCount, $pCCount, $pDCount) {
$points = array();
$score = array();
$res = array();
$val = array();
for ($i = 0; $i <= $pACount; $i++) {
for ($j = 0; $j <= $pBCount; $i++) {
for ($k = 0; $k <= $pCCount; $i++) {
for ($l = 0; $l <= $pDCount; $i++) {
$points[] = rand(5, 95);
}
$score[] = $points;
}
$res[] = $score;
}
$val[] = $res;
}
return $val;
}
When I return this to AJAX it is returned as: [[[[5, 32, 73, 62, 45]]]]
which was suppose to be
[[[[5, 32, 73, 62, 45], [15, 2, 7, 6, 50]],[[25, 52, 93, 2, 5], [16, 32, 67, 63, 15]]]]
I am reletively very new to php coding(started a week back) and I have no clue here.
What am I missing?
You are using $i++ in every for loop, while it was supposed to be $j++, $k++ and $l++.
The corrected code
function generateRandomNumbers($pACount, $pBCount, $pCCount, $pDCount) {
$points = array();
$score = array();
$res = array();
$val = array();
for ($i = 0; $i <= $pACount; $i++) {
for ($j = 0; $j <= $pBCount; $j++) {
for ($k = 0; $k <= $pCCount; $k++) {
for ($l = 0; $l <= $pDCount; $l++) {
$points[] = rand(5, 95);
}
$score[] = $points;
}
$res[] = $score;
}
$val[] = $res;
}
return $val;
}

Categories