我正试着交一个扑克的解决方案。我已经掌握了所有的逻辑来确定最好的5张牌手。我遇到了比较多个数组的问题,这些数组在发生关系时具有更高的元素(关于手类型)。
假设我们有一些潜在的赢家想冲一冲。
var low_flush = [2, 3, 4, 5, 7]
var medium_flush = [3, 4, 5, 6, 8]
var high_flush = [2, 3, 4, 5, 9]我想要构建一个函数,将任意数量的数组传递给它,它返回“最高的扑克牌手”,或者在发生实际领带时返回一组手:
function bestHand(hands){
//
return high_hand
}到目前为止,我所读到的所有东西都是如何比较两个数组的,通常情况下,它只会看到是否存在相等的数组。如果这对我的源代码有帮助的话
我的第一个想法是在双手上反复练习。对于每一次迭代,再次在双手上迭代以进行比较。一想到这个伪代码就会让我头疼,并认为它们可能是这个和/或库(但不是扑克库)更优雅的解决方案。
我在代码库的其他部分使用下划线,所以请随意使用它来回答!
发布于 2016-04-20 15:32:56
这听起来可能很傻。但这似乎对我有用。
var hands = [ [2, 3, 4, 5, 7], [2, 3, 5, 9, 8], [2, 3, 4, 5, 9] ];
var values = [];
function bestHand(hands){
hands.forEach(function(arr, index) {
var temp = arr.slice();
values[index] = parseInt(temp.sort().reverse().join(''));
});
var max = Math.max.apply(Math, values);
return hands[values.indexOf(max)];
}
bestHand(hands);发布于 2016-04-20 15:38:36
您可以首先使用减少()来计算每个数组的和
var total3 = high_flush.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
}, 0);之后,将每个数组推到一个数组中,其中包含数组的total和winner的名称。
allhands.push({total: total1 , name: "low_flush"});然后将它们与比较函数进行比较,并对数组进行排序。
function compare(a,b) {
if (a.total < b.total)
return -1;
else if (a.total > b.total)
return 1;
else
return 0;
}
allhands.sort(compare);这里的工作示例:
var low_flush = [2, 3, 4, 5, 7];
var medium_flush = [2, 3, 4, 5, 8];
var high_flush = [2, 3, 4, 5, 9];
var allhands = [];
var total3 = high_flush.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
}, 0);
allhands.push({total: total3 , name: "high_flush"});
var total1 = low_flush.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
}, 0);
allhands.push({total: total1 , name: "low_flush"});
var total2 = medium_flush.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
}, 0);
allhands.push({total: total2 , name: "medium_flush"});
function compare(a,b) {
if (a.total < b.total)
return -1;
else if (a.total > b.total)
return 1;
else
return 0;
}
allhands.sort(compare);
console.log("The winner is "+allhands[allhands.length - 1].name +"With total:"+ allhands[allhands.length - 1].total );<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
发布于 2016-04-20 15:41:57
显然,您需要将一个手动对象数组传递给类似的东西。
function getBest(...hands){
return hands.sort((p,c) => p.weight() <= c.weight() ? -1:1)[hands.length-1]
}当在领带条件下求出手部物体的重量时,首先可以由手的颜色(黑桃拍打所有)来决定,然后由诸如2,3,4,5,6,7,8,9,10,11(j),12(q),13(k),14(a)等俱乐部的卡片值之和来确定。它们的总和都是104,因此对于钻石卡的值可以是(104+2)、(104+3)、(104+4)等等。对于心脏,你用208来抵消数值,用312来抵消黑桃。
hand.prototype.weight = function(){
return this.reduce((p,c) => p.value + c.value)
}当然,这只会处理领带的条件。它不能区分同花顺和同花顺皇家。
https://stackoverflow.com/questions/36747809
复制相似问题