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
Really late for the party, but I think there a quite straightforward solution to the problem (slower and uglier than other solutions, though). Just iterate (no hardcoding, no permutations) through all integer values from 2359 to 0 and check if they contain provided digits:
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
getHHMM = (val) => `${Math.floor(val / 100).pad(2)}:${(val % 100).pad(2)}`;
isValidDate = value => !isNaN(new Date(`1970-01-01T${getHHMM(value)}`).getTime());
isFit = function(a, b, c, d, value) {
var valStr = value.pad(4).split("").sort().join("");
var digStr = [a, b, c, d].sort().join("");
return valStr === digStr;
}
generate = function(a, b, c, d) {
for (var i = 2359; i >= 0; i--) {
if (isFit(a, b, c, d, i) && isValidDate(i))
return getHHMM(i);
}
return "NOT POSSIBLE";
}