在数组中,如何找到给定浮点值的最近键?

时间:2021-12-12 21:32:30

I'm making an "acceleration" array like this:

我做了一个像这样的“加速度”数组:

acc["0100"] = 1;
acc["0300"] = 2;
acc["0600"] = 4;
acc["0900"] = 8;
acc["2000"] = 16;
acc["5000"] = 32;

And, when the user presses a key, I start a timer: this._startTick = (new Date()).getTime();

当用户按下一个键时,我启动一个计时器:this。_startTick =(新日期()).getTime();

Now I have a timer that checks if the key is still pressed. If so, then I do something like:

现在我有一个计时器,可以检查键是否仍然按下。如果是的话,那么我做一些事情:

this._delay = (new Date()).getTime() - this._startTick;

And now, based on this._delay, I'd like to find one of the previous values (1, 2, 4 or 8). How would you do that?

现在,基于这个。_delay,我想找一个之前的值(1、2、4或8)你怎么做?

NB: if the value is greater than "5.0" then the result should always be 32.

NB:如果值大于“5.0”,那么结果应该是32。

NOTA: my goal is, given an elapsed time, find out which value is the best. I started the way I've just explained, but if you have another solution, I'll take it!

我的目标是,给定一段时间,找出哪个值是最好的。我按照刚才解释的方式开始,但是如果你有其他的解决办法,我就接受它!

6 个解决方案

#1


2  

It's easier to operate on an array than on an object:

在数组中操作比在对象上操作更容易:

var accArr = [];
for (time in acc) {
    accArr.push({time: time, value: acc[time]});
}

Assuming you have an array, you can do:

假设你有一个数组,你可以这样做:

function getValue(delay) {
    var diffs = accArr.map(function (e) { return Math.abs(e.time - delay); });
    return accArr[diffs.indexOf(Math.min.apply(null, diffs))].value;
}

EDIT:

编辑:

Well, you didn't mention that this is a performance-critical function. In that case, I would recommend picking a granularity (e.g. 0.05, so the multiplier for delay is 20) and pre-calculating all values from 0 to MAX_DELAY:

你没有提到这是一个性能关键的函数。在这种情况下,我建议选择一个粒度(例如0.05,因此延迟的乘数为20),并预先计算从0到MAX_DELAY的所有值:

var multiplier = 20,
    granularity = 1 / multiplier;

var delayValues = (function () {
    var result = [];
    for (var delay = 0; delay <= MAX_DELAY; delay += granularity) {
        result.push(getValue(delay));
    }
    return result;
})();

During the animation, fetching the value will be a simple lookup in a relatively small table:

在动画中,获取值将是在一个相对较小的表中进行简单的查找:

function getValueFast(delay) {
    return (delayValues[Math.round(delay * multiplier)] || 
            delayValues[delayValues.length - 1])
}

JSPerf comparison between this solution and simple if statements shows they perform equally fast for searching around a middle value.

JSPerf对该解决方案和简单if语句的比较表明,在搜索中间值时,它们的执行速度同样快。

#2


2  

Here is the jsfiddle test page.

这是js小提琴测试页面。

var getAccForDelay = (function () {
    var acc = {
        0.1: 1,
        0.3: 2,
        0.6: 4,
        0.9: 8,
        2.0: 16,
        5.0: 32
    };

    return function(delay) {
        var key,
            bestKey = undefined,
            absDiff, 
            absDiffMin = Number.MAX_VALUE;

        for (key in acc) {
            if (acc.hasOwnProperty(key)) {
                absDiff = Math.abs(delay - key);
                if (absDiffMin > absDiff) {
                    absDiffMin = absDiff;
                    bestKey = key;
                }
            }
        } 
        return bestKey === undefined ? undefined : acc[bestKey];
    };
}());

Test:

测试:

console.clear();
console.log(getAccForDelay(0));
console.log(getAccForDelay(0.33));
console.log(getAccForDelay(3.14));
console.log(getAccForDelay(123456.789));

Output:

输出:

1
2
16
32

=== UPDATE ===

= = = = = =更新

The above solution doesn't utilize of the fact that acc is sorted by key. I optimized the code by replacing linear search with binary search, which is much faster on long arrays. Here is the test page.

