Jump to content

Display which row and which column has the biggest number of 1's


Dobby

Recommended Posts

Hi,

I am new to PHP and I have this homework due Sunday, I got it on Friday btw :) I have complete the first part of it , but I can not complete the second part of it. This is the exercise:

Largest Row and Column

Write a 4x4 array and fill it with random 1's or 0's

0 0 1 1

0 1 0 0

1 0 1 1

1 0 0 1

Display which row and which column has the biggest number of 1's

this is my code: 

<?php

$num = array("0", "1");



$rows = rand(4, 4); //using rand() function to generate 4 different numbers, min & max=4

$cols = rand(4, 4);



echo "<table>";

for($i = 1; $i <= $rows; $i++)

{

    echo "<tr>";

    for($j = 1; $j <= $cols; $j++)

    {

     $td_text = $num[rand(0,(count($num)-1))]; //number spacing

        echo '<td>'.$td_text.'</td>';

    }

    echo "</tr>";

}



?>

[edit : zane] Don't hesitate to use code tags next time ;), it's the <> button.

Link to comment
Share on other sites

I assume you've had a go at it yourself by now. Here's my effort...

<?php
$data = [];
for ($r=0; $r<4; $r++) {
    for ($c=0; $c<4; $c++) {
        $data[$r][$c] = rand(0,1);
    }
}

$rowcounts = $colcounts = [];
for ($r=0; $r<4; $r++) {
    $rowcounts[$r] = count(array_keys($data[$r], 1));
}
for ($c=0; $c<4; $c++) {
    $colcounts[$c] = count(array_keys(array_column($data,$c), 1));
}

$rmax = max($rowcounts);
$cmax = max($colcounts);
$rcmax = max($rmax, $cmax);

$hirows = array_keys($rowcounts, $rcmax);
$hicols = array_keys($colcounts, $rcmax);

echo "<table border='1' style='border-collapse:collapse'>\n";
for ($r=0; $r<4; $r++) {
    echo "<tr>";
    for ($c=0; $c<4; $c++) {
        $hilite = (in_array($r, $hirows) || in_array($c, $hicols)) ? 'class="max"' : '';
        echo "<td $hilite>&nbsp;{$data[$r][$c]}&nbsp;</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";   
?>

image.png.5808b5d66225aedee66ff4163bb0e972.png

  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.