algorithm - 模算法难以捉摸

标签 algorithm clock modulo color-wheel

我有一个色轮,可以将颜色映射到 24 小时制的每个小时。现在给定一天中的时间,我想将这些颜色映射到 12 小时制,以便使用当前时间之前 5 小时和之后 6 小时的颜色。但这有点棘手,因为结果的第 0 个索引始终必须是 24 色轮的第 0 种颜色或第 12 种颜色。

例如,给定colors24作为 24 种颜色的数组和 5 小时的时间,然后是最终的 color12数组将映射到 colors24 的索引为:

{0,1,2,3,4,5,6,7,8,9,10,11}

如果小时是 3,那么:

{0,1,2,3,4,5,6,7,8,9,22,23}

如果小时是 9,那么:

{12,13,14,15,4,5,6,7,8,9,10,11}

如果该算法可以推广到任意两个数组而不管大小,只要第一个数组可以被第二个数组整除即可加分。

最佳答案

如果hours是总小时数(24),length是一次显示的颜色数(12),hour 是当前时间,那么这是将索引放入颜色数组的通用算法:

result = [];
add = hour + hours - (length / 2) - (length % 2) + 1;
for (i = 0; i < length; i++) {
    result[(add + i) % length] = (add + i) % hours;
}

这是一个 Javascript 实现(通用,可用于 24/12 以外的其他范围):

function getColorIndexes(hour, hours, length) {
    var i, result, add;

    if (hours % length) throw "number of hours must be multiple of length";
    result = [];
    add = hour + hours - (length / 2) - (length % 2) + 1;
    for (i = 0; i < length; i++) {
        result[(add + i) % length] = (add + i) % hours;
    }
    return result;
}

console.log ('hour=3: ' + getColorIndexes(3, 24, 12));
console.log ('hour=5: ' + getColorIndexes(5, 24, 12));
console.log ('hour=9: ' + getColorIndexes(9, 24, 12));
console.log ('hour=23: ' + getColorIndexes(23, 24, 12));

如问题中所述,小时数 (24) 必须是要返回的数组长度的倍数。

关于algorithm - 模算法难以捉摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37501743/

相关文章:

python - 具有可变数量 worker 的任务的最佳调度

algorithm - 死锁检测算法(伪代码)

python - 简单的对象检测(python)

c++ - 如何使用C++根据当前时间自动生成新的CSV文件

sql - “MOD”不是可识别的内置函数名称

algorithm - 关于 p2p 算法的细节、书籍或开源项目?

c - Lamport 逻辑时钟。它是如何开始工作的?

json - 铯CZML模型: is it possible to define multiple clock intervals?

javascript - 在 switch 语句中是否可以在每种情况下使用模运算符?

c# - 随时间变化的数据聚合