Php multiplication table for specified number - php

I have a task to create a script which will output multiplication table just for specified number. To create regular multiplication table, for example 10x10 we would write something like this:
echo "<table border=\"1\">";
for ($r =0; $r < $rows; $r++){
echo'<tr>';
for ($c = 0; $c < $cols; $c++)
echo '<td>' .$c*$r.'</td>';
echo '</tr>'; // close tr tag here
}
echo"</table>";
But output which i am supposed to receive, for example for digit "3", should look like this:
|1 x 1 = 1|1 x 2 = 2|1 x 3 = 3|
| ------- | ------- | ------- |
|2 x 1 = 2|2 x 2 = 4|2 x 3 = 6|
|3 x 1 = 3|3 x 2 = 6|3 x 3 = 9|
Anyone got an idea how to echo this using php (while and/or for) loops?

It sounds like you want to output the text of the calculation as well as the result, e.g. 1 x 3 = 3. You're missing that from your output.
Also, you need to start your for loops at 1 rather than 0, otherwise you get 0 x 0 = 0 which I assume you don't want. You would compensate for the loss of iterations by using <= instead of < in your condition of the for loop so you still get 3 iterations (in this example).
Try this:
echo '<table border="1">';
for ($r = 1; $r <= $rows; $r++) {
echo '<tr>';
for ($c = 1; $c <= $cols; $c++) {
echo sprintf('<td>%d x %d = %d</td>', $r, $c, $c * $r);
}
echo '</tr>'; // close tr tag here
}
echo '</table>';
Your expected output also seems to suggest that the first row should be a heading. It would seem odd to me to do that, but if that is the case, you'll need to do this instead:
$cellType = ($r === 1) ? 'th' : 'td'; // use <th> for the first row, otherwise <td>
echo sprintf('<%s>%d x %d = %d</%s>', $cellType, $r, $c, $c * $r, $cellType);

Related

Possible combinations of binary

The problem statement is as following:
A particular kind of coding which we will refer to as "MysteryCode" is a binary system of encoding in which two successive values, differ at exactly one bit, i.e. the Hamming Distance between successive entities is 1. This kind of encoding is popularly used in Digital Communication systems for the purpose of error correction.
LetMysteryCodes(N)represent the MysteryCode list for N-bits.
MysteryCodes(1) = 0, 1 (list for 1-bitcodes,in this order)
MysteryCodes(2) = 00, 01, 11, 10 (list for 2-bitcodes,in this order)
MysteryCodes(3) =000, 001, 011, 010,110, 111, 101, 100 (list for 3-bitcodes,in this order)
There is a technique by which the list of (N+1) bitcodescan be generated from (N)-bitcodes.
Take the list of N bitcodesin the given order and call itList-N
Reverse the above list (List-N), and name the new reflected list: Reflected-List-N
Prefix each member of the original list (List-N) with 0 and call this new list 'A'
Prefix each member of the new list (Reflected-List-N) with 1 and call this new list 'B'
The list ofcodeswith N+1 bits is the concatenation of Lists A and B.
A Demonstration of the above steps: Generating the list of 3-bitMysteryCodesfrom 2-BitMysteryCodes
2-bit list ofcodes:00, 01, 11, 10
Reverse/Reflect the above list:10, 11, 01, 00
Prefix Old Entries with 0:000, 001, 011, 010
Prefix Reflected List with 1:110, 111, 101, 100
Concatenate the lists obtained in the last two steps:000, 001, 011, 010, 110, 111, 101, 100
Your Task
Your task is to display the last N "MysteryCodes" from the list of MysteryCodes for N-bits. If possible, try to identify a way in which this list can be generated in a more efficient way, than iterating through all the generation steps mentioned above.
More efficient or optimized solutions will receive higher credit.
Input Format
A single integer N.
Output Format
N lines, each of them with a binary number of N-bits. These are the last N elements in the list ofMysteryCodesfor N-bits.
Input Constraints 1 = N = 65
Sample Input 1
1
Sample Output 1
1
Explanation for Sample 1
Since N = 1, this is the (one) last element in the list ofMysteryCodesof 1-bit length.
Sample Input 2
2
Sample Output 2
11
10
Explanation for Sample 2 Since N = 2, these are the two last elements in the list ofMysteryCodesof 2-bit length.
Sample Input 3
3
Sample Output 3
111
101
100
$listN = 25;
$bits = array('0','1');
//check if input is valid or not
if(!is_int($listN))
{
echo "Input must be numeric!";
}
if($listN >= 1 && $listN <=65){
if($listN == 1){
echo '1'; exit;
}
ini_set('memory_limit', -1);
for($i=1; $i<=($listN - 1); $i++){
$reverseBits = array_reverse($bits);
$prefixBit = preg_filter('/^/', '0', $bits);
$prefixReverseBits = preg_filter('/^/', '1', $reverseBits);
$bits = array_merge($prefixBit, $prefixReverseBits);
unset($prefixBit, $prefixReverseBits, $reverseBits);
}
$finalBits = array_slice($bits, -$listN);
foreach($finalBits as $k=>$v){
echo $v."\n";
}
}
else{
echo "Invalid input!";
}
I have tried above solution, but didnt worked for input greater than 20.
for eg. If the input is 21, I got "Couldnt allocate memory" error.
It will be great if somebody figure out the optimized solutions...
The numbers follow a pattern which I transformed to below code.
Say given number is N
then create a N x N matrix and fill it's first column with 1's
and all other cells with 0's
Start from rightmost column uptil 2nd column.
For any column X start from bottom-most row and fill values like below:
Fill 2^(N - X + 1)/2 rows with 0's.
Fill 2^(N - X + 1) rows with 1's and then 0's alternatively.
Repeat step 2 till we reach topmost row.
Print the N x N matrix by joining the values in each row.
<?php
$listN = 3;
$output = [];
for ($i = 0; $i < $listN; $i++) {
$output[$i] = [];
for ($j = 0; $j < $listN; $j++) {
$output[$i][$j] = 0;
}
}
$output[$listN - 1][0] = 1;
for ($column = 1; $column < $listN; $column++) {
$zeroFlag = false;
for ($row = $listN - 1; $row >= 0;) {
$oneZero = 1;
if (!$zeroFlag) {
for ($k = 1; $k <= pow(2, $column) / 2 && $row >= 0; $k++) {
$output[$row][$listN - $column] = 0;
$row--;
$zeroFlag = true;
}
}
for ($k = 1; $k <= pow(2, $column) && $row >= 0; $k++) {
$output[$row][$listN - $column] = $oneZero;
$row--;
}
$oneZero = 0;
for ($k = 1; $k <= pow(2, $column) && $row >= 0; $k++) {
$output[$row][$listN - $column] = $oneZero;
$row--;
}
}
}
for ($i = 0; $i < $listN; $i++) {
$output[$i][0] = 1;
}
for ($i = 0; $i < $listN; $i++) {
print(join('', $output[$i]));
print("\n");
}

