Reputation: 121
I gotta do some homework about creating a farm. And i have to describe each events within the hours and the days (from 6 A.M to 22 P.M, from Monday to Saturday ). I'm trying to use a switch based on a enum like this :
// this is the hour's enum (day and night).
[Flags]
enum Horaire
{
Journee = 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 18 | 19 | 20 | 21,
Nuit = 22 | 23 | 0 | 1 | 2 | 3 | 4 | 5,
}
In my program.cs, i would like to do a while loop such as :
While(Journee!=Nuit)
switch(Journee)
case 6: // for 6.am
Farmer.DoAction();
case 12 : // for 12.pm
Farmer.Eat();
and so on until it will reach the night.
Is there an easier way to do this loop without an enum and a switch ?
Thank you.
Upvotes: 2
Views: 130
Reputation: 8194
You can step through each day and hour of the farmers working week with two simple loops:
// Outer loop counts the day, 1 being Monday and 6 being Saturday
for (int day = 1; day <= 6; day++)
{
// The Inner loop counts working hours from 6AM to 22PM.
for (int hour = 6; hour <= 22; hour++)
{
// Now you can inspect 'day' and 'hour' to see where you are and take action
}
}
For example he must eat his dinner every day so you can have a case like this:
if (hour == 12)
{
Farmer.Eat();
}
He might only plow the fields on a Wednesday at 10AM and not any other day:
if (day == 3 && hour == 10)
{
Farmer.PlowFields();
}
You may want to put the switches into a method like so:
public void DoWork(Farmer farmer, int day, int hour)
{
if (hour == 6)
farmer.WakeUp();
if (day == 3 && hour == 10)
farmer.PlowFields();
}
Then the inside of your inner loop just becomes:
DoWork(farmer, day, hour);
Upvotes: 0
Reputation: 37000
You can simply create a Dictionary<int, Action>
that holds your hours as keys and the action to execute in the value:
var dayMap = new Dictionary<int, Action>
{
{ 6, farmer.DoAction },
{ 12, farmer.Eat },
{ 22, farmer.Sleep }
};
Than simply execute the delegate by providing the current hour:
dict[6]();
So you won´t even care on if it is day or night, just pass the current time and you´re gone.
When you also want to consider the weekdays you´ll need a nested dictionary:
var weekMap = new Dictionary<string, Dictionary<int, Action>>
{
{ "Monday", new Dictionary<int, Action> { ... }}
};
Call it like this:
weekMap["Monday"][6]()
to execute farmer.DoAction
.
Upvotes: 3