I have a grid with 42 nrs where I will use the rand() function to pick out numbers from the grid and and mark them
so far I came up with
<?php
$row="";
print ("<table border=\"1\">");
for ($i=0; $i<6; $i++)
{
print ("<tr>");
for ($j=0; $j<7; $j++)
{
$random = rand(1,42);
$row += "(string)$random";
$som = $som + 1;
print("<th>".$som);
}
("</tr>");
}
print ("</table>");
print ("$rij");
// here I'm just testing to see if I can get a list of random numbers
for ($i=0; $i<6; $i++){
$randomNr = rand(1,42);
echo "$randomNr<br/>";
}
?>
I guess the idea is to match the numbers out of the rand function to the indexes of the table. But i'm really stuck here at getting the table to convert to an arra so I can match the index with the random numbers.
You're probably not too far off with your own attempt. You would just need to generate 6 random unique numbers and compare against them. Easiest way to do that is to generate an array using range() and pick the random numbers with array_rand() (which actually returns indexes, so you need a bit of additional code to get the values). Then you just need to find whether the currently outputted number is in the chosen number array using in_array()
Here's an example function of the general case that expands Sondre's example a bit. The function in the example takes following arguments: Total random numbers picked, Smallest number in the grid, Biggest number in the grid and the numbers per row in the grid. The function returns the generated HTML table source a string.
<?php
function generateHighlightedLotteryTable ($count = 6, $min = 1, $max = 42, $perRow = 7)
{
// Generate the picked numbers (actually we just get their indexes)
$nums = array_rand(range($min, $max), $count);
$output = "<table>\n";
for ($n = $min; $n <= $max; $n++)
{
// get "index" of the number, i.e. $min is the first number and thus 0
$i = $n - $min;
if ($i % $perRow == 0)
{
$output .= "<tr>";
}
// If the current number is picked
if (in_array($i, $nums))
{
$output .= "<td><strong>$n</strong></td>";
}
// If the current number hasn't been chosen
else
{
$output .= "<td>$n</td>";
}
if ($i % $perRow == $perRow - 1)
{
$output .= "</tr>\n";
}
}
// End row, if the numbers don't divide evenly among rows
if (($n - $min) % $perRow != 0)
{
$output .= "</tr>\n";
}
$output .= "</table>";
return $output;
}
echo generateHighlightedLotteryTable();
?>
I hope this is what you were trying to achieve.
This would create a grid of 42 numbers and mark out a random one. If you want to mark out more create and array and check against that insted of just the rand variable. In you're original code there you were actually running the rand-function 42 times which I guess is unintended.
EDIT: Or did you need the grid to be filled with random numbers?
$rand = rand(1, 42);
echo "<table>";
for($i = 1;$i <= 42; $i++) {
if($i%7 == 1) {
echo "<tr>";
}
$print = $rand == $i ? "<strong>" . $i . "</strong>" : $i;
echo "<td>" . $print . "</td>";
if($i%7 == 0) {
echo "</tr>";
}
}
echo "</table>";
Related
Im trying to make a random number counter game that uses a for loop to print out 6 random numbers 1 - 6. I want to make it so the code can say how many times the number 6 shows in the loop.
At the moment I have the code it prints out for a loop of 6 random numbers but it only counts the numbers printed out.
For example
Welcome to the Dice Game!
How many sixes will you roll?
4 2 4 6 4 6
You rolled 2 six(es)!
<?php
echo"<h1>Welcome to the guess game thing guess how many 6s!</h1>";
$counter = 0;
for ($i=0; $i <=6;$i++) {
$randomNum = rand(1,6);
if ($randomNum <= 6) {
echo "<br> $randomNum";
$counter++;
}
else
{
echo"$randomNum <br>";
}
}
echo"<br>You rolled $counter sixes";
Some minor changes but you were almost there. Being consistent with your line breaks and verifying you check specifically for 6
$numberToMatch = 6;
for ($i = 0; $i <= 6; $i++) {
$randomNum = rand(1,6);
if ($randomNum == $numberToMatch) {
$counter++;
}
echo "$randomNum <br>";
}
You can do it like this:
$num = $_POST["num"];
for ($i=0; $i <=100;$i++) {
$randomNum = rand(1,10);
if ($randomNum == $num) {
echo $randomNum;
break;
}
echo $randomNum;
}
echo"<h2> there are $i</h2>";
I'm stuck trying to use nested loops to make a reflective pattern from numbers.
I've already tried, but the output looks like this:
|0|1|2|
|0|1|2|
|0|1|2|
This is my code:
<?php
echo "<table border =\"1\" style='border-collapse: collapse'>";
for ($row=1; $row <= 3; $row++) {
echo "<tr> \n";
for ($col=1; $col <= 3; $col++) {
$p = $col-1;
echo "<td>$p</td> \n";
}
echo "</tr>";
}
echo "</table>";
?>
I expected this result:
|0|1|0|
|1|2|1|
|0|1|0|
Each columns' and rows' cell values must increment to a given amount then decrement to form a mirror / palindromic sequence.
First declare the square root of the of the table cell count. In other words, if you want a 5-by-5 celled table (25 cells), declare $size = 5
Since your numbers are starting from zero, the highest integer displayed should be $size - 1 -- I'll call that $max.
I support your nested loop design and variables are appropriately named $row and $col.
Inside of those loops, you merely need to make the distinction between your "counters" as being higher or lower than half of the $max value. If it is higher than $max / 2, you subtract the "counter" (e.g. $row or $col) from $max.
By summing the two potentially adjusted "counters" and printing them within your inner loop, you generate the desired pattern (or at least the pattern I think you desire). This solution will work for $size values from 0 and higher -- have a play with my demo link.
Code: (Demo)
$size = 5;
$max = $size - 1;
echo "<table>\n";
for ($row = 0; $row < $size; ++$row) {
echo "\t<tr>";
for ($col = 0; $col < $size; ++$col) {
echo "<td>" . (($row >= $max / 2 ? $max - $row : $row) + ($col >= $max / 2 ? $max - $col : $col)) . "</td>";
}
echo "</tr>\n";
}
echo "</table>";
Output:
<table>
<tr><td>0</td><td>1</td><td>2</td><td>1</td><td>0</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>2</td><td>1</td></tr>
<tr><td>2</td><td>3</td><td>4</td><td>3</td><td>2</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>2</td><td>1</td></tr>
<tr><td>0</td><td>1</td><td>2</td><td>1</td><td>0</td></tr>
</table>
There are a lot of ways to achive that.
An easy way to do that is;
<?php
$baseNumber = 0;
echo "<table border='1' style='border-collapse: collapse'>";
for ($row = 0; $row < 3; $row++) {
echo "<tr>";
if ($row % 2 !== 0) {
$baseNumber++;
} else {
$baseNumber = 0;
}
for ($col = 0; $col < 3; $col++) {
echo "<td>" . ($col % 2 === 0 ? $baseNumber : $baseNumber + 1) . "</td>";
}
echo "</tr>";
}
echo "</table>";
this code will do what you want just call the patternGenerator function with the number of distinct numbers you want for your example these numbers are 3 (0,1,2).
the idea in this code is to use two for loops one that starts from the minimum number to the maximum one and the other one that starts after the maximum number decreasing to the minimum.
for example:
if min = 0 and max = 5
the first loop will print 0,1,2,3,4,5
and the second will print 4,3,2,1,0
and that's it.
at first, I created a function that creates just on row called rowGenerator it takes $min and $max as parameters and prints one row
so if we want to print a row like this: |0|1|0| then we will call this function with min = 0 and max = 1 and
if we want to print a row like this: |1|2|1| then we will call it with min = 1 and max = 2.
function rowGenerator($min, $max)
{
echo '<tr>';
for($i = $min; $i<=$max;$i++)
echo '<td>'.$i.'</td>';
for($i = $max-1; $i>=$min;$i--)
echo '<td>'.$i.'</td>';
echo '</tr>';
}
for now, we can print each row independently. now we want to print whole the table if we look at the calls we do for the rowGenerator function it will looks as follow:
(min = 0, max = 1),
(min = 1, max = 2) and
(min = 0, max = 1).
minimums are (0,1,0).
yes, it's the same pattern again. then we need two loops again one to start from 0 and increase the number until reach 1 and the other one to loop from 0 to 0.
and that's what happened in the patternGenerator function. when you call it with the number of distinct numbers the function just get the min that will always be 0 in your case and the max.
function patternGenerator($numberOfDistinct )
{
echo "<table border =\"1\" style='border-collapse: collapse'>";
$min = 0;
$max = $numberOfDistinct - 2;
for($i = $min;$i<=$max; $i++)
{
rowGenerator($i,$i+1);
}
for($i = $max-1;$i>=$min;$i--)
{
rowGenerator($i,$i+1);
}
echo '</table>';
}
this is the output of calling patternGenerator(3):
the output of calling patternGenerator(5):
I'm trying to use ONE PHP for loop to echo the sum of the numbers 1-10 as well as echo the sum of only the even numbers. I seem to have a problem as these iterations won't be "parallel"
Code:
<?php
$sum = 0; $evensum = 0;
for($x = 1, $y=2; $x<=10, $y<=6; $x++, $y += 2) {
$sum = $sum + $x; $evensum = $evensum + $y;
}
echo "total sum= ". $sum, ", even sum=" . $evensum;
?>
total sum should reflect 55 (1+2+3+4+5+6+7+8+9+10) and even sum should reflect 30 (2+4+6+8+10)
Just Use
<?php
$sum = 0; $evensum = 0;
for($x = 1; $x<=10; $x++) {
// sum all the number
$sum = $sum + $x;
// check the number is even
if( $x % 2 === 0 ) {
// sum only the even numbers
$evensum = $evensum + $x;
}
}
// output
echo "total sum= ". $sum, ", even sum=" . $evensum;
?>
Another approach is using range() and array_functions
$arr=range(1,10);
echo $sum=array_sum($arr);
function even($var)
{
return(!($var & 1));
}
echo $even=array_sum(array_filter($arr, "even"));
Sum all ranges
$all_sum=array_sum(range(1,10));
Sum even number (0,2,4,6,8,10)
$even_sum = array_sum(range(0,10,2));
I want to print all combination of sub range in an given array. I have an array of y number of elements in it from which I want to print all combination of contiguous sub range.
Constraint is : each sub range should have at least 2 elements and each element in sub range should be contiguous. It should share same border of each element.
For example, We have an array of 7 elements [11,12,13,14,11,12,13]
So, the total number of sub range combination will [7 * (7-1) /2] = 21
So, the Output will be something like this:
11,12
12,13
13,14
14,11
11,12
12,13
11,12,13
12,13,14
13,14,11
...
11,12,13,14 and so on (total 21 combination as per above array)
we should not print any combination which is not contiguous. example: [11,12,14] is not valid combination as it skips the element "13" in between.
I am able to print the combination with 2 elements but i am having difficulty in printing more then 2 elements combination.
Below is what I have tried so far.
$data=array("11","12","13","14","11","12","13");
$totalCount=count($data);
for($i=0;$i<$totalCount;$i++){
if(($i+1) < ($totalCount)){
echo "[".$data[$i].",".$data[$i+1]."]<br>";
}
}
You can do that:
$arr = [11,12,13,14,11,12,13];
function genComb($arr, $from = 1, $to = -1) {
$arraySize = count($arr);
if ($to == -1) $to = $arraySize;
$sizeLimit = $to + 1;
for ($i = $from; $i < $sizeLimit; $i++) { // size loop
$indexLimit = $arraySize - $i + 1;
for ($j = 0; $j < $indexLimit; $j++) { // position loop
yield array_slice($arr, $j, $i);
}
}
}
$count = 0;
foreach (genComb($arr, 2) as $item) {
echo implode(',', $item), PHP_EOL;
$count++;
}
echo "total: $count\n";
Casimir et Hippolyte was faster, but you can gain huge performance by processing each contiguous section independently:
function getCombos(&$data) {
$combos = array();
$count = count($data);
$i = 0;
while ($i < $count) {
$start = $i++;
while ($i < $count && $data[$i - 1] + 1 == $data[$i]) // look for contiguous items
$i++;
if ($i - $start > 1) // only add if there are at least 2
addCombos($data, $start, $i, $combos); // see other answer
}
return $combos;
}
How do I find the sum of all the digits in a number in PHP?
array_sum(str_split($number));
This assumes the number is positive (or, more accurately, that the conversion of $number into a string generates only digits).
Artefactos method is obviously unbeatable, but here an version how one could do it "manually":
$number = 1234567890;
$sum = 0;
do {
$sum += $number % 10;
}
while ($number = (int) ($number / 10));
This is actually faster than Artefactos method (at least for 1234567890), because it saves two function calls.
Another way, not so fast, not single line simple
<?php
$n = 123;
$nstr = $n . "";
$sum = 0;
for ($i = 0; $i < strlen($nstr); ++$i)
{
$sum += $nstr[$i];
}
echo $sum;
?>
It also assumes the number is positive.
function addDigits($num) {
if ($num % 9 == 0 && $num > 0) {
return 9;
} else {
return $num % 9;
}
}
only O(n)
at LeetCode submit result:
Runtime: 4 ms, faster than 92.86% of PHP online submissions for Add Digits.
Memory Usage: 14.3 MB, less than 100.00% of PHP online submissions for Add Digits.
<?php
// PHP program to calculate the sum of digits
function sum($num) {
$sum = 0;
for ($i = 0; $i < strlen($num); $i++){
$sum += $num[$i];
}
return $sum;
}
// Driver Code
$num = "925";
echo sum($num);
?>
Result will be 9+2+5 = 16
Try the following code:
<?php
$num = 525;
$sum = 0;
while ($num > 0)
{
$sum= $sum + ($num % 10);
$num= $num / 10;
}
echo "Summation=" . $sum;
?>
If interested with regex:
array_sum(preg_split("//", $number));
<?php
echo"----Sum of digit using php----";
echo"<br/ >";
$num=98765;
$sum=0;
$rem=0;
for($i=0;$i<=$num;$i++)
{
$rem=$num%10;
$sum=$sum+$rem;
$num=$num/10;
}
echo "The sum of digit 98765 is ".$sum;
?>
-----------------Output-------------
----Sum of digit using php----
The sum of digit 98765 is 35
// math before code
// base of digit sums is 9
// the product of all numbers multiplied by 9 equals 9 as digit sum
$nr = 58821.5712; // any number
// Initiallization
$d = array();
$d = explode(".",$nr); // cut decimal digits
$fl = strlen($d[1]); // count decimal digits
$pow = pow(10 ,$fl); // power up for integer
$nr = $nr * $pow; // make float become integer
// The Code
$ds = $nr % 9; // modulo of 9
if($ds == 0) $ds=9; // cancel out zeros
echo $ds;
Assume you want to find the sum of the digits of a number say 2395 the simplest solution would be to first split the digits and find out the sum then concatenate all the numbers into one single number.
<?php
$number=2;
$number1=3;
$number2=9;
$number3=5;
$combine=$number.$number1.$number2.$number3;
$sum=$number+$number1+$number2+$number3;
echo "The sum of $combine is $sum";
?>
One way of getting sum of digit however this is a slowest route.
$n=123;
while(($n=$n-9)>9);
echo "n: $n";
<html>
<head>
<title>detail</title>
</head>
<body>
<?php
$n = 123;
$sum=0; $n1=0;
for ($i =0; $i<=strlen($n);$i++)
{
$n1=$n%10;
$sum += $n1;
$n=$n/10;
}
echo $sum;
?>
</body>
</html>
Here's the code.. Please try this
<?php
$d=0;
$num=12345;
$temp=$num;
$sum=0;
while($temp>1)
{
$temp=$temp/10;
$d++;
}
echo "Digits Are : $d </br>";
for (;$num>1;)
{
$d=$num%10;
$num=$num/10;
$sum=$sum+$d;
}
echo "Sum of Digits is : $sum";
?>