I made this code for calculating max winning & losing streaks on an array of values. But I can get my head around doing it in one foreach loop. Currently I'm using 2 loops as follow :
public function calculateStreaks()
{
$max_win_streak = 0;
$_win_streak = 0;
$max_loss_streak = 0;
$_loss_streak = 0;
foreach($this->all_trades_pnl as $value){
if($value >= 0) {
$_win_streak++;
if($_win_streak > $max_win_streak){
$max_win_streak = $_win_streak;
}
}
else {
$_win_streak = 0;
}
}
foreach($this->all_trades_pnl as $value){
if($value < 0) {
$_loss_streak++;
if($_loss_streak > $max_loss_streak) {
$max_loss_streak = $_loss_streak;
}
}
else {
$_loss_streak = 0;
}
}
return array('win_streak' => $max_win_streak, 'loss_streak' => $max_loss_streak);
}
It works but seems far from optimized, any ideas to code this better ?
Thanks a lot in advance,
Regards,
John
Since both your loop are equal i think you can mix them toghter and assign all variables at once as follow
public function calculateStreaks()
{
$max_win_streak = 0;
$_win_streak = 0;
$max_loss_streak = 0;
$_loss_streak = 0;
foreach($this->all_trades_pnl as $value){
if($value >= 0) {
$_win_streak++;
if($_win_streak > $max_win_streak){
$max_win_streak = $_win_streak;
}
$_loss_streak = 0;
}
else if($value < 0) {
$_loss_streak++;
if($_loss_streak > $max_loss_streak) {
$max_loss_streak = $_loss_streak;
}
$_win_streak = 0;
}
}
return array('win_streak' => $max_win_streak, 'loss_streak' => $max_loss_streak);
}
Related
I had a job interview test and the question I got was about making a function which would return the number of ways a number could be generated by using numbers from a certain set and any number in the set can be used N times.
It is like if I have the number 10 and I want to find out how many ways 10 can be generated using [2,3,5]
2+2+2+2+2 = 10
5+3+2 = 10
2+2+3+3 = 10
5+5 = 10
to solve it I made this function:
function getNumberOfWays($money, $coins) {
static $level = 0;
if (!$level) {
sort($coins);
}
if ($level && !$money) {
return 1;
} elseif (!$level && !$money) {
return 0;
}
if ($money === 1 && array_search(1, $coins) !== false) {
return 1;
} elseif ($money === 1 && array_search(1, $coins) === false) {
return 0;
}
$r = 0;
$tmpCoins = $coins;
foreach ($coins as $index => $coin) {
if (!$coin || $coin > $money) {
continue;
}
$tmpCoins[$index] = 0;
$tmpMoney = $money;
do {
$tmpMoney -= $coin;
if ($tmpMoney >= 0) {
$level++;
$r += getNumberOfWays($tmpMoney, $tmpCoins);
$level--;
} elseif (!$tmpMoney) {
$r++;
}
} while ($tmpMoney >= 0);
}
return $r;
}
This function works ok and returns the right value.
My question is if there is a better way for it.
Thanks
$data = array(5,0,15,20,22,14,13,15,12,22,40,25);
Hi , i want to traverse the data points above and find the turning points based on a range.
The way i'm tackling it so far is simply taking the $array[$i] - $array[$i-1] , and if the absolute difference is greater than the range - i'm taking it as a turning point . however - the logic is flawed as if it moved slightly up and then back down - it breaks the cycle.
The 3 down values should have been enough to make X , a turning point downwards , but because they individually do not meet the range - they are discarded .
Any solutions ?
if($diff >= 0)
{
$diff_up = $diff_up + $diff;
}
else
{
$diff_down = $diff_down + abs($diff);
}
if((($diff_up-$diff_down) >=$range) && ($pivot_type != "UP"))
{
echo "Pivot UP at : ".$current;
break;
}
else if((($diff_down-$diff_up) >$range) && ($pivot_type != "DOWN"))
{
echo "Pivot DOWN at : ".$current;
break;
}
What you are looking for is all local minima and maxima, This is a good article.
I made this (with inspiration from:
get extremes from list of numbers):
<?php
$data = array(5,0,15,20,22,14,13,15,12,22,40,25);
function minima_and_maxima(array $array){
$maxima = [];
$minima = [];
$maxima[] = $array[0];
for($i = 1; $i < count($array) - 1; $i++){
$more_than_last = $array[$i] > $array[$i-1];
$more_than_next = $array[$i] > $array[$i+1];
$next_is_equal = $array[$i] == $array[$i+1];
if($next_is_equal) {
continue;
}
if ($i == 0) {
if ($more_than_next) {
$maxima[] = $array[$i];
} else {
$minima[] = $array[$i];
}
} elseif ($i == count($array)-1) {
if ($more_than_last) {
$maxima[] = $array[$i];
} else {
$minima[] = $array[$i];
}
} else {
if ($more_than_last && $more_than_next) {
$maxima[] = $array[$i];
} elseif (!$more_than_last && !$more_than_next) {
$minima[] = $array[$i];
}
}
}
for ($i = 0; $i < count($maxima); $i++) {
$current_maxima = $maxima[$i];
$next_maxima = $maxima[$i+1];
if ($current_maxima > $next_maxima) {
unset($maxima[$i+1]);
}
}
for ($i = 0; $i < count($minima); $i++) {
$current_minima = $minima[$i];
$next_minima = $minima[$i+1];
if ($next_minima < $current_minima) {
unset($minima[$i]);
}
}
return [
'maxima' => array_values($maxima),
'minima' => array_values($minima),
];
}
function get_turning_points($data)
{
$mins_and_maxs = minima_and_maxima($data);
$turning_points = [];
for ($i = 0; $i < count($mins_and_maxs['maxima']) - 1; $i++) {
$turning_points[] = $mins_and_maxs['maxima'][$i];
$turning_points[] = $mins_and_maxs['minima'][$i];
}
$turning_points[] = $mins_and_maxs['maxima'][count($mins_and_maxs['maxima'])-1];
return $turning_points;
}
print_r(get_turning_points($data));
This gives you:
Array
(
[0] => 5
[1] => 0
[2] => 22
[3] => 12
[4] => 40
)
Demo: https://eval.in/832708
Hope this helps :)
The below code works and does output exactly what i want. I made a foreach loop getting the values of a specific field ($CustomFields...) which is part of a framework variable. Then is only counts that field when the condition is "group".
After that i want to het the average price of all fields / count.
// ########### Get average hourly rate for group classes
$itemsperhour = array();
$countperhour = 0;
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson',$listing,false,false) == 'group') {
$itemsperhour[] = $CustomFields->field('jr_hourlyrateus',$listing,false,false);
$countperhour = $countperhour + 1;
}
}
//print_r($items);
if ($countperhour > 0) {
$totalperhour = array_sum($itemsperhour);
$averageperhour =($totalperhour / $countperhour);
echo round($averageperhour,2);
} else {
echo "No data";
}
unset ($averageperhour);
As said, the snippet works. But may I ask how other people would write such a script related to optimise such a piece of code (for speed and readability?
PHP 5.6+
Jasper
Below is one way of optimizing:
$totalperhour = 0;
$countperhour = 0;
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson',$listing,false,false) == 'group') {
$totalperhour += $CustomFields->field('jr_hourlyrateus',$listing,false,false);
$countperhour = $countperhour + 1;
}
}
if($countperhour > 0) {
$averageperhour =($totalperhour / $countperhour);
echo round($averageperhour,2);
$averageperhour = '';
} else {
echo "No data";
}
I would suppose to use array_reduce function for getting the average:
$averageperhour = array_reduce($listings, function($average, $listing) use (&$CustomFields)
{
static $sum = 0;
static $counter = 0;
if ($CustomFields->fieldValue('jr_typeoflesson', $listing, false, false) == 'group') {
$sum += $CustomFields->field('jr_hourlyrateus', $listing, false, false);
$counter ++;
$average = round(($sum / $counter), 2);
}
return $average;
}, 'No data');
echo $averageperhour;
Not sure about speed improvement (needs testing), but this variant seems to me like more readable.
How about this?
$itemsPerHour = [];
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson', $listing, false, false) !== 'group') {
continue;
}
$itemsPerHour[] = $CustomFields->field('jr_hourlyrateus', $listing, false, false);
}
$countPerHour = count($itemsPerHour);
if ($countPerHour > 0) {
$averagePerHour = array_sum($itemsPerHour) / $countPerHour;
echo round($averagePerHour,2);
} else {
echo "No data";
}
I am trying to evaluate the content of an array. The array contain water temperatures submitted by a user.
The user submits 2 temperaures, one for hot water and one for cold water.
What I need is to evaluate both array items to find if they are within the limits, the limits are "Hot water: between 50 and 66", "Cold water less than 21".
If either Hot or Cold fail the check flag the Status "1" or if they both pass the check flag Status "0".
Below is the code I am working with:
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray new(array);
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$field = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val > $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
My question is:
When I run the script the array key(0) works but when the array key(1) is evaluted the status flag for key(1) overrides the status flag for key0.
If anyone can help that would be great.
Many thanks for your time.
It seems OK to me, exept for the values at limit, and you can simplify
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray = array("58", "21");
$Status = array() ;
foreach($SeqWaterArray as $key => $val) {
if($key == 0) {
$Status = ($val >= $row_WaterTemp['HotMin'] && $val <= $row_WaterTemp['Hotmax']) ;
$WaterHot = $val;
} else if($key == 1) {
$Status += ($val >= $row_WaterTemp['ColdMax']) ;
$WaterCold = $val;
}
}
If one fails, $Status = 1, if the two tests failed, $Status = 2, if it's ok, $Status = 0.
<?php
// this function return BOOL (true/false) when the condition is met
function isBetween($val, $min, $max) {
return ($val >= $min && $val <= $max);
}
$coldMax = 20; $hotMin = 50; $hotMax = 66;
// I decided to simulate a test of more cases:
$SeqWaterArray['john'] = array(58, 30);
$SeqWaterArray['martin'] = array(34, 15);
$SeqWaterArray['barbara'] = array(52, 10);
foreach($SeqWaterArray as $key => $range) {
$flag = array();
foreach($range as $type => $temperature) {
// here we fill number 1 if the temperature is in range
if ($type == 0) {
$flag['hot'] = (isBetween($temperature, $hotMin, $hotMax) ? 0 : 1);
} else {
$flag['cold'] = (isBetween($temperature, 0, $coldMax) ? 0 : 1);
}
}
$results[$key]['flag'] = $flag;
}
var_dump($results);
?>
This is the result:
["john"]=>
"flag"=>
["hot"]=> 1
["cold"]=> 0
["martin"]=>
"flag" =>
["hot"]=> 1
["cold"]=> 0
["barbara"]=>
"flag" =>
["hot"]=> 0
["cold"]=> 0
I don't think that you need a foreach loop here since you are working with a simple array and apparently you know that the first element is the hot water temperature and the second element is the cold water temperature. I would just do something like this:
$row_WaterTemp['HotMin'] = 50;
$row_WaterTemp['HotMax'] = 66;
$row_WaterTemp['ColdMax'] = 21;
$SeqWaterArray = array(58, 21);
$waterHot = $SeqWaterArray[0];
$waterCold = $SeqWaterArray[1];
$status = 0;
if ($waterHot < $row_WaterTemp['HotMin'] || $waterHot > $row_WaterTemp['HotMax']) {
$status = 1;
}
if ($waterCold > $row_WaterTemp['ColdMax']) {
$status = 1;
}
You can combine the if statements of course. I separated them because of readability.
Note that I removed all quotes from the numbers. Quotes are for strings, not for numbers.
You can use break statement in this case when the flag is set to 1. As per your specification the Cold water should be less than 21, I have modified the code.
<?php
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$row_WaterTemp['ColdMax'] = "21";
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$key = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
break;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val >= $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
break;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
echo $Status;
?>
This way it would be easier to break the loop in case if the temperature fails to fall within the range in either case.
https://eval.in/636912
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am working on a personal project, a bot that plays connect 4. So something is seriously wrong with the recursive function I have written to manage the bots move. No errors are thrown, and any debug info I can be shown does not tell me anything useful. Additionally, I am sure that I have not overflown my stack and that my php.ini file is good to go. This script just runs (consumes a sane amount of memory) and never returns. Only about 2400 function calls should be happening, so this script should return after only a second or two. This has stumped me for days. I believe there is something I have not properly researched. Additonally I should mention that the game board is a simple 2D array to simulate a 7 x 7 board. ai_move_helper is the recursive function and I just cannot figure out why it will not function correctly.
// this class is a code igniter library
class ConnectFour
{
public function __construct()
{
// these are expensive opperations this will give the server enough time
set_time_limit(0);
ini_set('memory_limit', '2048M');
}
public $board_width = 7;
public $board_length = 7;
public $game_array = array();
public $depth_limit = 3;
// this function gets a human made move from a CI controller ($game board)
// and returns the board after the new AI move is applied
public function ai_player_move($game_array, $active_players_move)
{
$this->game_array = $game_array;
$this->game_array = $this->calculate_ai_move($active_players_move);
return $this->game_array;
}
public function calculate_ai_move($active_players_move)
{
$move_weight_array = array();
$prime_game_board = array();
// we hardcast the active player because at this point we know it is the AI
// here we also have to prime the move computer
for($q = 0; $q < $this->board_length; $q++)
{
// MAGIC NUMBERS are the active players!!!
$prime_game_board[] = $this->apply_prime_move($q, 2, $this->game_array);
$move_weight_array[] = $this->ai_move_helper($prime_game_board[$q], 2, 0);
}
//choose your move
for($u = 0; $u < $this->board_length; $u)
{
if($move_weight_array[$u][0] == 1)
{
return $prime_game_board[$u];
}
}
// otherwise return a random acceptable move
$random = rand(0, 6);
return $prime_game_board[$random];
}
public function ai_move_helper($game_board, $active_player, $depth)
{
// build the object that will be needed at this level of recusion
$depth = $depth + 1;
$score_object = new stdClass;
$move_array = array();
$game_boards_generated_at_this_level = array();
$new_game_boards_generated_at_this_level = array();
$return_end_state_detected = 0;
$score_agregate = array();
if($this->depth_limit < $depth)
{
$score_agregate[0] = 0;
$score_agregate[1] = 0;
return $score_agregate;
}
$active_player = ($active_player == 1) ? 2 : 1;
// check for possible moves
for($i=0; $i < $this->board_width; $i++)
{
// calculate all of the possible recusions (all of the next moves)
$game_boards_generated_at_this_level[$i] = $this->apply_ai_move($i, $active_player, $game_board);
// this is the recusive level
$score_agregate = $this->ai_move_helper($game_boards_generated_at_this_level[$i]->game_board, $active_player, $depth);
}
// check to see if there are more moves of if it is time to return
foreach($game_boards_generated_at_this_level as $game_state)
{
//compute the agragate of the scores only for player two (AI)
if($active_player == 2)
{
$score_agregate[0] = $score_agregate[0] + $game_state->score_array[0];
$score_agregate[1] = $score_agregate[1] + $game_state->score_array[1];
}
}
return $score_agregate;
}
public function apply_ai_move($move, $active_players_move, $board_to_use)
{
$board_for_function = array();
$location_of_new_pieces = 0;
$return_object = new stdClass;
// this makes sure that this function is being called with the right board
if(!empty($board_to_use))
{
$board_for_function = $board_to_use;
} else {
$board_for_function = $this->game_array;
}
// check that this move is possible
if(!$this->move_possible($move, $board_for_function))
{
$return_object->game_board = NULL;
$return_object->score_array = NULL;
return $return_object;
}
// this part of the function applies a valid move
foreach($board_for_function[$move] as $column_key => $column_space)
{
// check if you are at the edge of an empty row
if(!array_key_exists(($location_of_new_pieces + 1), $board_for_function[$move]) && $column_space == '_')
{
$board_for_function[$move][$location_of_new_pieces] = ($active_players_move == 1) ? 'x' : 'o';
break;
}
// check if the next place has stuff in it too
if($column_space != '_')
{
// check the edge of the board to make sure that exists
if(array_key_exists(($location_of_new_pieces - 1), $board_for_function))
{
$board_for_function[$move][$location_of_new_pieces - 1] = ($active_players_move == 1) ? 'x' : 'o';
break;
} else {
echo "well fuck...1"; exit;
}
}
$location_of_new_pieces++;
}
$return_object->game_board = $board_for_function;
// now check if this state is a win loss or draw
$test_for_complete = $this->check_for_winner_or_draw($board_for_function, $active_players_move);
// this is a draw
if($test_for_complete == -1)
{
$return_object->score_array = array(0, 1);
} else if($test_for_complete > 3) {
$return_object->score_array = array(1, 0);
} else {
$return_object->score_array = array(0, 0);
}
return $return_object;
}
public function apply_prime_move($move, $active_players_move, $board_to_use)
{
$location_of_new_pieces = 0;
foreach($board_to_use[$move] as $column_key => $column_space)
{
// check if you are at the edge of an empty row
if(!array_key_exists(($location_of_new_pieces + 1), $board_to_use[$move]) && $column_space == '_')
{
$board_to_use[$move][$location_of_new_pieces] = ($active_players_move == 1) ? 'x' : 'o';
break;
}
// check if the next place has stuff in it too
if($column_space != '_')
{
// check the edge of the board to make sure that exists
if(array_key_exists(($location_of_new_pieces - 1), $board_to_use))
{
$board_to_use[$move][$location_of_new_pieces - 1] = ($active_players_move == 1) ? 'x' : 'o';
break;
} else {
echo "well fuck...1"; exit;
}
}
$location_of_new_pieces++;
}
return $board_to_use;
}
public function move_possible($move, $game_board)
{
// check that this move is not going to fall out of the board
if($game_board[$move][0] != "_")
{
return FALSE;
} else {
return TRUE;
}
}
public function check_for_winner_or_draw($game_array, $active_player_move)
{
$present_possible_winner = "";
$count_to_win = 0;
$game_not_a_draw = FALSE;
for($i = 0; $i < $this->board_length; $i++)
{
for($j = 0; $j < $this->board_width; $j++)
{
// start checking for a winner
if($game_array[$i][$j] != "_")
{
$present_possible_winner = $game_array[$i][$j];
// check for a winner horizontally
for($x = 0; $x < 4; $x++)
{
if($j+$x < $this->board_width)
{
if($game_array[$i][$j+$x] == $present_possible_winner)
{
$count_to_win = $count_to_win + 1;
}
}
}
if($count_to_win > 3)
{
return $present_possible_winner; // this player has won
} else {
$count_to_win = 0;
}
// check for a winner horizontally
for($y = 0; $y < 4; $y++)
{
if($i+$y < $this->board_width)
{
if($game_array[$i+$y][$j] == $present_possible_winner)
{
$count_to_win = $count_to_win + 1;
}
}
}
if($count_to_win > 3)
{
return $present_possible_winner; // this player has won
} else {
$count_to_win = 0;
}
// check for a winner up to down diagonal
for($z = 0; $z < 4; $z++)
{
if(($i+$z < $this->board_width) && ($j+$z < $this->board_length))
{
if($game_array[$i+$z][$j+$z] == $present_possible_winner)
{
$count_to_win = $count_to_win + 1;
}
}
}
if($count_to_win > 3)
{
return $present_possible_winner; // this player has won
} else {
$count_to_win = 0;
}
// check for a winner down to up diagonal
for($w = 0; $w < 4; $w++)
{
if(($i+$w < $this->board_width) && ($j-$w >= 0))
{
if($game_array[$i+$w][$j-$w] == $present_possible_winner)
{
$count_to_win = $count_to_win + 1;
}
}
}
if($count_to_win > 3)
{
return $present_possible_winner; // this player has won
} else {
$count_to_win = 0;
}
}
}
}
// check for a drawed game and return accordingly
for($i = 0; $i < $this->board_length; $i++)
{
for($j = 0; $j < $this->board_width; $j++)
{
if($game_array[$i][$j] == "_")
{
$game_not_a_draw = TRUE;
}
}
}
if(!$game_not_a_draw)
{
return -1;
}
return 0;
}
// this is a private debugging function that I wrote for this script
public function debug($value = NULL, $name = NULL, $exit = NULL)
{
if(!empty($name))
{
echo $name . "<br />";
}
echo "<pre>";
var_dump($value);
echo "</pre>";
if($exit)
{
exit;
}
}
}
Well I found it: The calculate ai move had an infinite loop in it...
//choose your move
for($u = 0; $u < $this->board_length; $u)
{
if($move_weight_array[$u][0] == 1)
{
return $prime_game_board[$u];
}
}
Should be
//choose your move
for($u = 0; $u < $this->board_length; $u++)
{
if($move_weight_array[$u][0] == 1)
{
return $prime_game_board[$u];
}
}
Back to work for me...