Average from Array - PHP - php

<?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>";

Related

Can't understand why my php cosine similarity code isn't working

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!

PHP - Finding consecutive values in multidimensional associative arrays for seat reservation program

I'm working on a program to reserve seats for a show. I have a multidimensional array that is created using $row and $column variables. After making a few initial reservations, I need to pass integers into a function/some code to make further reservations.
I've tried looping through the array to find consecutive available seats (value "avail") but it ignores reserved seats or skips over them. I'll need to later use manhattan distance to reserve the best seats (from row 1, seat 6) first.
function to create the array:
//function to create seating chart data structure
function createChart($row, $column){
//create array for row values
$row_chart = array();
for($r=0; $r < $row; $r++){
$row_number = $r + 1;
$row_chart[$row_number] = array(); // array of cells for row $r
}
//create array for column values
$column_chart = array();
for($c=0; $c < $column; $c++){
$column_number = $c + 1;
//$location = $c_num;
$status = "avail";
foreach($row_chart as $key => $value){
$column_chart[$column_number] = $status; //add arrays of "seats" for each row
}
}
//nest the column array into the row array
foreach($row_chart as $key => $value){
foreach($column_chart as $k => $v){
$seating_chart[$key][$k] = $status;
}
}
//$seating_chart = array_combine($row_chart, $column_chart);
return $seating_chart;
}
function to make initial reservations:
$initial_reservation = "R1C4 R1C6 R2C3 R2C7 R3C9 R3C10";
$initial_reservation = explode(" ", $initial_reservation);
echo "<br> <br>";
print_r($initial_reservation);
$initial_res_length = count($initial_reservation);
echo "<br> <br>";
//echo $initial_res_length;
//split each seat up into integers to mark it reserved in the array
//issue for flexibility: find way to break up string by letters and numbers for larger charts
for($a = 0; $a < $initial_res_length; $a++){
$reso_row = substr($initial_reservation[$a], 1, 1);
//echo $reso_row . "<br>";
$reso_column = substr($initial_reservation[$a], 3, 2);
//echo $reso_column . "<br>";
$working_chart[$reso_row][$reso_column] = "reserved";
}
//echo "<br> <br>";
//echo "<pre>" . print_r($working_chart, 1) . "</pre>";
what I have so far in attempt to make further reservations:
//write some code to find consecutive seats
$seats_needed = 4;
$outer_array_length = count($working_chart);
//echo $outer_array_length;
for($d = 1; $d < $outer_array_length + 1; $d++){
for($e = 1; $e < $seats_needed + 1; $e++){
//issue: run through $seats_needed amount of times and executes the code block
//needed: check if $seats_needed amount of seats in available first then run reservation code
if($working_chart[$d][$e] === "avail"){
$working_chart[$d][$e] = "new reservation";
}
else{
echo "Sorry, not possible.";
}
}
break;
}
echo "<br> <br>";
echo "<pre>" . print_r($working_chart, 1) . "</pre>";
I'd like to be able to find a number of available seats ($seats_needed) first, and then loop through to reserve them.
I have initialized the $working_chart with :
$working_chart = createChart(10, 11);
I have written the attempt to make further reservations :
foreach(array_keys($working_chart) as $d ){
$maxColumn = count($working_chart[$d]) - $seats_needed + 1;
for($e = 1; $e <= $maxColumn ; $e++){
if(["avail"] === array_unique(array_slice($working_chart[$d], $e - 1 , $seats_needed))){
$working_chart[$d] = array_replace($working_chart[$d], array_fill($e, $seats_needed, "new reservation"));
break 2;
}
else{
echo "Sorry, not possible.";
}
}
}
I hope it can help you...

How do I divide an integer over multiple values in PHP?

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;
}
}

Role a 6 to win! PHP Code

I'm currently learning how to use do/while loops in PHP through codeacademy. I'm working on a challenge where you create a six-sided die and continue rolling until you get a six. Here's what I've come up with so far:
<?php
$roll = 1;
do {
echo “Roll Number " . $roll . ". Begin rolling for a 6.";
} while ($roll != 6); {
for ($rollNumber = 1; $roll != 6; $roll ++) {
$roll = rand(1, 6);
echo "On roll number " . $rollNumber . "You got a " $roll ".\n";
};}
?>
I though the best way to get started is by creating a roll variable that we can use once for the do loop to check if it's working:
$roll = 1;
I set the value to one instead of zero, because there's no zero number on a die, and we'll assume the player first rolls a one. Next I want to check if the do loop is working so I echo the following:
do {
echo “Roll Number " . $roll . ". Begin rolling for a 6.";
}
After making sure the do loop worked, I create the while condition:
while ($roll != 6) {
Then I want to create a rollNumber variable to keep track of what roll I'm on and increment it:
for ($rollNumber = 1; $roll != 6; $roll ++) {
next I set the value of the roll variable so that it generates a random number between 1 and 6:
$roll = rand(1,6);
Finally I want to echo the message "On roll number you got a ." :
echo “On roll number “ . $rollNumber . "You got a " $roll “.\n";}
For some reason the code's not working. Any suggestions or help would be much appreciated! Thanks.
You were on the right track with a while loop and rand(). The only other thing you needed was to set a count variable to display the roll number (you can just increment this variable on every "roll").
Your code could be simplified to this:
$c = $n = 1;
while ($n != 6) {
echo 'on roll number ' . $c++ . ' you rolled a ' . $n = rand(1, 6) . "\n";
}
Here's an example
You've made this way too complicated. There's no need for two loops.
$rolled = 0;
$numbers = range(1, 6); //generate array with 1-6
$counter = 0;
while($rolled!=6)
{
$counter++;
shuffle($numbers); //shuffle array
$rolled = $numbers[0]; //grab first item
echo '<br/>(Roll ' . $counter . ') ' . $rolled;
}
Why not have a function that returns the result of a roll, and then a loop that calls this function until it returns a 6?
<?php
function roll() {
return mt_rand(1, 6);
}
$roll = 1;
do {
if (roll() == 6) {
printf('You rolled a 6 on roll %d.', $roll);
break;
}
$roll++;
} while (0);
This do/while loop continues until the roll() function returns a 6.

PHP equation from JavaScript

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
}

Categories