在x和y之间生成“随机”数字,差异至少为100

时间:2013-01-28 17:30:47

标签: javascript random

我正在尝试将图片放在网页上的横幅div中。图像需要沿x轴“随机”定位(使用CSS left属性),因此在加载页面时它们并不总是相同。我有以下脚本来执行此操作(它还设置了随机延迟,因此图像每次都以不同的时间顺序出现:

for (var i = 1; i <= 5; i++) {

    var delay = Math.floor(Math.random() * 800) + 1;
    var xPos = Math.floor(Math.random() * 900) + 1;

    $('#item'+i).css('left',xPos+'px').delay(delay).animate({ top: 18 }, { duration: 1000, easing: 'easeOutBounce' });

}

然而,问题在于图像的重叠经常太多而且它们彼此隐藏在一起。所以我想扭曲随机性,以便所有xPos变量之间至少有100px的差异。这应该给我一个随机的外观,但保持项目大部分也可见。

必须有一个词来描述这种事情,但是我已经找不到任何有用的东西来指示如何实现它。

有人能指出我在正确的方向吗?

非常感谢。

编辑:

好的,所以我可以自己动手去做这个。我想我差不多了。我正在做的是创建一个初始随机数并将其添加到数组中,然后循环遍历5个项目中的每一个并生成另一个随机数,然后进行比较以确保它与当前数组中的任何内容不同。

代码是这样的(我目前没有使用所有变量 - 这是一项正在进行中的工作!):<​​/ p>

function randomImagePlacement() {
    var containerWidth = 940;                   // Width of container element
    var itemWidth = 267;                        // Width of item (taking into account rotation)
    var minX = 0;                               // Minimum left position of an item
    var maxX = containerWidth - itemWidth;      // Maximum left position of an item
    var minSeparation = 100;                    // Minimum number of pixels of separation between items
    var numberOfItems = 5;                      // Total number of items
    var randomNumbers = [];                     // Array 'container' to hold random numbers

    for (var i = 1; i <= numberOfItems; i++) {

        if (i == 1) {
            var firstRandomNumber = Math.floor(Math.random() * 700) + 1;
                    randomNumbers.push(firstRandomNumber);
                    console.log('First random number: ' + firstRandomNumber);
        } else {
                    var newRandomNumber = Math.floor(Math.random() * 700) + 1;

            /*
            This if/else block works okay but it doesn't keep checking differences until the criteria is met
            if (checkDiff(newRandomNumber, randomNumbers)) {
                        console.log('New number (' + newRandomNumber + ') sufficiently different enough');
                        randomNumbers.push(newRandomNumber);
            } else {
                        console.log('New number (' + newRandomNumber + ') NOT sufficiently different enough');
            }
            */
            /* This do/while block is my attempt at trying to run the check diff function until the criteria is met, but it just results in the browser crashing */     
            do {
                        randomNumbers.push(newRandomNumber);
            } while (checkDiff(newRandomNumber, randomNumbers) == true);

        }

    }

    for (var i = 0; i < randomNumbers.length; i++) {
        console.log('From final array: ' + randomNumbers[i]);
    }

}


function checkDiff(newRandomNumber, currentArray) {
    console.log('newRandomNumber = ' + newRandomNumber);

    var proximityMatch = false;
    for (var i = 0; i < currentArray.length; i++) {
        console.log('Diff between ' + currentArray[i] + ' and ' + newRandomNumber + ' = ' + Math.abs(currentArray[i] - newRandomNumber));
        if (Math.abs(currentArray[i] - newRandomNumber) > 100) {
            proximityMatch = true;
        }
    }
    if (proximityMatch == true) {
        return true;
    } else {
        return false;
    }
}

randomImagePlacement();

基本上它失败的地方是上面的do / while循环。我不确定这样做的正确方法,但我基本上需要说“继续运行checkDiff函数,直到它返回true;当它返回true时,将newRandomNumber添加到数组中;如果它不返回再次运行它“。

任何人都可以帮我解决这个问题吗?

非常感谢!

2 个答案:

答案 0 :(得分:0)

您可以采取的方法是:

item0.x = //随机数

item1.x = item0.x + item0.width + 100 +(随机数)

item2.x = item1.x + item1.width + 100 +(随机数)

答案 1 :(得分:0)

<强>更新

抱歉,我没有意识到您需要对所有生成的值进行比较。这将有效:

var isLessThanMinSeparation = function checkDiff(randomNumber, randomNumbers, minSeparation) {
    var lessThan100 = false,                // Flag for whether minSeparation has been maintained
        i = 0;                              // Incrementer
    console.log('randomNumber = ' + randomNumber);
    for (i = 0; i < randomNumbers.length; i += 1) {
        console.log('Diff between ' + randomNumbers[i] + ' and ' + randomNumber + ' = ' + Math.abs(randomNumbers[i] - randomNumber));
        lessThan100 = lessThan100 || Math.abs(randomNumbers[i] - randomNumber) <= minSeparation;
    }
    return lessThan100;
};
var randomImagePlacement = function randomImagePlacement(numberOfItems, minSeparation) {
    //numberOfItems = 5,                    // Total number of items
    //minSeparation = 100,                  // Minimum number of pixels of separation between items
    var randomNumbers = [],                 // Array 'container' to hold random numbers
        randomNumber = 0,                   // Random number
        i = 0;                              // Incrementer
    for (i = 1; i <= numberOfItems; i += 1) {
        while (isLessThanMinSeparation(randomNumber, randomNumbers, minSeparation)) {
            randomNumber = Math.floor(Math.random() * 700) + 1;
        }
        randomNumbers.push(randomNumber);
    }
    return randomNumbers;
};
console.log(randomImagePlacement(5, 100));

我实现这一目标的方式是:

  1. 存储最后一个随机分配的位置
  2. 使用循环(最少运行一次)来分配新的随机分配位置
  3. 比较新的随机分配的位置并重新进入循环,如果差异&lt; 100
  4. 一个例子:

    var randomizeImgPlacement = function randomizeImgPlacement() {
        var i = 0,
            delay = 0,
            xPos = 0,
            lastPos = 1000; //Default to 1000 so very first assignment has at least 100 difference
        for (i = 1; i <= 5; i += 1) {
            delay = Math.floor(Math.random() * 800) + 1;
            do { //loop assignment of xPos
                xPos = Math.floor(Math.random() * 900) + 1;
            } while (Math.abs(xPos) - Math.abs(lastPos) >= 100); // while difference is < 100
            $('#item' + i).css('left', xPos + 'px').delay(delay).animate({
                top: 18
            }, {
                duration: 1000,
                easing: 'easeOutBounce'
            });
            lastPos = xPos; //store lastPos for loop comparison
        }
    };