在 x 和 y 之间生成至少相差 100 的“随机"数 [英] Generate 'random' numbers between x and y with a difference of at least 100

查看:40
本文介绍了在 x 和 y 之间生成至少相差 100 的“随机"数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to position images within a banner div on a web page. The images need to be positioned 'randomly' along the x axis (using the CSS left property), so they don't always appear the same when the page is loaded. I have the following script to do this (it also sets a random delay so the images appear in a different temporal order each time:

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 的差异.这应该给我一个随机的外观,但也保持项目大部分可见.

However, the problem is that there's very often too much overlap with the images and they're hidden behind one another. So I'd like to skew the randomness so that there's at least 100px difference between all of the xPos variables. This should give me a random-looking appearance but keeping the items mostly visible too.

必须有一个词来描述这种事情,但搜索后我找不到任何有用的东西来说明如何实现它.

There must be a word to describe this kind of thing but having searched I just can't find anything useful to indicate how to achieve it.

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

Can anyone point me in the right direction here?

非常感谢.

好的,所以尝试滚动我自己的函数来做到这一点.我想我快到了.我正在做的是创建一个初始随机数并将其添加到一个数组中,然后循环遍历 5 个项目中的每一个并生成另一个随机数,然后将其进行比较以确保它与当前数组中的任何内容都有 100 多个不同.

Okay, so having a go at rolling my own functions to do this. I think I'm almost there. What I'm doing is creating an initial random number and adding this to an array, then looping through each of the 5 items and generating another random number, then comparing this to make sure it's more than 100 different to anything currently in the array.

代码是这样的(不是我所有的变量当前都在使用——这是一项正在进行的工作!):<​​/p>

The code is like this (not all of my variables are being used currently - it's a work in progress!):

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 添加到数组中;如果它没有返回再次运行它".

Basically where it's failing is in the do/while loop above. I'm not sure of the correct way to do something like this, but I basically need to say "Keep running the checkDiff function until it returns true; when it does return true add the newRandomNumber to the array; if it doesn't return true run it again".

有人能帮我解决这个问题吗?

Can anyone help me out on this?

非常感谢!

推荐答案

UPDATE

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

Sorry, I didn't realize you needed that comparison across all generated values. This will work:

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));

我要做到这一点的方法是:

The way I'd accomplish this would be to:

  1. 存储最后一个随机分配的位置
  2. 使用循环(最少运行一次)分配新的随机分配位置
  3. 比较新的随机分配的位置,如果差异<则重新进入循环.100

示例:

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
    }
};

这篇关于在 x 和 y 之间生成至少相差 100 的“随机"数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