简体   繁体   中英

Find the shortest difference between two times, in an array

I have following strArr array

["1:10pm", "4:40am", "5:00pm"]

Now I'm trying to find the shortest time difference between in minutes of the above time list.

here in above array, it should out put me 230.

All the times are in twelve-hour format. (HH:MM (am/pm))

function TimeDifference(strArr) { 

  // code goes here  
  return strArr; 

}
   
// keep this function call here 
console.log(TimeDifference(readline()));

Well, since you need the result in minutes, first I'd convert all the values to minutes:

strArr.map((time) => /(\d{1,2}):(\d{1,2})(am|pm)/.exec(time).slice(1))
      .map(([hour, min, midday]) =>
        (Number(hour) + (midday === `pm` ? 12 : 0)) * 60 + Number(min))

Then I'd sort it all from the smallest to the largest, so that we can compare n(i) with n(i + 1):

      .sort((a, b) => (a > b ? 1 : a < b ? -1 : 0))

After we sorted our times in minutes we need to find the difference. That's an interesting part, because we also need to consider the difference between times that pass the whole 24 hours, eg 11:59pm - 0:01am should return 2 minutes. If we go for a simple substracting of n(i + 1) - n(i) now, we would get a wrong result in such cases. Here's my solution (though I think there are better ones):

const WHOLEDAY = 60 * 24;

const findDifference = (a, b) => {
  let diff = 0;
  while (a != b) {
    a = (a + 1) % WHOLEDAY;
    diff += 1;
  }
  return diff;
};

strArr.map((v, i, arr) => findDifference(v, arr[(i + 1) % arr.length]));

So that we don't lose the difference between the latest time and the earliest (next day), we need to compare the last value with the first one.

And then all we need to do is just reduce it to the smallest difference:

strArr.reduce((a, b) => (a < b ? a : b));

Here you go. I didn't care for the cases when the input is wrong though.

const arr1 = ["1:10pm", "4:40am", "5:00pm"];
const arr2 = ["11:50pm", "0:30am"];
const arr3 = ["4:23am", "4:25am", "4:26am", "4:28am"];
const arr4 = ["0:00am"];

const WHOLEDAY = 60 * 24;

const findDifference = (a, b) => {
  let diff = 0;
  while (a != b) {
    a = (a + 1) % WHOLEDAY;
    diff += 1;
  }
  return diff;
};

const timeDifference = (strArr) =>
  strArr
    .map((time) => /(\d{1,2}):(\d{1,2})(am|pm)/.exec(time).slice(1))
    .map(([hour, min, midday]) =>
      (Number(hour) + (midday === `pm` ? 12 : 0)) * 60 + Number(min))
    .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
    .map((v, i, arr) => findDifference(v, arr[(i + 1) % arr.length]))
    .reduce((a, b) => (a < b ? a : b));

console.log(timeDifference(arr1)); // 230
console.log(timeDifference(arr2)); // 40
console.log(timeDifference(arr3)); // 1
console.log(timeDifference(arr4)); // 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM