I recently took a coding test for a promotion at work. This was one of the tasks I really struggled with and was wondering what is the best way to do this. I used a load of
Hmmm..... I guess it's really simple if you break it into simpler problems: eg find all valid hours (00-23), for each of these valid hours use the remaining numbers to find valid minutes (00-59), combine and sort. In pseudo code something like the following
valid_times = []
function get_max(digits[]) {
for each d1 in digits[]
for each d2 in (digits[] except d1)
res = is_valid_hour(d1, d2)
if(res > 0) {
if(res == 2)
swap(d1, d2)
d3 = one of the rest in (digits except d1 and d2)
d4 = digit left in digits[]
res = is_valid_minute(d3, d4)
if(res > 0)
if(res == 2)
swap(d3, d4)
add (d1, d2, d3, d4) to valid_times;
}
sort(valid_times)
print valid_times[0]
}
function is_valid_hour(a, b) {
if (a*10+b<24)
return 1
if (b*10+a<24)
return 2
return 0;
}
function is_valid_minute(a, b) {
if (a*10+b<60)
return 1
if (b*10+a<60)
return 2
return 0;
}