上面的解决方案没有利用acc按键排序的事实。我对代码进行了优化,将线性搜索替换为二进制搜索,这在长数组中要快得多。这是测试页面。

var getAccForDelay = (function () {
    var accKey   = [ 0.1, 0.3, 0.6, 0.9, 2.0, 5.0 ],
        accValue = [   1,   2,   4,   8,  16,  32 ],
        accLength = accKey.length;

    return function(delay) {
        var iLeft, iMiddle, iRight;

        iLeft = 0;
        if (delay <= accKey[iLeft])
            return accValue[iLeft];
        iRight = accLength - 1;
        if (accKey[iRight] <= delay)
            return accValue[iRight];        
        while (true) {
            if (iRight - iLeft === 1)
                return delay - accKey[iLeft] < accKey[iRight] - delay ? accValue[iLeft] : accValue[iRight];
            iMiddle = ~~((iLeft + iRight) / 2);
            if (delay < accKey[iMiddle])
                iRight = iMiddle;
            else if (accKey[iMiddle] < delay)
                iLeft = iMiddle;
            else
                return accValue[iMiddle];
        }
    };
}());

#3


1  

In my humble opinion I think the best solution to this problem is to write a function which picks the best acceleration based on the time using if statements as follows:

在我的拙见下,我认为这个问题的最佳解决方案是编写一个根据时间选择最佳加速度的函数,使用if语句如下:

function getAcceleration(time) {
    if (time < 0.20) return 1;
    if (time < 0.45) return 2;
    if (time < 0.75) return 4;
    if (time < 1.45) return 8;
    if (time < 3.50) return 16;
    return 32;
}

However this is a static solution. If that's alright with you then I recommend you use this method. On the other hand if you need a dynamic solution then use this instead:

然而,这是一个静态的解决方案。如果你觉得可以的话,我建议你使用这个方法。另一方面,如果你需要一个动态的解决方案,可以使用以下方法:

var getAcceleration = createAccelerationMap(0.1, 0.3, 0.6, 0.9, 2.0, 5.0);

function createAccelerationMap(previous) {
    var length = arguments.length, limits = [];

    for (var i = 1; i < length;) {
        var current = arguments[i++];
        limits.push((previous + current) / 2);
        previous = current;
    }

    return function (time) {
        var length = limits.length, acceleration = 1;

        for (var i = 0; i < length;) {
            if (time < limits[i++]) return acceleration;
            acceleration *= 2;
        }

        return acceleration;
    };
}

Either way you may then use getAcceleration as follows:

无论哪种方式,您都可以使用get加速度,如下所示:

console.log(getAcceleration(0));          // 1
console.log(getAcceleration(0.33));       // 2
console.log(getAcceleration(0.64));       // 4
console.log(getAcceleration(1.42));       // 8
console.log(getAcceleration(3.14));       // 16
console.log(getAcceleration(123456.789)); // 32

See the demo: http://jsfiddle.net/QepT7/

看到演示:http://jsfiddle.net/QepT7/

#4


0  

If the 0.1 is the number of seconds, and you want to round to 1 decimal you can do something this:

如果0。1是秒数,你想四舍五入到1小数你可以这样做:

// 0.42332 * 10 = 4.2332 
// Math.round( ) will be 4
// 4 / 10 = 0.4
acc[ (Math.round(this._delay * 10) / 10).toString() ]

#5


0  

var seconds = this._delay.toString().substring(0,2)

console.log(acc[seconds]);

This is a straight-forward approach of your problem: First I convert the float to a string, second I cut off everything after the third character.

这是您的问题的一种直接处理方法:首先我将浮点数转换为字符串,其次我在第三个字符之后删除所有内容。

#6


0  

What units are you using?

你用的是什么单位?

this._startTick = (new Date()).getTime();
//       ms     =                 ms

this._delay = (new Date()).getTime() - this._startTick;
//     ms   =                 ms     -       ms

So to get to "0.1"/etc from milliseconds I'm assuming you are doing

从毫秒到0。1,等等,我假设你在做

(Math.floor(ms / 100) / 10).toString();

Why not just keep everything in ms/100 so you can use integers?

为什么不把所有东西都保存在ms/100中,以便使用整数呢?

var acc = [];
acc[ 1] =  1;
acc[ 3] =  2;
acc[ 6] =  4;
acc[ 9] =  8;
acc[20] = 16;
acc[50] = 32;

