【发布时间】:2021-07-20 11:38:26
【问题描述】:
我正在尝试洗牌。我将一些卡片作为输入。例如,numCards = 5,所以牌组(列表)变为 [0,1,2,3,4]。问题是 test_order(i,j,l) 函数中的 while 循环没有正确改组。函数 console.log(m) 应该使用原始列表 (l) 打印一个新的洗牌甲板/列表,但它会在第一次正确洗牌后继续打印 [0,1,2,3,4]。它应该每次使用原始列表创建一个新洗牌的牌组,相反,它会不断重复原始列表或第一个洗牌列表。
该程序的目的是找出标记为 i 的牌在洗牌后高于标记为 j 的牌的次数的概率。
function list(numCards){
var newList = []
var i = 0;
while (i < numCards){
newList.push(i);
i++;
}
return newList
}
function top_to_random(l){
while(numPerformed != 0){
var x = Math.floor(Math.random() * l.length);
l.splice(x, 0, l.shift())
numPerformed--;
}
return l
}
function test_order(i,j,l){ //PROBLEM IS IN HERE!!!!
var n = 0
var trials = 10
var count = 0
while (count < trials){ // PROBLEM IN WHILE LOOP
let arrayCopy = JSON.parse(JSON.stringify(l));
//console.log(arrayCopy)
var m = top_to_random(arrayCopy)
m.indexOf(i) < m.indexOf(j) ? n++ : n = n + 0
//console.log(arrayCopy)
console.log(m)
count++
}
var prob = n/trials
return prob
}
//Argument Inputs
var numCards = parseInt(prompt("Enter number of cards in deck: "))
var l = list(numCards)
var numPerformed = parseInt(prompt("Enter number of shuffles to perform on deck: "));
var i = parseInt(prompt("i: "))
var j = parseInt(prompt("j: "))
//Execution
console.log(test_order(i,j,l))
【问题讨论】:
标签: javascript arrays while-loop shuffle