在x和y之间生成“随机”数字,差异至少为100(Generate 'random' numbers between x and y with a difference of at

编程入门 行业动态 更新时间:2024-10-17 11:22:03
在x和y之间生成“随机”数字,差异至少为100(Generate 'random' numbers between x and y with a difference of at least 100)

我正在尝试将图像放在网页上的横幅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个项目中的每一个并生成另一个随机数,然后进行比较以确保它与当前数组中的任何内容不同。

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

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添加到数组中;如果它不返回再次运行它“。

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

非常感谢!

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

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?

Many thanks.

EDIT:

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.

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

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?

Many thanks!

最满意答案

UPDATE

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

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

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

存储最后一个随机分配的位置 使用循环(最少运行一次)来分配新的随机分配位置 比较新的随机分配位置,如果差值<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 } };

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:

Store the last randomly-assigned position Use a loop (with a minimum run of once) to assign the new randomly-assigned position Compare the new randomly-assigned position and re-enter the loop if the difference < 100

An example:

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

更多推荐

本文发布于:2023-08-06 04:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1444509.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:差异   数字   Generate   numbers   random

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!