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
I could do with tons of ifs and elses but i am pretty sure that's already been done. Instead i go with a different way.
function getMaxTime(...a){
function perm(a){
var r = [[a[0]]],
t = [],
s = [];
if (a.length <= 1) return a;
for (var i = 1, la = a.length; i < la; i++){
for (var j = 0, lr = r.length; j < lr; j++){
r[j].push(a[i]);
t.push(r[j]);
for(var k = 1, lrj = r[j].length; k < lrj; k++){
for (var l = 0; l < lrj; l++) s[l] = r[j][(k+l)%lrj];
t[t.length] = s;
s = [];
}
}
r = t;
t = [];
}
return r;
}
function isValidTime(a){
return 10*a[0]+a[1] < 24 && 10*a[2]+a[3] < 60;
}
var time = perm(a).filter(t => isValidTime(t)) // filter out the invalids
.map(t => t.reduce((p,c) => 10*p+c)) // convert them into 4 digit integer
.reduce((p,c) => p > c ? p : c, -1); // get the biggest
return time >= 0 ? ("0" + ~~(time/100)).slice(-2) + ":" + time%100 : "No way..!";
}
console.log(getMaxTime(6, 5, 2, 0));
console.log(getMaxTime(3, 9, 5, 0));
console.log(getMaxTime(7, 6, 3, 8));