Monday, August 30, 2010

Minimum diff between dates of a week

Problem statement:
The UI contains a set of checkboxes. Each signifies a day. The list starts from a Sunday and goes upto a Saturday. The task is to find out the minimum difference between the selected days.

Eg:
If Mon, Thur and Fri were selected, then the minimum days between the selected days would be 1 (Thu and Fri).

Take into consideration that if Sun and Sat were selected, the difference would be 1. :)

5 comments:

Arun Raghavendar said...

How about this one?

Assign a number for each like below

Sun Mon Tue Wed Thu Fri Sat
3 2 1 0 1 2 3

Let X and Y be the two days clicked

Now do a

Min( (X+Y), (7-(X+Y)) );

Does it cover all ur edge cases?

Arun Raghavendar said...

To be more simple,

Assign numbers 0 - 6 for Sun - Sat

Assume X and Y are the days selected

Now do

Min( (Y-X), (7-Y+X));

dineshvasudevan said...

What about the iteration technique ? 2 for loops or one ?

Rajeesh said...
This comment has been removed by the author.
Rajeesh said...

"""
diff = 7
for x in selected_days[]:
for y in selected_days[1:]:
diff = min(diff, min(y-x, 7-y+x))
"""
How can we do that in a single loop? Well, my solution looks more like the sorting problems of school-days! ;)