请帮助。我对这些事情还很陌生,因此面临解决方案的挑战。
我需要一个JavaScript代码,该代码将帮助我自动选择具有3种可能结果(例如足球-主队,平局或客队获胜)的随机结果。总共有10个事件。必须一次从每个事件中得出一个结果(可能是主胜(a),平局(b)或AwayWin(c)),并且必须为10个事件随机选择结果或结果,直到没有其他可能性为止。我试图在JavaScript中使用递归和不同类型的字符串置换方法,但是我没有得到。 我想要的内容的描述可以从上面的链接中查看。 谢谢。
答案 0 :(得分:1)
如果不需要 生成所有可能的序列,则可以编写一个生成器函数,该函数可以确定性地生成任何单个序列。
此javascript代码段将生成足球比赛的前10个序列。
您可以通过一次致电footballGenerator()
// generates a generic sequence
function sequenceGenerator(index, length, radix) {
return Array.from(
(index % (length * radix))
.toString(radix)
.padStart(length, '0')
).map(n => parseInt(n))
}
// convert a generically generated sequence into a football season's outcomes
function footballGenerator(seed, seasonLength) {
return sequenceGenerator(seed, seasonLength, 3).map(game => {
if (game == 0) {
return "Home"
} else if (game == 1) {
return "Draw"
} else {
return "Away"
}
})
}
// example usage of the `footballGenerator()` function
for (let i = 0; i < 10; i++) {
console.log(footballGenerator(i, 10))
}
答案 1 :(得分:1)
这应该做到。我认为这些评论很明确,但请告诉我是否需要解释。您还可以设置不同数量的事件和结果数组。
// number of events (length of sequence)
const numEvents = 10;
// possible outcomes
const outcomes = ['a', 'b', 'c'];
// total number of possible permutations
// (number of outcomes to the power of number of events)
const numPermutations = outcomes.length**numEvents;
// permutations indices [0, 1, .., numPermutations - 1]
let permutations = Array(numPermutations).fill(0).map((v, i) => i)
// convert sequence of digits to sequence of outcomes ('012' -> 'a b c')
function sequenceToChars(sequence) {
return Array.from(sequence).map(i => outcomes[i]).join(' ');
}
// convert permutation index to an outcome sequence (2 -> 'a a c')
function permutationToSequence(permutation) {
// get the sequence as a number in base of number of outcomes
const sequence = permutation.toString(outcomes.length).padStart(numEvents, '0')
return sequenceToChars(sequence)
}
// pick a permutation randomly until no permutations left
for (let i = 0; i < numPermutations; i++) {
// choose a random index of permutations left
const rand_idx = Math.floor(Math.random() * permutations.length)
// remove and return chosen index
permutation = permutations.splice(rand_idx, 1)[0]
// convert permutation index to sequence
const sequence = permutationToSequence(permutation)
console.log(sequence)
}