我有javascript日期对象的有序数组,数组总有14项的长度。在伪:
I have a sorted array of Javascript date objects, the array always has a length of 14 entries. In pseudo:
dates
["label1"] = date object 1,
["label2"] = date object 2,
...
["label14"] = date object 14
虽然他们是在有序地按日期,日期不是均匀分布的。例如,条目1和2之间可以是1小时,而条目5和6之间是几分钟或几小时。
Although they are in sorted order by date, the dates are not distributed evenly. For example, between entry 1 and 2 may be 1 hour, whilst between entry 5 and 6 are a few minutes, or a few hours.
我的挑战是找到一种算法,对于任何给定的输入日期,会发现此数组如下:
My challenge is to find an algorithm that for any given input date, will find the following from this array:
的previous日期的数组中的位置 下一个日期的数组中的位置 在我们输入的日期将落在上面的日期之间,我想知道2点之间的时间的百分比。例如,正好在日期间将返回50%。我不喜欢问请$ C C此$我的问题,但我真的没有好书面高效alghorithms并找到现有alghorithm是不成功的。
I don't like asking "please code this for me" questions but I'm really no good in writing efficient alghorithms and have been unsuccesful in finding an existing alghorithm.
推荐答案
由于数组进行排序,则previous日期是在阵列在previous位置,同时下一个日期是在下一位置阵列
Since the array is sorted, the previous date is at the previous position in the array while the next date is at the next position in the array.
要确定的百分比,你可以简单地用下面的公式:
To determine the percentage, you can simply use the following formula:
var percentage = (date - prev) / (next - prev);
这将导致一个介于0和1,因此,如果需要在0和100%,简单地乘以100
That will result in a number between 0 and 1, so if you need between 0 and 100%, simply multiply by 100.
例如:
var dates = [];
for (var i=0; i<14; i++) { dates.push(new Date(1392119656126 + i*i*10000000)) }
for (var i = 1; i<dates.length-1; i++) {
var percentage = ((dates[i]-dates[i-1])/(dates[i+1]-dates[i-1])) * 100;
console.log('P', dates[i-1], 'C', dates[i], 'N', dates[i+1], 'PERC', percentage);
}
相关推荐
最新文章