This should be pretty easy to do. Consider DayOfWeek.Sunday == 0 , Monday == 1 , etc.
Your mask matches that. That is, in your mask:
Sunday = 1 << 0 Monday = 1 << 1 Tuesday = 1 << 2
Now, given the day of the week, we can easily determine the day that will meet your criteria:
[Flags] enum DayMask { Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64 } static DayOfWeek FindNextDay(DayMask mask, DayOfWeek currentDay) { DayOfWeek bestDay = currentDay; int bmask = 1; for (int checkDay = 0; checkDay < 7; ++checkDay) { if (((int)mask & bmask) != 0) { if (checkDay >= (int)currentDay) { bestDay = (DayOfWeek)checkDay; break; } else if (bestDay == currentDay) { bestDay = (DayOfWeek)checkDay; } } bmask <<= 1; } return bestDay; }
For example, the day you want to combine is Wednesday, but the mask contains only Monday. You can see that the algorithm will select Monday as the best day, and then go through the remaining days without selecting anything.
If the mask contains Monday, Tuesday, and Thursday, the algorithm will select Monday as the best candidate, ignore Tuesday, and then select Thursday as the best candidate and exit.
It won't be as fast as the lookup table, but it should be damned quickly. And it will use a lot less memory than the lookup table.
The lookup table will be much faster, and it will not take up only a kilobyte of memory. And given the FindNextDay method above, it's easy enough to build:
static byte[,] LookupTable = new byte[128, 7]; static void BuildLookupTable() { for (int i = 0; i < 128; ++i) { DayMask mask = (DayMask)i; for (int day = 0; day < 7; ++day) { LookupTable[i, day] = (byte)FindNextDay(mask, (DayOfWeek)day); } } }
Now, to get the next day for any combination of mask and current day:
DayOfWeek nextDay = (DayOfWeek)LookupTable[(int)mask, (int)currentDay];
This is undoubtedly a quick way to generate a table. But it is fast enough and, since it will be executed once when the program starts, there is no point in optimizing it. If you want the launch to be faster, write a small program that displays the table as C # code. Something like:
Console.WriteLine("static byte[,] LookupTable = new byte[128,7] {"); for (int i = 0; i < 128; ++i) { Console.Write(" {"); for (int j = 0; j < 7; ++j) { if (j > 0) { Console.Write(","); } Console.Write(" {0}", LookupTable[i, j]); } Console.WriteLine(" },"); } Console.WriteLine("};");
Then you can copy and paste it into your program.