Need a little help for algorithm - php

Right now I have a set of if and elseif to set the height of the div
<?php
if($num == 0){echo 'height:0px;';}
elseif($num > 0 && $num < 10) {echo 'height:3px;';}
elseif($num >= 10 && $num < 22) {echo 'height:7px;';}
elseif($num >= 22 && $num < 45) {echo 'height:16px;';}
elseif($num >= 45 && $num < 50) {echo 'height:33px;';}
elseif($num >= 50 && $num < 67) {echo 'height:36px;';}
elseif($num >= 67 && $num < 79) {echo 'height:48px;';}
elseif($num >= 79 && $num < 88) {echo 'height:56px;';}
elseif($num >= 88) {echo 'height:72px;';}
?>
The problem is that this is copyed 5 times for 5 different divs and think there is better way to do it
Like so :
<?php
function divHeight($maxNum,$number)
{
if($number == 0)
{
echo 'height:0px;' ;
}
elseif($number >= $maxNum)
{
echo 'height:72px;' ;
}
else
{
//here were the algorithm have to be
}
}
?>
I will call it like <?php divHeight(88,$number);?>
The max height of div is 72, now how to calculate the height?
// Edit : This is so simple :X :X but is too late and i havent sleept so
$newHeight = floor($number * 72 / 100);
echo $newHeight;

function mapNumToHeight($num) {
// Max $num => height for that num
$heightMap = array(
0 => 0,
9 => 3,
21 => 7,
44 => 16,
49 => 33,
66 => 36,
78 => 48,
87 => 56,
88 => 72
);
// Store the keys into an array that we can search
$keys = array_keys($heightMap);
rsort($keys);
// We want to find the smallest key that is greater than or equal to $num.
$best_match = $keys[0];
foreach($keys as $key) {
if($key >= $num) {
$best_match = $key;
}
}
return 'height:' . $heightMap[$best_match] . 'px;';
}
mapNumToHeight(3); // height:3px;
mapNumToHeight(33); // height:16px;
mapNumToHeight(87); // height:56px;
mapNumToHeight(88); // height:72px;
mapNumToHeight(1000); // height:72px;

Related

output numbers bold except some

How to produce the following output? All numbers should be bold except 10, 20, 30 and 40.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
My current code is:
<?php
$i = 1;
while($i <= 40) {
$m = ($i % 1);
if($m == 0) {
echo '<b><u>' . $i . '</b></u>';
}
$i++;
}
?>
Simple one:
<?php
for ($i=1;$i<=40;$i++){
if ($i % 10 == 0){
$result .= $i;
}
else{
$result .= "<b>".$i."</b>";
}
}
echo $result;
?>
Update 1:
If your logic is to be corrected then,
<?php
$i = 1;
while($i <= 40) {
$m = ($i % 10); // have to replace 1 by 10
if($m == 0) {
echo $i;
}
else{
echo '<b><u>' . $i . '</b></u>';
}
$i++;
}
?>
You can merge the if ($i%10 == 0) into single statement as well.
<?php
$i=1;
while($i<=40)
{
if ($i%10 == 0){
echo $i;
}
else{
echo '<b><u>'.$i.'</b></u>';
}
$i++;
}
?>
one small Correction From 1st answer #Fakhruddin Ujjainwala
Undefined variable: result
<?php
$result = "";
for ($i=1;$i<=40;$i++){
if ($i % 10 == 0){
$result .= $i;
}
else{
$result .= "<b>".$i."</b>";
}
}
echo $result;
?>

Fix for convert fraction short PHP snippet, issue with calculation converting a fraction to more readable format

