gpt4 book ai didi

javascript - 查找最多 9 个数字 - 快速

转载 作者:行者123 更新时间:2023-11-30 09:28:42 24 4
gpt4 key购买 nike

我有 9 个随机整数。有没有更快的方法如何在不显式比较所有内容的情况下找到最大值?

我每帧执行此操作数百万次,这非常慢。

function calculateMax(a, b, c, 
d, e, f,
g, h, i){
var max = (a > b) ? a : b;
var max2 = (c > d) ? c : d;
var max3 = (e > f) ? e : f;
var max4 = (g > h) ? g : h;

max = (i > max) ? i : max;
max = (max2 > max) ? max2 : max;
max = (max3 > max) ? max3 : max;
max = (max4 > max) ? max4 : max;

return max;
}

最佳答案

The results seem rather disappointing after running few times , 但如果有人想在其他浏览器上进行更好的测试或改进(使用 SIMD instructions 可能会更快)

function max1(a, b, c, d, e, f, g, h, i) {                   // shortened calculateMax
var max = (a > b) ? a : b; var max2 = (c > d) ? c : d;
var max3 = (e > f) ? e : f; var max4 = (g > h) ? g : h;

max = ( i > max) ? i : max; max = (max2 > max) ? max2 : max;
max = (max3 > max) ? max3 : max; max = (max4 > max) ? max4 : max;
return max;
}

function max2(a, b, c, d, e, f, g, h, i) {
if (a < b) a = b; if (a < c) a = c; if (a < d) a = d; if (a < e) a = e;
if (a < f) a = f; if (a < g) a = g; if (a < h) a = h; if (a < i) a = i;
return a;
}

//function max(a, b) { return a - ((a -= b) & (a >> 31 )); }
//function max(a, b) { return (a - b >>> 31) * b | (b - a >>> 31) * a }
function max(a, b) { return (a - b >> 31) & b | (b - a >> 31) & a }

function max3(a, b, c, d, e, f, g, h, i) {
return max(a, max(b, max(c, max(d, max(e, max(f, max(g, max(h, i))))))))
}

function max4(a, b, c, d, e, f, g, h, i) {
a = (a - b >> 31) & b | (b - a >> 31) & a
a = (a - c >> 31) & c | (c - a >> 31) & a
a = (a - d >> 31) & d | (d - a >> 31) & a
a = (a - e >> 31) & e | (e - a >> 31) & a
a = (a - f >> 31) & f | (f - a >> 31) & a
a = (a - g >> 31) & g | (g - a >> 31) & a
a = (a - h >> 31) & h | (h - a >> 31) & a
return (a - i >> 31) & i | (i - a >> 31) & a
}

var l = console.log, p = performance
var t = p.now(), m = max1(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 1, -t)
var t = p.now(), m = max2(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 2, -t)
var t = p.now(), m = max3(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 3, -t)
var t = p.now(), m = max4(1,2,3,4,5,6,7,8,9); t -= p.now(); l(m, 4, -t)

关于javascript - 查找最多 9 个数字 - 快速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47728919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com