The Setup
I have an array of rain probability that I'm outputting as a forecast:
$rain_probability = array(
'7am' => '33',
'8am' => '0',
'9am' => '8',
'10am' => '7',
'11am' => '8',
'12pm' => '19',
'1pm' => '8',
'2pm' => '13',
'3pm' => '50',
'4pm' => '50',
'5pm' => '60',
'6pm' => '60',
'7pm' => '7',
'8pm' => '5',
'9pm' => '0'
);
$forecast = 'The likelihood of rain is: ';
foreach( $rain_probability as $hour => $percentage )
{
$forecast .= "$hour: $percentage%. \n";
}
echo $forecast;
The Results
The likelihood of rain is:
7am 33%.
8am 0%.
9am 8%.
10am 7%.
11am 8%.
12pm 19%.
1pm 8%.
2pm 13%.
3pm 50%.
4pm 50%.
5pm 60%.
6pm 60%.
7pm 7%.
8pm 5%.
9pm 0%.
Desired Results
I'd like this to be more human-friendly, like this:
The likelihood of rain is:
7am: 33%.
8am-11am: less than 10%.
12pm: 19%.
1pm: 8%.
2pm: 13%.
3pm-4pm: 50%.
5pm-6pm: 60%.
7pm-9pm: less than 10%.
What I Tried
Thought this would be pretty simple, so I began writing a loop that would check to see if the probability for the previous hour was the same as the current hour. Then needed to special case for numbers less than 10%. Then had to special case the first and last array elements. Pretty soon I was in the midst of a lot of conditional statements and (excuse the pun) the code was not very dry anymore. And wasn't sure there wouldn't be bugs with certain combinations or sequences of probabilities, and could setup tests for that. But overall started feeling like I may be reinventing the wheel and that maybe there was a better approach.
The Question
My question is not "how can I make this work" - but rather does there exist a classical approach, pattern, or even a class or library for solving this problem? ( Sort of feels like a computer science homework assignment )
Aucun commentaire:
Enregistrer un commentaire