Here is the problem, when it encounters fractions like: 300/10 instead of giving a result of "30"
the following code gives me: 1/0
$tokens = explode('/', $value);
while ($tokens[0] % 10 == 0) {
$tokens[0] = $tokens[0] / 10;
$tokens[1] = $tokens[1] / 10;
}
if ($tokens[1] == 1) {
return $tokens[0].' s';
} else {
return '1/'.floor(1/($tokens[0]/$tokens[1])).' s';
// return $tokens[0].'/'.$tokens[1].' s';
}
thanks
You should change the line while($tokens[0] % 10 === 0 && $tokens[1] % 10 === 0) { to while($tokens[0] % 10 === 0 && $tokens[1] % 10 === 0) {.
And the line return '1/'.floor(1/($tokens[0]/$tokens[1])).' s'; is not reliable.
If you want to reduce fractions, try this function:
function reduceFraction($fraction) {
sscanf($fraction, '%d/%d %s', $numerator, $denominator, $junk);
// TODO: validation
if( $denominator === null ) {
return (string)$numerator;
}
if( $numerator === $denominator ) {
return 1;
}
$max = max(array($numerator, $denominator));
for($i = 1; $i < $max; ++$i) {
if( $denominator % $i === 0 && $numerator % $i === 0) {
$common = $i;
}
}
if( $denominator === $common ) {
return (string)($numerator / $common);
}
return ($numerator / $common) . '/' . ($denominator / $common);
}
You could use it like this:
reduceFraction('300/10') . ' s';
It's also possible to generalize more the function for chained fractions (eg: '300/100/10'). I can send an implementation of it if you wish.
tell me why the "while ($tokens[0] % 10 == 0 && $tokens[1] % 10 ==0)"
would be better to use than just "while ($tokens[0] % 100 == 0)" since
both methods seem to work ok
If you try to use the string "3000/10" as an argument for each implementation, the one with while ($tokens[0] % 10 == 0 && $tokens[1] % 10 ==0) will return 300 s, and the other with while ($tokens[0] % 100 == 0) will return 1/0 s.
If you use the while ($tokens[0] % 100 == 0) method, the loop iterations are:
$tokens[0] = 3000 / 10 = 300;
$tokens[1] = 10 / 10 = 10;
$tokens[0] = 30 / 10 = 30;
$tokens[1] = 10 / 1 = .1;
Stopped because 30 % 100 != 0.
Since the $token[1] is not 1, it does not return "30 s".
1/30 is less than zero (0.0333...), thus floor(1/30) = 0. That's why it returns "1/0 s".
If you use the while ($tokens[0] % 10 == 0 && $tokens[1] % 10 == 0) method, the loop iterations are:
$tokens[0] = 3000 / 10 = 300;
$tokens[1] = 10 / 10 = 1;
Stopped because 1 % 10 != 0.
Since the $token[1] is not 1, it returns "30 s".
It is better because it will work with more inputs.
But I recommend you to use the "reduceFraction" function that I implemented.
It uses the maximum common denominator technique to reduce functions.
echo reduceFraction('3000/10'); outputs "300".
echo reduceFraction('300/10'); outputs "30".
echo reduceFraction('30/10'); outputs "3".
echo reduceFraction('3/10'); outputs "3/10".
echo reduceFraction('3/3'); outputs "1".
echo reduceFraction('222/444'); outputs "1/2".
echo reduceFraction('444/222'); outputs "2".

Why does this return 1 number and then stops the loop? PHP

I'm a beginner at PHP, so my code might not be efficient or good.
Why does this code return 1 number and then stops the loop? It's supposed to stop the loop when "the dice" rolled two of every number (1,2,3,4,5,6). But now it stops after randomly generating 1 number..
<?php
$sixCount = 0;
$fiveCount = 0;
$fourCount = 0;
$threeCount = 0;
$twoCount = 0;
$oneCount = 0;
$rollCount = 0;
do{
$roll = rand(1,6);
$rollCount++;
if($roll == 6){
$sixCount++;
echo "6";
} else if($roll == 5){
$fiveCount++;
echo "5";
} else if($roll == 4){
$fourCount++;
echo "4";
} else if($roll == 3){
$threeCount++;
echo "3";
} else if($roll == 2){
$twoCount++;
echo "2";
} else {
$oneCount++;
echo "1";
}
} while($sixCount < 3 && $sixCount > 1 && $fiveCount < 3 && $fiveCount > 1 && $fourCount < 3 && $fourCount > 1 && $threeCount < 3 && $threeCount > 1 && $twoCount < 3 && $twoCount > 1 && $oneCount < 3 && $oneCount > 1);
echo "<br />It took {$rollCount} rolls!";
?>
This is an exercise from Codecademy.com!
Thanks,
Jesper (New at Stackoverflow!)
After first execution of loop, you cannot have $sixCount > 1 && $fiveCount > 1, among other conditions.
After first roll, suppose it's 3, your variables are:
$sixCount = 0;
$fiveCount = 0;
$fourCount = 0;
$threeCount = 1;
$twoCount = 0;
$oneCount = 0;
It doesn't suit while conditions, cuz, for example, $sixCount > 1 is false and other vars too.
The while expression says:
while ($sixCount < 3 && $sixCount > 1 && $fiveCount < 3 && $fiveCount > 1 ...
If $sixCount is less than 3 and more than 1 that implies $sixCount equals 2. Ditto for the others. So it means "keep looping while $sixCount equals 2 and $fiveCount equals 2 and [all the others equal 2]".
You start with those variables at 0:
$sixCount = 0;
$fiveCount = 0;
...
So the loop condition is not initially met. The loop allows at most one of them to be incremented at most once:
$roll = rand(1, 6);
if ($roll == 6) {
$sixCount++;
echo "6";
} else if ($roll == 5) {
$fiveCount++;
echo "5";
} ...
No matter what number is rolled it is impossible to get any of the counts to 2 by the end of a single roll, and certainly not all of them, so the loop condition will not be met, and the loop will inevitably stop.
It's supposed to stop the loop when "the dice" rolled two of every number (1,2,3,4,5,6)
In that case, the correct condition would be:
while ($sixCount < 2 && $fiveCount < 2 && ...
As others have said, your conditional for the while loop will never be true. Instead, you want to make sure the variables aren't all at 2. Try this instead:
while ($sixCount < 2 || $fiveCount < 2 || $fourCount < 2 || $threeCount < 2 || $twoCount < 2 || $oneCount < 2)
I just adapted your script. It can be a funny game.
It rolls 6 dice times 2 (6 x 2) and then if requirements are not met, it rolls the dice again :
$rollCount = 0;
do{
$sixCount = 0;
$fiveCount = 0;
$fourCount = 0;
$threeCount = 0;
$twoCount = 0;
$oneCount = 0;
$rollCount++;
for ($i= 0; $i< 2 * 6; $i++) {
$roll = rand(1,6);
if($roll == 6){
$sixCount++;
echo "6";
} else if($roll == 5){
$fiveCount++;
echo "5";
} else if($roll == 4){
$fourCount++;
echo "4";
} else if($roll == 3){
$threeCount++;
echo "3";
} else if($roll == 2){
$twoCount++;
echo "2";
} else {
$oneCount++;
echo "1";
}
}
echo "_";
} while(!($sixCount < 3 && $sixCount > 1 && $fiveCount < 3 && $fiveCount > 1 && $fourCount < 3 && $fourCount > 1 && $threeCount < 3 && $threeCount > 1 && $twoCount < 3 && $twoCount > 1 && $oneCount < 3 && $oneCount > 1));
echo "<br />It took {$rollCount} rolls!";
$a = array(
$sixCount,
$fiveCount,
$fourCount,
$threeCount,
$twoCount,
$oneCount);
echo '<pre>';
print_r($a);
echo '</pre>';
Giving this king of output :
262225451666_535451252543_666153663214_652652635413_522615315213_412123422526_113553235335_255616351453_124215216465_112544353243_161145351612_522462262355_114331531645_563664155335_455623424146_233336226515_213136514365_646344361534_445325236533_423153546564_324466143565_422464136444_631511342612_516266141216_613556242333_351541131651_554665566244_261433652145_
It took 28 rolls!
Array
(
[0] => 2
[1] => 2
[2] => 2
[3] => 2
[4] => 2
[5] => 2
)

Create list per 4 records [duplicate]

This question already has answers here:
display data in multiple columns
(3 answers)
Closed 8 years ago.
I am trying to create multi-list of records with 4 records per list without knowing how many records there are. However, I cannot figure out how to handle the math. I manually typed in $n == 5 || $n == 9 etc knowing it is stipud and cannot exactly solve the problem. Can anyone help me how to handle that. Also, the lists underneath works well only if the total number of records cannot be evenly divided by 4. If it can, it will create a blank list at the end.
$query = "SELECT * FROM `table` WHERE `field` = $whatever";
if ($result = $con->query($query)){
$n = 1
$row_cnt = $result->num_rows;
$total_lists = round($row_cnt / 4, 0);
$current_list = 1;
echo "<ul>List $current_list of $total_lists";
while ($row = $result->fetch_assoc()) {
echo "<li>$row['something']</li>";
if ($n == 5 || $n == 9 || $n == 13 || $n == 17 || $n == 21 || $n ==25 || $n ==29 || $n == 33 || $n == 37 || $n == 41 || $n == 45 || $n == 49 || $n == 53 || $n == 57 || $n == 61 || $n == 65 || $n == 69 || $n == 73 || $n == 77){
echo "</ul>";
$current_list = $current_list + 1;
echo "<ul>List $current_list of $total_lists";
}
$n = $n + 1;
}
echo "</ul>";
}
Thanks in advance for the help. :)
SOLVED:
$query = "SELECT * FROM `table` WHERE `field` = $whatever";
if ($result = $con->query($query)){
$n = 0
$row_cnt = $result->num_rows;
$total_lists = ceil($row_cnt / 4);
$current_list = 1;
echo "<ul>List $current_list of $total_lists";
while ($row = $result->fetch_assoc()) {
$n++;
echo "<li>$row['something']</li>";
if ($row_cnt > 4) {
if ($n % 4 === 0) {
echo "</ul>";
$current_list = $current_list + 1;
echo "<ul>List $current_list of $total_lists";
}
}
}
echo "</ul>";
}
You're actually not too far off track from what you might want to be doing, you just need to use one additional tool to accomplish it: the % or modulus operator.
The modulus operator will return the remainder of division problem:
$x = 5 % 2; // 1
Looking at your logic, your action needs to be taken when your incrementer ($n) minus 1 divided by 4 would have a remainder of 0:
if (($n - 1) % 4 === 0)
{
//your <ul> insertion could go here.
}
Here's a link to the PHP manual page discussing mathematical operators:
http://us1.php.net/manual/en/language.operators.arithmetic.php
Alternatively, you could use a simple array_chunk() on your db results. Provide the proper grouping (in this case by four's) to it and them loop them thru foreach. Consider this example:
// dummy data (values from db)
$values_from_db = array(
array('id' => 1, 'something' => 'list1'),
array('id' => 2, 'something' => 'list2'),
array('id' => 3, 'something' => 'list3'),
array('id' => 4, 'something' => 'list4'),
array('id' => 5, 'something' => 'list5'),
array('id' => 6, 'something' => 'list6'),
array('id' => 7, 'something' => 'list7'),
array('id' => 8, 'something' => 'list8'),
array('id' => 9, 'something' => 'list9'),
);
$values_from_db = array_chunk($values_from_db, 4); // group them by four's
?>
<?php foreach($values_from_db as $key => $value): ?>
<ul style="list-style-type: none;">
<?php foreach($value as $index => $element): ?>
<li><?php echo $element['id'].'.'.$element['something']; ?></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>

PHP: How can I determine if a variable has a value that is between two distinct constant values?

How can I determine using PHP code that, for example, I have a variable that has a value
between 1 and 10, or
between 20 and 40?
if (($value > 1 && $value < 10) || ($value > 20 && $value < 40))
Do you mean like:
$val1 = rand( 1, 10 ); // gives one integer between 1 and 10
$val2 = rand( 20, 40 ) ; // gives one integer between 20 and 40
or perhaps:
$range = range( 1, 10 ); // gives array( 1, 2, ..., 10 );
$range2 = range( 20, 40 ); // gives array( 20, 21, ..., 40 );
or maybe:
$truth1 = $val >= 1 && $val <= 10; // true if 1 <= x <= 10
$truth2 = $val >= 20 && $val <= 40; // true if 20 <= x <= 40
suppose you wanted:
$in_range = ( $val > 1 && $val < 10 ) || ( $val > 20 && $val < 40 ); // true if 1 < x < 10 OR 20 < x < 40
You can do this:
if(in_array($value, range(1, 10)) || in_array($value, range(20, 40))) {
# enter code here
}
if (($value >= 1 && $value <= 10) || ($value >= 20 && $value <= 40)) {
// A value between 1 to 10, or 20 to 40.
}
Sorry for the late answer, but this function allow you to do that.
function int_between($value, $start, $end) {
return in_array($value, range($start, $end));
}
// Example
$value1 = 20;
$value2 = 40;
echo int_between(20, $value1, $value2) ? "true" : "false";
Guessing from the tag 'operand' you want to check a value?
$myValue = 5;
$minValue = 1;
$maxValue = 10;
if ($myValue >= $minValue && $myValue <= $maxValue) {
//do something
}
If you just want to check the value is in Range, use this:
MIN_VALUE = 1;
MAX_VALUE = 100;
$customValue = min(MAX_VALUE,max(MIN_VALUE,$customValue)));
Try This
if (($val >= 1 && $val <= 10) || ($val >= 20 && $val <= 40))
This will return the value between 1 to 10 & 20 to 40.

Categories