简体   繁体   English

Fisher Yates随机播放1个显示的数字

[英]Fisher Yates shuffle 1 number shown

I am using the Fisher Yates Shuffle and gone through the little tutorial, I can see that you can randomize an order such as 4,1,3,2,6,7,5 etc... but I want to find out how to have only 1 number shown. 我正在使用Fisher Yates Shuffle并阅读了该小教程,我可以看到您可以将一个顺序随机化,例如4,1、3、2、6、7、5等。但是我想了解如何仅显示1个数字。 There could be a submit button and when I press submit a random number between 1 to 7 is shown. 可能会有一个提交按钮,当我按“提交”按钮时,会显示一个1到7之间的随机数。 That number is then put aside so when I hit submit again there will be a 100% chance I wont see that number again. 然后将该数字放在一边,所以当我再次单击Submit时,我将有100%的机会不再看到该数字。 So basically I can press submit 7 times and the 8th time nothing will happen. 因此,基本上我可以按7次提交,而第八次则什么也不会发生。 this was the Javascript i was using: 这是我使用的Javascript:

    <script>
Array.prototype.shuffle = function(){
  var i = this.length, j, temp;
while(--i > 0) {
    j = Math.floor(Math.random() * (i+1));
    temp = this[j];
    this[j] = this[i];
    this[i] = temp;
    }
    return this;
}
var arr = ['A','B','C','D','E','F','G','H'];
var result = arr.shuffle();

document.write(result);
</script>

I have googled this with no success, Many thanks. 我用谷歌搜索没有成功,非常感谢。

Here is my implementation of it that I have used. 这是我使用过的实现。

function fisherYates ( myArray,stop_count ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  var c = 0;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
     c++;
     if(c == stop_count)return;
   }
}

You can call this with : 您可以通过以下方式致电:

fisherYates(arr,Math.min(nr_items, selectionSize));

Note that 注意

 var tempi = myArray[i];
 var tempj = myArray[j];
 myArray[i] = tempj;
 myArray[j] = tempi;

is a dumber version of: 是以下版本的哑色版本:

 var temp = myArray[i];
 myArray[i] = myArray[j];
 myArray[j] = temp;

You could print a particular position within the array, because it's randomised each time- isn't it? 您可以在数组中打印特定位置,因为它每次都是随机的,不是吗? So, you could create a variable with that position, and then print the variable. 因此,您可以使用该位置创建一个变量,然后打印该变量。 Eg 例如

var finalResult = arr[2]; //you can have any position you want
document.write(finalResult);

That should work for you. 那应该为您工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM