我必须计算硬件的配置,它使用最少数量的捕获卡,基于所需频道的数量。这些卡可分为4、8和16种渠道。
重要的是要注意,最少的卡数是第一优先,第二优先是尽可能使用更便宜的(较低的通道)卡。因此,22通道请求可以用2 16通道卡填充,但是使用16通道卡和8通道卡更可取,因为它使用相同数量的物理卡,同时使用更便宜的8通道卡而不是两个16通道卡。
var card_16 = "US-HDVRC2-16-480D";
var card_8 = "US-HDVRC2-8-240D";
var card_4 = "US-HDVRC2-4-120D";
function getCardObject(channels) {
var cards = {}
var remainder = channels%16;
if (channels/16 >= 1) //if there are at least 16 channels
{
cards[card_16] = Math.floor(channels/16);
if (remainder != 0)
{
if (remainder > 8)
cards[card_16] = cards[card_16] + 1;
else if (remainder > 4)
cards[card_8] = 1;
else
cards[card_4] = 1;
}
}
else if (channels/8 >= 1) { //if there aren't 16 but at least 8
if (remainder != 0)
{
if (remainder > 8)
cards[card_16] = 1;
else if (remainder > 4)
cards[card_8] = 1;
else
cards[card_4] = 1;
}
}
else if (channels/4 >= 1) { //if there are at least 4
if (remainder != 0)
{
if (remainder > 4)
cards[card_8] = 1;
else
cards[card_4] = 1;
}
}
else //if there are less than 4
cards[card_4] = 1;
return cards;
};发布于 2017-01-05 23:59:40
你的自己的答案相当不错。我会把它拉紧一点。特别地,
answer代表的是什么。此外,由于您只对Math.floor(channels/16)感兴趣,我将以更简洁和高效的方式计算它:var sixteens = channels >> 4;。cards["US-HDVRC2-16-480D"]或重新计算remainder > 8。+运算符。cards对象。这意味着你可能会得到一些成员的价值是0 -我不知道这是否是可以接受的。function getCardObject(channels) {
var sixteens = channels >> 4; // Math.floor(channels / 16)
var remainder = channels & 15; // channels % 16
return {
"US-HDVRC2-16-480D": sixteens + (8 < remainder),
"US-HDVRC2-8-240D": +(4 < remainder && remainder <= 8),
"US-HDVRC2-4-120D": +(0 < remainder && remainder <= 4),
};
}作为比较,这里有一个使用显式公式的单一表达式版本。我不认为它比你所拥有的更好--这当然不容易理解。
function getCardObject(channels) {
return {
// Use a 4-channel card if 1 <= (channels % 16) <= 4
'US-HDVRC2-4-120D': +(((channels - 1) & 15) < 4),
// Use an 8-channel card if 5 <= (channels % 16) <= 8
'US-HDVRC2-8-240D': +(((channels - 1) & 12) == 4),
// 16-channel cards for the rest
'US-HDVRC2-16-480D': (channels >> 4) + ((channels & 15) > 8),
};
}发布于 2017-01-05 22:21:35
我想我想明白了,当我可以依靠剩下的操作时,我甚至不需要执行所有这些部门:
function getCardObject(channels) {
var cards = {}
var answer = channels/16;
var remainder = channels%16;
if (remainder > 8)
cards["US-HDVRC2-16-480D"] = 1;
else if (remainder > 4)
cards["US-HDVRC2-8-240D"] = 1;
else if (remainder > 0)
cards["US-HDVRC2-4-120D"] = 1;
if (answer >= 1) cards["US-HDVRC2-16-480D"] = (remainder > 8 ? 1 : 0) + Math.floor(answer);
return cards;
};https://codereview.stackexchange.com/questions/151795
复制相似问题