php display array data in multiple columns by using ceil function

For example, I have a array with 8 data. I want to display in this format
$a = array(1,2,3,4,5,6,7,8);
======
1 2
3 4
5 6
7 8
=====
OR array with 11 data
$a = array(1,2,3,4,5,6,7,8,9,10,11);
=========
1 2 3
4 5 6
7 8 9
10 11
=========
Not sure which part i got wrong. Here is my code
$a = array(1,2,3,4,5,6,7,8);
$c = ceil(count($a)/2);
echo "<table>";
for($i=0; $i<$c;$i++){
echo "<tr>";
echo '<td>'.$a[$i].'</td>';
echo '<td>'.$a[$i+1].'</td>';
}
echo "</table>";
However, my data display in this way instead
======
1 2
2 3
3 4
4 5
=====
Basically, I want to display my data from mysql in this format. But before that, I need to test out the ceil function and see if its working. Anyone knows whats wrong with my coding?
Since you have 2 cels per row you need to calculate the actual index. Also don't forget to close the <tr>
for($i=0; $i<$c;$i++){
echo "<tr>";
echo '<td>'.$a[$i * 2].'</td>';
echo '<td>'.$a[$i * 2 + 1].'</td>';
echo '</tr>';
}
Here is a full example of a cleaner solution:
<?php
$a = array(1,2,3,4,5,6,7,8);
$cols = 2;
$c = ceil(count($a) / $cols);
echo "<table>";
for($i = 0; $i < $c; $i++){
echo "<tr>";
for ($col = 0; $col < $cols; $col++) {
$value = isset($a[$i * $cols + $col]) ? $a[$i * $cols + $col] : '';
echo '<td>'. $value .'</td>';
}
echo "</tr>";
}
echo "</table>";
If you increase it manually you have to skip 1 loop every time.
$a = array(1,2,3,4,5,6,7,8,9,10,11);
$size = sizeof($a);
/* Your magic method to determine the total table cols.
*/
$cols = 3;
#$cols = 2;
echo "<table>";
for($i = 0; $i < $size; $i+=$cols){
echo "<tr>";
for($c = 0; $c < $cols; $c++){
if($i+$c >= $size){
break;
}
echo '<td>'.$a[$i+$c].'</td>';
}
echo "</tr>";
}
echo "</table>";
I've used the method of math to determine if it should print or not because it is faster. However, if you have empty indexes in the array you might want to use the isset() method as the whole code in the inner for loop.
if(isset($a[$i+$c])){
echo '<td>'.$a[$i+$c].'</td>';
}

While loop ommitting every fourth result

