问题描述
我在这里发现了关于 Fisher-Yates 和随机化的非常有趣的东西:How to randomize (shuffle) a JavaScript array?
内容!
html,body {
font-size: 16px;
font-family: sans-serif;
}
h1,h2 {
font-family: serif;
margin: 1rem 0.5rem;
}
h1 {
font-size: 1.75rem;
}
h2 {
font-size: 1.25rem;
}
p {
line-height: 1.5;
margin: 0.5rem 0.5rem;
}
<h1>Shuffling</h1>
<p>Comparing the Fisher-Yates to Durstenfield shuffle. Both return randomly sorted numbers quickly and efficiently. Is it O(n)? Only you can tell!</p>
<p>The array to be sorted is 30 numbers,1-30 inclusive. Originally,I intended to do a performance comparison but because of deliberate error introduced into performance.Now() due to Spectre mitigation fixes,that was infeasible to do clientside. So enjoy some shuffled numbers!</p>
<p>Specifically,on pageload each shuffle function will take the input array and return a shuffled result to the DOM.</p>
<div class="results">
<h2>Results</h2>
<p>Fisher-Yates: <span id="fyresults"></span></p>
<p>Durstenfield: <span id="dfresults"></span></p>
</div>
animals = {'Lion':["meet",1.2,'yellow'],'Cat':["milk",0.3,'white'],'dog':["Dog",1,'black']}
def invert_dict(dic):
return {v: d.setdefault(v,[]).append(k) or d[v] for d in ({},) for k in dic for v in dic[k]}
print(invert_dict(animals))
现在我想用名字替换这 30 位数字(例如:Thomas、Adrian、James、Patrick、Victor...)
我该怎么做?我对此很陌生,我迈出了第一步
解决方法
由于 shuffle
函数会打乱数组索引,因此您可以按照与之前相同的方式打乱数组,但在数组中添加名称字符串。
// replace numbers with names
const inputArray = ["Thomas","Adrian","James","Patrick","Victor"];
//define Durstenfield shuffle
const durstenShuffle = function(array) {
for (var i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
let temp = array[i];
array[i] = array[j];
array[j] = temp;
}
document.getElementById("dfresults").append(array.toString());
};
//define Fisher-Yates shuffle
const fisherShuffle = function(array) {
let currentIndex = array.length,temporaryValue,randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
document.getElementById("fyresults").append(array.toString());
};
fisherShuffle(inputArray);
durstenShuffle(inputArray);
<div class="results">
<h2>Results</h2>
<p>Fisher-Yates: <span id="fyresults"></span></p>
<p>Durstenfield: <span id="dfresults"></span></p>
</div>