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

## 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.

##### Share on other sites

Well, you've output a table of 0s and 1s, but what are you going to count?

Store the random 0/1s in a two-dimensional  array  then count the array contents.

Output the array into the table.

##### 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";
?>``` • 1
##### Share on other sites

Barand thank you for your help . Your comment really helped me! ##### Share on other sites

This thread is more than a year old.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account. ×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

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

×
×

• #### Activity

• Chat
×
• Create New...