Then you can create a "nearest" lookup function like this

然后您可以创建这样的“最近的”查找函数

function find(x) {
    var i = 0;
    x = x | 0; // The | 0 will cause a cast to int
    if (x < 0) x = 0;
    if (acc[x] !== undefined) return acc[x];
    if (x > acc.length) return acc[acc.length - 1];
    while (++i < acc.length) {
        if (acc[x - i] !== undefined) return acc[x - i];
        if (acc[x + i] !== undefined) return acc[x + i];
    }
}
find(this._delay / 100);

Now examples are

现在的例子

find(30);    // 16
find(100.5); // 32
find(0);     //  1

#1


2  

It's easier to operate on an array than on an object:

在数组中操作比在对象上操作更容易:

var accArr = [];
for (time in acc) {
    accArr.push({time: time, value: acc[time]});
}

Assuming you have an array, you can do:

假设你有一个数组,你可以这样做:

function getValue(delay) {
    var diffs = accArr.map(function (e) { return Math.abs(e.time - delay); });
    return accArr[diffs.indexOf(Math.min.apply(null, diffs))].value;
}

EDIT:

编辑:

Well, you didn't mention that this is a performance-critical function. In that case, I would recommend picking a granularity (e.g. 0.05, so the multiplier for delay is 20) and pre-calculating all values from 0 to MAX_DELAY:

你没有提到这是一个性能关键的函数。在这种情况下,我建议选择一个粒度(例如0.05,因此延迟的乘数为20),并预先计算从0到MAX_DELAY的所有值:

var multiplier = 20,
    granularity = 1 / multiplier;

var delayValues = (function () {
    var result = [];
    for (var delay = 0; delay <= MAX_DELAY; delay += granularity) {
        result.push(getValue(delay));
    }
    return result;
})();

During the animation, fetching the value will be a simple lookup in a relatively small table:

在动画中,获取值将是在一个相对较小的表中进行简单的查找:

function getValueFast(delay) {
    return (delayValues[Math.round(delay * multiplier)] || 
            delayValues[delayValues.length - 1])
}

JSPerf comparison between this solution and simple if statements shows they perform equally fast for searching around a middle value.

JSPerf对该解决方案和简单if语句的比较表明,在搜索中间值时,它们的执行速度同样快。

#2


2  

Here is the jsfiddle test page.

这是js小提琴测试页面。

var getAccForDelay = (function () {
    var acc = {
        0.1: 1,
        0.3: 2,
        0.6: 4,
        0.9: 8,
        2.0: 16,
        5.0: 32
    };

    return function(delay) {
        var key,
            bestKey = undefined,
            absDiff, 
            absDiffMin = Number.MAX_VALUE;

        for (key in acc) {
            if (acc.hasOwnProperty(key)) {
                absDiff = Math.abs(delay - key);
                if (absDiffMin > absDiff) {
                    absDiffMin = absDiff;
                    bestKey = key;
                }
            }
        } 
        return bestKey === undefined ? undefined : acc[bestKey];
    };
}());

Test:

测试:

console.clear();
console.log(getAccForDelay(0));
console.log(getAccForDelay(0.33));
console.log(getAccForDelay(3.14));
console.log(getAccForDelay(123456.789));

Output:

输出:

1
2
16
32

=== UPDATE ===

= = = = = =更新

The above solution doesn't utilize of the fact that acc is sorted by key. I optimized the code by replacing linear search with binary search, which is much faster on long arrays. Here is the test page.

上面的解决方案没有利用acc按键排序的事实。我对代码进行了优化,将线性搜索替换为二进制搜索,这在长数组中要快得多。这是测试页面。

var getAccForDelay = (function () {
    var accKey   = [ 0.1, 0.3, 0.6, 0.9, 2.0, 5.0 ],
        accValue = [   1,   2,   4,   8,  16,  32 ],
        accLength = accKey.length;

    return function(delay) {
        var iLeft, iMiddle, iRight;

        iLeft = 0;
        if (delay <= accKey[iLeft])
            return accValue[iLeft];
        iRight = accLength - 1;
        if (accKey[iRight] <= delay)
            return accValue[iRight];        
        while (true) {
            if (iRight - iLeft === 1)
                return delay - accKey[iLeft] < accKey[iRight] - delay ? accValue[iLeft] : accValue[iRight];
            iMiddle = ~~((iLeft + iRight) / 2);
            if (delay < accKey[iMiddle])
                iRight = iMiddle;
            else if (accKey[iMiddle] < delay)
                iLeft = iMiddle;
            else
                return accValue[iMiddle];
        }
    };
}());

