【问题标题】:Random Generated Number- "Check" function随机生成数字-“检查”功能
【发布时间】:2014-05-10 02:39:41
【问题描述】:

我有一个 3x4 的图像表,当页面加载时,所有单独的图像都会加载,以便制作“一个图像”(图像是碎片化的,有点像拼图)。我有一个名为自动化的按钮,单击时会随机化图像。我需要的是一个“检查”函数来查看一个数字是否已经被使用(希望代码有助于理解这一点)。

JS 随机化图片:

function auto(){
    for (i = 0; i <= 12; i++){ 
    r=Math.floor(Math.random()*12);
    alert(r)   // Just shows where I'm at for figuring it out
    document.images[i].src="pic"+r+".gif"
}

我的图像被称为“pic0 , pic1”等。所以随机数 0-12 将随机化图像源。

我现在需要的是一个函数,它将逐步遍历图像 0-11 并检查是否已经使用了一个数字以避免重复图片。到目前为止,这就是我对该功能的了解,但现在卡住了。

用于检查的 JS:

for (i=0; i < 12; i++){
check[i]=0;
}

if ( check[r] === 0)
{
    document.images[i].src = "pic" + r + ".gif";
    check[r] = 1;
}
else {
    while (check[r] ===0){
        r= (r+1) % 12;
        document.images[i].src = "pic" + r + ".gif";
        check[r] = 1;
    }

【问题讨论】:

    标签: javascript if-statement for-loop random


    【解决方案1】:

    你想要的是一个打乱函数。

    scramble = function(x) {
       var y = [];
       while(x.length > 0) y.push(x.splice(Math.floor(Math.random() * x.length), 1)[0]);
       return y;
    }
    scramble([1,2,3,4,5,6])
    // [2, 4, 3, 5, 1, 6]
    

    在上面的代码中,我们不断地从x 中选择一个随机索引,然后将其删除并附加到数组y 中。这样,x 最终将为空,y 将是x 的加扰版本。

    【讨论】:

    • 这很漂亮,我唯一可能建议的是在 x === y 时递归,否则它不会是一个很大的“谜题”。
    【解决方案2】:

    您无需检查该号码是否已被使用。相反,用数字 1 - n 填充一个数组并将它们打乱:

    // using the suffle function here:
    // http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
    
    var imgIndices = [];
    for ( i=0; i < 12; i++ )
        imgIndices.push( i );
    imgIndices = shuffle( imgIndices );
    
    for ( var imgNum=0; imgNum < imgIndices.length; imgNum++ )
        picName="pic"+imgIndices[ imgNum ]+".gif"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 2018-03-12
      • 1970-01-01
      • 2016-04-13
      • 2015-05-28
      • 1970-01-01
      相关资源
      最近更新 更多