Find maximum possible time HH:MM by permuting four given digits

前端 未结 23 2090
执念已碎
执念已碎 2020-11-30 02:44

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

23条回答
  •  庸人自扰
    2020-11-30 02:56

    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.

    • We get all permutations of the given 4 numbers. Here i use my rotationPerm algorithm. I guess it is one of the fastest ever in JS.
    • Filter out the invalid times
    • Chose the biggest from the remaining values
    • Format as time.

    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));

提交回复
热议问题