#3


1  

In my humble opinion I think the best solution to this problem is to write a function which picks the best acceleration based on the time using if statements as follows:

在我的拙见下,我认为这个问题的最佳解决方案是编写一个根据时间选择最佳加速度的函数,使用if语句如下:

function getAcceleration(time) {
    if (time < 0.20) return 1;
    if (time < 0.45) return 2;
    if (time < 0.75) return 4;
    if (time < 1.45) return 8;
    if (time < 3.50) return 16;
    return 32;
}

However this is a static solution. If that's alright with you then I recommend you use this method. On the other hand if you need a dynamic solution then use this instead:

然而,这是一个静态的解决方案。如果你觉得可以的话,我建议你使用这个方法。另一方面,如果你需要一个动态的解决方案,可以使用以下方法:

var getAcceleration = createAccelerationMap(0.1, 0.3, 0.6, 0.9, 2.0, 5.0);

function createAccelerationMap(previous) {
    var length = arguments.length, limits = [];

    for (var i = 1; i < length;) {
        var current = arguments[i++];
        limits.push((previous + current) / 2);
        previous = current;
    }

    return function (time) {
        var length = limits.length, acceleration = 1;

        for (var i = 0; i < length;) {
            if (time < limits[i++]) return acceleration;
            acceleration *= 2;
        }

        return acceleration;
    };
}

Either way you may then use getAcceleration as follows:

无论哪种方式,您都可以使用get加速度,如下所示:

console.log(getAcceleration(0));          // 1
console.log(getAcceleration(0.33));       // 2
console.log(getAcceleration(0.64));       // 4
console.log(getAcceleration(1.42));       // 8
console.log(getAcceleration(3.14));       // 16
console.log(getAcceleration(123456.789)); // 32

See the demo: http://jsfiddle.net/QepT7/

看到演示:http://jsfiddle.net/QepT7/

#4


0  

If the 0.1 is the number of seconds, and you want to round to 1 decimal you can do something this:

如果0。1是秒数,你想四舍五入到1小数你可以这样做:

// 0.42332 * 10 = 4.2332 
// Math.round( ) will be 4
// 4 / 10 = 0.4
acc[ (Math.round(this._delay * 10) / 10).toString() ]

#5


0  

var seconds = this._delay.toString().substring(0,2)

console.log(acc[seconds]);

This is a straight-forward approach of your problem: First I convert the float to a string, second I cut off everything after the third character.

这是您的问题的一种直接处理方法:首先我将浮点数转换为字符串,其次我在第三个字符之后删除所有内容。

#6


0  

What units are you using?

你用的是什么单位?

this._startTick = (new Date()).getTime();
//       ms     =                 ms

this._delay = (new Date()).getTime() - this._startTick;
//     ms   =                 ms     -       ms

So to get to "0.1"/etc from milliseconds I'm assuming you are doing

从毫秒到0。1,等等,我假设你在做

(Math.floor(ms / 100) / 10).toString();

Why not just keep everything in ms/100 so you can use integers?

为什么不把所有东西都保存在ms/100中,以便使用整数呢?

var acc = [];
acc[ 1] =  1;
acc[ 3] =  2;
acc[ 6] =  4;
acc[ 9] =  8;
acc[20] = 16;
acc[50] = 32;

Then you can create a "nearest" lookup function like this

然后您可以创建这样的“最近的”查找函数

function find(x) {
    var i = 0;
    x = x | 0; // The | 0 will cause a cast to int
    if (x < 0) x = 0;
    if (acc[x] !== undefined) return acc[x];
    if (x > acc.length) return acc[acc.length - 1];
    while (++i < acc.length) {
        if (acc[x - i] !== undefined) return acc[x - i];
        if (acc[x + i] !== undefined) return acc[x + i];
    }
}
find(this._delay / 100);

Now examples are

现在的例子

find(30);    // 16
find(100.5); // 32
find(0);     //  1