One of my colleagues is working on a report that shows the weekly (Sunday to Saturday) promotion of each employee in our small consulting firm. A code snippet is written there that shows the columns corresponding to the days in the target week. Its algorithm is as follows:
- Get that day of the week on the first day of the month. If it is Sunday, set the flag to zero; otherwise, set it to one.
- Iterates through all days of the month. If it's Sunday, increase the flag. Then, if the flag value is equal to the week to be displayed, show the column corresponding to the current day; otherwise hide the column.
Of course, the flag indicates what the current week is.
I suggested another algorithm:
- Indicate which days of the month are the first (F) and last (L) days of the specified week. For example, the first week of October 2009 starts on Tuesday 1st and ends on Saturday 3rd.
- Iterate through the columns corresponding to the days of the 1st level F-1, and hide them.
- Go through the columns corresponding to the days F in L, and show them.
- Iterate through the columns corresponding to days L + 1 on DaysOfMonth and hide them.
The "difficult" part of my algorithm is part 1. I mean the "difficult" as "hard to understand" because the algorithmic complexity of its execution is constant. And my algorithm has the advantage of having a denser loop. My peer loop makes a comparison for each day of the month. Mine does not.
, , . , .
:
if (condition)
{
flag++;
if (flag > test)
doSomething();
}
else
if (flag >= test)
doSomething();
, , :
if (flag >= test);
doSomething();
if (condition)
flag++;
?!?!?!
EDIT: .