Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

You have an array of working time period pairs (from, till) received from user input and written according 24-hour clock format convention. You have to merge these periods if the intersect each other.

For example, if you have (10, 12), (11, 13), (12, 14) you should merge them into (10,14). Also (23, 0) and (0, 1) should be merged into (23, 1).

UPDATE:

@dmckee Let assume that the set of pairs like (10:00, 12:00) is the valid input.

@dude We don't consider Sundays and holidays so all merges should be performed for the common twenty-four hours range.

@steven-rumbalski The result of (0,8), (8,16), (16,0) may be any (x,x) pair, for example, (00:00,00:00).

Example 1

Input

(09:00,12:00),(11:00,13:00),(17:00,19:00)

Output

(09:00,13:00),(17:00,19:00)

Example 2

Input

(00:00,08:00),(08:00,16:00),(16:00,00:00)

Output

(00:00)
share|improve this question
3  
Is (10,12) a valid input, or should it be (10:00, 12:00) or something similar? Likewise, what is the correct format for the output? Also each challenge should specify what the metric is (i.e. we don't only do [code-golf] or even default to it). –  dmckee Jan 11 '13 at 15:20
1  
Because one work shift can spill over from one day into the next [as (23,0)+(0,1) =(23,1) appears to show], shouldn't we be keeping track of the days in the workweek also? If Sunday is not a work day, it would seem that (23,1), starting Sunday Evening and going to 1 am Monday, would not count. However, from Monday to Tuesday, it would be counted. –  David Carraher Jan 11 '13 at 16:32
3  
What should the result of (0,8), (8,16), (16,0) be? –  Steven Rumbalski Jan 11 '13 at 16:41
1  
In the future, maybe post your spec to the sandbox on meta first to get feedback before you post. This could have been a great question with a little more work. –  Tim Seguine Feb 24 at 22:20
    
@TimSeguine thank you for your suggestion, I did not know about this opportunity! –  user533039 Feb 25 at 10:27
add comment

1 Answer

Python (198 chars)

r=[]
p=r.append
l=r+sorted(a<b and (a,b)or p((0,b))or(a,24)for a,b in input())
r[:]=[]
a,b=l[0]
for c,d in l[1:]:
 if c>b:p((a,b));a,b=c,d
 elif b<d:b=d
if b>23:b=a and r.pop(0)[1]
p((a,b))
print r

Example:

> python merge.py
(10, 12), (11, 13), (12, 14)
[(10, 14)]
> python merge.py
(23,0),(0,1)
[(23, 1)]
> python merge.py
(0,8), (8,16), (16,0)
[(0, 0)]
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.