I'm trying to make a little PHP script for fun, and I'm a little stuck.
I want to divide an integer (for example 5) over multiple values.
For example:
$total = 5;
$mike = 0;
$ralf = 0;
$ashley = 0;
// Run the magic here
echo "Mike has " . $mike . " apples, Ralf has " . $ralf ." apples and Ashley has " . $ashley . " apples";
The output that I expect would look something like this:
Mike has 2 apples, Ralf has 1 apples and Ashley has 2 apples
Is there a way how to do this? :)
I can't do this hard coded, because I want the values to be randomized.
Cheers
Do it like this:
$total = 5;
$mike = rand(1,$total-2); // so that max value is 3 (everyone should get at least 1) ($total - $numberOfVarsToDistributeTheValueTo + 1)
$ralf = rand(1,$total - $mike - 1); // if 3 goes to mike, only 1 goes to ralf
$ashley = $total - $mike - $ralf; // i hope you understand.
// use it.
Something like this would work:
$people = array('mike','ralf','ashley');
$num = count($people);
$sum = 5; // TOTAL SUM TO DIVIDE
$groups = array();
$group = 0;
while(array_sum($groups) != $sum) {
$groups[$group] = mt_rand(0, $sum/mt_rand(1,5));
if(++$group == $num){
$group = 0;
}
}
// COMBINE ARRAY KEYS WITH VALUES
$total = array_combine($people, $groups);
echo "Mike has " . $total['mike'] . " apples, Ralf has " . $total['ralf'] ." apples and Ashley has " . $total['ashley'] . " apples";
Solution is inspired from this answer: https://stackoverflow.com/a/7289357/1363190
Hope This function will do your work . it can work for variable # of persons also.
divide_items(10,['mike','ralf','ashley']);
function divide_items($total=1,array $persons){
$progressed = 0;
for($i=0;$i<count($persons);$i++){
echo $random_count = rand(1,$total);
if(($i==(count($persons)-1)) && $progressed<$total ){
$random_count1 =$total - $progressed;
echo $persons[$i]." has ".$random_count1 ." Items<br>";
continue;
}
$progressed = $progressed+$random_count;
if($progressed<=$total){
echo $persons[$i]." has ".$random_count ." Items<br>";
}else{
echo $persons[$i]." has 0 Item<br>";
}
$total = $total-$random_count;
$progressed = 0;
}
}
Related
<?php
$games = [
["Call of Duty", "Shooter", 59.95],
["Rocket League", "Sport", 19.95],
["Assassins Creed", "RP", 49.95]
];
?>
// i have an assignment where they want me to get the average string length from the titles and a average game price and echo it out like :
// echo "average price: €" . $averageprice;
// echo "average length of titles: " . $averagetitle
it needs to include:
number_format
for loop
i have tried numerous options but only got into coding for half a year now and havent really gotten into php. tried looking up different functions to use but couldnt get my head wrapped around it so i wonderd if the amazing coding community could heklp me out.
Average is computed as $sum_of_values/$number_of_values, so you can use for loop to loop throught all the items and sum them up as for example $sum_of_prices += $current_item[2] and finally divide it by length of array (count($games)).
For length of string, just find out length of string by strlen($current_item[0]) and add it to sum of lengths of titles like in prices. Finally divide it by length of array. You can use same loop for this.
Not sure to have understand right your request,
If games informations are always in the same position you can try something like this:
<?php
$games = [
["Call of Duty", "Shooter", 59.95],
["Rocket League", "Sport", 19.95],
["Assassins Creed", "RP", 49.95]
];
$avg_name_lenght = 0;
$avg_game_price = 0;
foreach($games as $game ){
$game_name_lenght = strlen($game[0]);
$avg_name_lenght += $game_name_lenght;
$game_price = $game[2];
$avg_game_price +=$game_price;
}
$avg_name_lenght = $avg_name_lenght / count($games);
$avg_game_price = $avg_game_price / count($games);
echo "<p>average price: €" . $avg_game_price."</p>";
echo "<p>average length of titles: " . $avg_name_lenght."</p>";
?>
Try something like this.
It includes a for loop en the number_format function:
function getAveragePrice($array) {
$sum = 0;
for($i = 0; $i < count($array); $i++) {
$sum += $array[$i][2];
}
return number_format($sum / count($array), 2);
}
function getAverageLength($array) {
$sum = 0;
for($i = 0; $i < count($array); $i++) {
$sum += strlen($array[$i][0]);
}
return number_format($sum / count($array), 2);
}
$averageprice = getAveragePrice($games);
$averagetitle = getAverageLength($games);
echo "average price: €" . $averageprice . "<br>";
echo "average length of titles: " . $averagetitle . "<br>";
I'm working on a website for my friend's gaming clan. I'm trying to have a php code that takes the player's coordinates, loops over some known locations and print the name of the closest location.
I can't get it to work however. It always seems to want to print "Balota" which is index 1 in the array. I also noticed that the cosine function can't be working as all values are above 1.0.
But I'm completely stuck now. I think I've been beating my head over it for too long and its something right in front of me but I can't see it.
<?php
function DotProd($loc1,$loc2){
return array_sum(array_map(create_function('$a, $b', 'return $a * $b;'), $loc1, $loc2));
}
function CosineSim($loc1,$loc2){
return DotProd($loc2,$loc2)/sqrt(DotProd($loc1,$loc2)*DotProd($loc1,$loc2));
}
function Closest($loc){
$novo = array(11300,14300);
$balota = array(4500,2500);
$zelen = array(2500,5200);
$sever = array(7900,12600);
$vybor = array(4500,8200);
$nwaf = array(4500,10200);
$neaf = array(12100,12500);
$kamensk = array(7870,14600);
$bere = array(12900,10000);
$gorka = array(9600,8900);
$elektro = array(10100,2000);
$cherno = array(6600,2600);
$stary = array(6100,7700);
$novy = array(7000,7700);
$mysk = array(1100,7200);
$locations = array($novo,$balota,$zelen,$sever,$vybor,$nwaf,$neaf,
$kamensk,$bere,$gorka,$elektro,$cherno,$stary,$novy,$mysk);
$sim = 99999999999;
$locat = 0;
for($i = 14; $i >= 0; $i--){
$s = CosineSim($loc,$locations[$i]);
echo "<br>" . $i . " " . CosineSim($loc,$locations[$i]);
if($s < $sim){
$sim = $s;
$locat = $i;
}
}
$items = array("Novo","Balota","Zelenogorsk","Severograd","Vybor","NWAF","NEAF","Kamensk Military","Berezino",
"Gorka","Elektro","Cherno","Stary Sobor","Novy Sobor","Myshkino");
return $items[$locat];
}
$x = $_GET["xpos"];
$y = $_GET["ypos"];
$location = array($x,$y);
echo "<b>You are at " . $x . ":" . $y;
$index = Closest($location);
echo "<br>You're pretty close to ". $index . "<br>";
?>
I am using a distance calculation formula based on the link: https://www.mathwarehouse.com/algebra/distance_formula/index.php
I only changed CosineSim. The rest of the code remains the same. And you don't actually need DotProd. It's not elegant but it works for me.
function CosineSim($loc1,$loc2){
// sum of x coordinates
$x1 = ($loc1[0]-$loc2[0])*($loc1[0]-$loc2[0]);
// sum of y coordinates
$y2 = ($loc1[1]-$loc2[1])*($loc1[1]-$loc2[1]);
$summ = $x1 + $y2;
$sqrt_res = sqrt($summ);
return $sqrt_res;
}
If I enter something like:
You are at 4640:7205
...
You're pretty close to Vybor
Hope this helps!
Ok, I don't even know where to start with this one! I'll try and explain what I want to achieve, and we'll go from there....
I have a list of dates each with an associated number, say from 20-100. What I want to do is to output the date in a shade which represents the associated number. So 20 would display in a light blue and 100 in a dark blue. My code so far looks like this...
dateArray = Array('2001-01-01'=>30, '2001-02-01'=>40, '2001-03-01'=>50, '2001-04-01'=>60, '2001-05-01'=>70, '2001-06-01'=>80, '2001-07-01'=>90, '2001-08-01'=>90, '2001-09-01'=>80, '2001-10-01'=>70, '2001-11-01'=>60, '2001-12-01'=>50)
$maxNum = max($dateArray);
$minNum = min($dateArray);
foreach($dateArray AS $date => $num){
$lightest = 'rgb(204,204,255)';
$darkest = 'rgb(0, 0, 179)';
///magic that converts $num into $shade goes here///
echo "<span style='color:$shade'>$date</span><br>"
}
Any ideas? Thanks
I would do something like that :
$dateArray = Array('2001-01-01'=>30, '2001-02-01'=>40, '2001-03-01'=>50, '2001-04-01'=>60, '2001-05-01'=>70, '2001-06-01'=>80, '2001-07-01'=>90, '2001-08-01'=>90, '2001-09-01'=>80, '2001-10-01'=>70, '2001-11-01'=>60, '2001-12-01'=>50)
// get max and min values
$maxNum = max($dateArray);
$minNum = min($dateArray);
// set rgb values for max and min
$lightest = array(204, 204, 255);
$darkest = array(0, 0, 179);
foreach($dateArray AS $date => $num)
{
// get a "delta" where the current num value is
$delta = ($num / $maxNum) - $minNum;
// get a pro-rata values thanks to $delta
$shadesNum = array(
$delta * ($lightest[0] - $darkest[0]) + $darkest[0],
$delta * ($lightest[1] - $darkest[1]) + $darkest[1],
$delta * ($lightest[2] - $darkest[2]) + $darkest[2]
);
echo "<span style='rgb(".implode(',', $shadesNum).")'>$date</span><br>";
}
Some languages have a "lerp" function - linear interpolation. Quite useful.
My suggestion:
for ($x1=20; $x1<=100; $x1+=10)
echo $x1 . ": " . getshade($x1) . "<br />\n";
function getshade($num) {
$rlight = 204;
$glight = 204;
$blight = 255;
$rdark = 0;
$gdark = 0;
$bdark = 179;
$lightnum = 20;
$darknum = 100;
$k01 = ($num-$lightnum)/($darknum-$lightnum); // 0 to 1
$rshade = ilerp($rlight, $rdark, $k01);
$gshade = ilerp($glight, $gdark, $k01);
$bshade = ilerp($blight, $bdark, $k01);
return "rgb($rshade,$gshade,$bshade)"; }
function lerp($start, $end, $k01) { // linear interpolation
return $k01*$end + (1.0-$k01)*$start; }
function ilerp($start, $end, $k01) { // integer lerp
return intval($k01*$end + (1.0-$k01)*$start); }
EDIT: Same thing but better:
$rgblight = [204,204,255];
$rgbdark = [0,0,179];
$numlight = 20;
$numdark = 100;
for ($x1=20; $x1<=100; $x1+=10)
echo $x1 . ": " . getshade2($x1, $numlight, $numdark, $rgblight, $rgbdark) . "<br />\n";
function getshade2($num, $numlight, $numdark, $rgblight, $rgbdark) {
$k01 = ($num-$numlight)/($numdark-$numlight);
for ($i1=0; $i1<3; $i1+=1)
$rgb[$i1] = ilerp($rgblight[$i1], $rgbdark[$i1], $k01);
return "rgb({$rgb[0]},{$rgb[1]},{$rgb[2]})"; }
I've wrote a script in PHP for an university big data project.
The following code should support following function:
Read amount of data from a table
read a subset of the same table und extend it with 2 columns which calculate 2 values.
generate f.e. 1000 inserts and commit them to an other table
do this for the whole dataset of point 1
My problem:
0-1000:
my solution inserts in the first try 1000 datalines
1000-2000:
in this step it inserts 2000 datalines, so after the 2nd step it seems to insert 0-2000 datalines of the origin dataset. In sum 3000 datalines.
I'm a little bit out of ideas... I don't see my failure.
<?php
$user = 'root';
$pass = '';
$kill = 0;
echo 'Connecting to DB:';
try {
$db1 = new PDO('mysql:host=localhost;dbname=itt2_joined;charset=utf8',$user,$pass);
$db1->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo "OK \nGOING2COPY!\n";
}
catch(PDOException $ex) {
echo " Failed - Process stopped!\n";
$kill = 1;
}
if(!$kill) {
$stmt = 'SELECT
`id_transaction`
FROM
`database_joined_full`
WHERE
`relative_delivery_date` > 0
AND
`relative_received_date` > 0
AND
`relative_issued_date` > 0';
$setSize = $db1->query($stmt)->rowCount();
echo "No. Of Datasets: " . $setSize . "\n";
$stepSize = 1000;
echo "Start Copy $stepSize Datasets per Query! \n";
$copy = 1;
$lower = 0;
$upper = 0;
echo "[";
while($copy) {
$lower = $upper;
$upper += $stepSize;
$upper = ($upper > $setSize ? $setSize : $upper);
$data = $db1->query("SELECT
`id_transaction`,
`id_order_line`,
`relative_transaction_date`,
`relative_requested_date`,
`new_requested_qty`, `new_requested_price`,
`relative_suggested_date`,
`new_suggested_qty`,
`delivery_qty`,
`relative_delivery_date`,
`received_qty`,
`relative_received_date`,
`id_order_header`,
`delivery_counter`,
`relative_issued_date`,
`relative_xcurrent_date`,
`issued_quantity`,
`current_quantity`,
`product_code`,
`destination`,
`relative_issuing_date`,
`delivery_location`,
`issuer`,
`id_supplier`,
`currency`,
`shipment`,
`issued_price4unit`,
`current_price4unit`,
`total_delivered`
FROM
`database_joined_full`
WHERE
`relative_delivery_date` > 0
AND
`relative_received_date` > 0
AND
`relative_issued_date` > 0
LIMIT $lower OFFSET $stepSize")->fetchAll();
$db1->beginTransaction();
foreach($data as $row) {
$sql = "";
$sql = "INSERT INTO `refactored_data` (`id_transaction`, `id_order_line`, `relative_transaction_date`,
`relative_requested_date`, `new_requested_qty`, `new_requested_price`, `relative_suggested_date`,
`new_suggested_qty`, `delivery_qty`, `relative_delivery_date`, `received_qty`,
`relative_received_date`, `id_order_header`, `delivery_counter`, `relative_issued_date`,
`relative_xcurrent_date`, `issued_quantity`, `current_quantity`, `product_code`, `destination`,
`relative_issuing_date`, `delivery_location`, `issuer`, `id_supplier`, `currency`, `shipment`,
`issued_price4unit`, `current_price4unit`, `total_delivered`, `shipment_delay`, `sending_delayed`) VALUES ";
$sql .= "(";
for($i = 0; $i<sizeof($row)/2; $i++) {
$sql .= "'".$row[$i] . "', ";
}
$sql .= $row['relative_received_date'] - $row['relative_delivery_date'] . ',';
$sql .= ($row['relative_received_date'] <= $row['relative_issued_date'] ? 1 : 0) .')';
$db1->prepare($sql)->execute();
}
$db1->commit();
// Statusbar
//echo "\n$lower - $upper\n";
$perc = ceil(($upper/$setSize) *40);
$bar = "\r[". str_repeat("=", $perc - 1). ">";
$bar .= str_repeat(" ", 40 - $perc) . "] - " . number_format($upper / $setSize * 100, 3) ."% ";
echo "\033$bar"; // Note the \033. Put the cursor at the beginning of the line
//While_Exit
$copy = ($upper == $setSize ? 0 : 1);
//$copy = 0;
}
echo "\nall done, BYE! \n";
}
?>
You're using the stepsize as the offset each time:
LIMIT $lower OFFSET $stepSize
Should be:
LIMIT $stepSize OFFSET $lower
Oh thank you! I haven't seen the failure.
Now the code works, nearly completely, my last problem is the following:
in the first Select query i get from '->rowCount();' the number of rows of the select query.
But with my insertion copys a bit more data. But in the second Select i have the same Where clause likewise the first Select query.
I get from the CLI-Print : No. of Rows: 655056
and it writes in the Database 658597
so how do i get the 3541 rows?
or is maybe a failure inside the Insert?
Greetings
I have this JavaScript equation which I'm now trying to transform to PHP.
JavaScript:
LVL=new Array();
LVL[1]=128;
LVL[0]=128;
m=.05;
for (i=1;i<101;i++) {
if (i>1) {
LVL[i]=Math.floor(LVL[i-1]+(LVL[i-1]*m));
m=m+.0015;
}
}
then it's a bunch of document.writes of a table and a for loop.
Here's what I have so far (which is NOT working):
<?php
$n = 1; // level
$m = .05; // exp modifier
$exp = floor($n*1+($n-1)*$m);
echo "Level " . $n . ", exp needed: " . $exp; // 128 exp
?>
The PHP output is: Level 1, exp needed: 1 and that's WRONG.
It SHOULD say: Level 1, exp needed: 128
What am I doing wrong?
A direct transcription:
$LVL = array();
$LVL[1] = 128;
$LVL[0] = 128;
$m = .05;
for ($i = 1; $i < 101; $i++)
{
if ($i > 1)
{
$LVL[$i] = floor($LVL[$i-1] + $LVL[$i-1]*$m);
$m = $m + .0015
}
}
You need to build the array as its built bottom-up
You do a couple of errors:
you use the index (the level) as it is the amount of the experience points needed to
reach the level.
you forgot the for (if you are testing the formula it is ok)
the code so far:
$lvl = array(128,128);
$modifier=.05;
for ($i=1;$i<101;i++) {
$lvl[$i]=floor($lvl[$i-1]*(1+$modifier));
$modifier+=0.0015;
}
foreach ($lvl as $level=>$points) {
echo "Level " . $level . ", exp needed: " . $points ."\n<br />"; // 128 exp
}