## Television Time

### March 20, 2018

I like this problem because it’s a good way to show off the Standard Prelude; the problem is easy to solve because all the hard work has already been done:

(define (tv-time xs) (length (unique = (sort < (mappend (lambda (x) (range (car x) (cadr x))) xs)))))

`Range`

builds a list of times at which the television is on during a single interval, then `mappend`

(which is like `map`

but builds the output list using `append`

instead of `cons`

) builds a list of all the times the television is on during all the intervals, with some times repeated. `Sort`

brings like times together, `unique`

discards duplicate times, and `length`

counts the times. Here are some examples:

> (tv-time '((1 4) (2 3))) ; 1, 2, 3 3 > (tv-time '((4 6) (1 2))) ; 1, 4, 5 3 > (tv-time '((1 4) (6 8) (2 4) (7 9) (10 15))) ; 1, 2, 3, 6, 7, 8, 10, 11, 12, 13, 14 11

You can run the program at https://ideone.com/P1q7Vv.

intervals_list = [(1, 4), (6, 8), (2, 4), (7, 9)]

on_times = set()

for start, end in intervals_list:

for time in range(start, end):

on_times.add(time)

print list(on_times)

A Haskell version.

Here is a solution in standard Scheme. with time- and

space-complexity linear in the size of the input. (I believe the

other solutions, so far, require space and time that are exponential

in the size of the input.)

Here’s an alternate version in Haskell, which (like chaw’s) just prints the total time spanned by the intervals.

MUMPS language

LAB>W $$TIMES^XJSG(“1 4,6 8,2 4,7 9”)

6

@Mithran: I always like to see short solutions. Language?

Here’s a solution in C.

Output:

@steve, Mithran’s answer looks like Python that had the leading whitespace eaten.

Here’s a Python answer in a functional style:

Thanks, Mike!

Klong language

[1 2 3 6 7 8]

6

“end”

[1 2 3 6 7 8 11 12 13 14 15 16 17 18 19]

15

“end”

Klong language – Commented version

steve@steve-VirtualBox:~/klong$ ./kg

Klong 20180213

]l tv-time.kg

loading “./tv-time.kg”

fh([[1 4] [6 8] [2 4] [7 9]])

[1 2 3 6 7 8]

6

“end”

fh([[1 4] [10 15] [6 8] [2 4] [7 9]])

[1 2 3 6 7 8 10 11 12 13 14]

11

“end”