I'm try to dynamically generate an HTML table containing data from a database. The output looks perfect, but upon closer inspection I realized it was omitting every fourth result. I know it has something to do with the structure of my while loop and the if/else statement within, but I'm not sure what it is exactly.
$i=0;
while ($person = $pull_person->fetch()){
if ($i <= 2){
echo "<td valign='top'>";
echo "<h3>" . $person['person_name'] . " - " . $person['person_id'] . "</h3>";
echo "<label style='background-image:url(" . $person['person_pic'] . ");'><input type='checkbox' name='person[]' value='" . $person['person_id'] . "''></label>";
echo "</td>";
$i++;
}
else{
echo "</tr>";
echo "<tr>";
$i=0;
}
}
It's gotta be something simple/obvious, but it's not registering with me. Thanks!
The loop is not hitting the fourth result because of the loop limiting logic.
$i=0;
while ($person = $pull_person->fetch()){
if ($i <= 2){
echo "<p>item: $i</p>";
$i++;
}
}
Iteration 1: $i = 0
Iteration 2: $i = 1
Iteration 3: $i = 2
Iteration 4: $i = 3
Iteration 4 is never hit because it checks and sees that $i must be less than or equal to 2. If you change this to be less than or equal to 3 it will work as you want.
if ($i <= 3)
Evidently... you only increment the variable $i when the condition is met:
$i=0;
while ($person = $pull_person->fetch())
{
if ($i <= 2)
{
//output
$i++;
}
else
{
//no output
$i=0;
}
}
So this happens:
iteration old $i new $i output
1 0 1 yes
2 1 2 yes
3 2 3 yes
4 3 0 no //condition not met
5 0 1 yes //loops...
...
What you observe here is that the code will skip the output of the iteration given by the number in the conditional plust 2. So, for example, if you use the condtion $i <= 3, the results are:
iteration old $i new $i output
1 0 1 yes
2 1 2 yes
3 2 3 yes
4 3 4 yes
5 4 0 no //condition not met
6 0 1 yes //loops...
...
If you want to insert something each n iterations, do as follows:
$n = 3; //number of items per row
$i = 0;
while ($person = $pull_person->fetch())
{
//output item
$i++;
if ($i == $n)
{
//something each $n iterations
$i=0;
}
}
The effect is the following (assuming $n = 3):
iteration old $i new $i new row
1 0 1 no
2 1 2 no
3 2 0 yes //condition is met, $i reset to 0
4 0 1 no
5 1 2 no
6 2 0 yes //condition is met, $i reset to 0
...
Note 1: every iteration outputs an item.
Note 2: you can adjust the initial value of i to have an offset.
Misread question but will leave the answer as it may provide use anyway.
Best way is to look at the array as a 'module' (mathematically) -- i.e. use Modular Arithmetic:
if ((i % 4) == 0)
That is to say, indices 0, 4, 8, 12, 16, ... will be targeted, only. And, actually, this is how most setInterval functions work under the hood.

How to display each number of a variable?

basically what I want is display a count until it reaches a certain number, so if I had the number "5" on the screen it would show "1 2 3 4 5". Or if I had the number "3" it would show "1 2 3".
The reason is because im creating a paging system for my MySQL results. The code I have so far is
$result1 = mysql_query("SELECT * FROM questions WHERE subcat = '$conditions'");
$num_rows = mysql_num_rows($result1);
$results_per_page = "3";
$num_pages = $num_rows / $results_per_page;
So it counts how many results there are, for example we will say 12 results. It then devides this number by how many results I want shown per page. In this example its "3". So the answer is "4".
So I now want to have "1 2 3 4" displayed on the screen, however I want each number to be a link.
How do I do this?
Thanks
Ben
foreach( range( 1, $num_pages) as $i) {
echo '' . $i . '';
}
Or, an approach suggested by knittl:
echo implode( ' | ', array_map( function( $i) {
return sprintf( '%d', $i, $i);
}, range( 1, $num_pages)));
Prints something like this:
1 | 2 | 3 | 4 | 5
Use a for loop.
for($i = 1; $i <= $num_pages; $i++){
echo ''.$i.' ';
}
Use a loop:
for($i = 0; $i < $num_pages; ++$i) {
printf('page %d', $i, $i);
}

PHP echo in rows of three?

I am attempting to show data in rows of three like this (notice the number of items will not always be even):
abcd defg hijk
lmno pqrs tuvw
xyz1 2345 6789
1011 1213
I am struggling to get the logic right to do this (this is in a foreach() loop).
I know I have to have some if($i %3 == 0) logic in there.. But I'm a bit stuck.
Can anyone help me out?
$a = array('abcd','defg','hijk','lmno');
for ($i = 0; $i < count($a); $i++) {
if ($i && $i % 3 == 0)
echo '<br />';
echo $a[$i].' ';
}
It's better to use a for loop as:
// run $i for each index in the array.
for($i=0 ; $i<count($arr) ; $i++) {
// if $i is non-zero and is divisible by 3 print a line break.
if ($i && $i % 3 == 0) {
echo "<br />";
}
// print the element at index $i.
echo $arr[$i].' ';
}
Code in action
Pseudo-code since I don't know PHP (and you asked for the logic which tends to be the same across all procedural languages):
perline = 3
i = 0
foreach item in list:
if i > 0 and (i % perline) == 0:
print newline
if (i % perline) != 0:
print space
print item
i = i + 1
This will both output a line separator before elements 3, 6, 9 and so on (first element being 0) and place whatever desired spacing you want before the second and third elements on each line. You can just use a different value for perline to change the number output on each line.

Categories