How can I generate a random number within a range but exclude some?(如何生成一个范围内的随机数但排除一些?)
问题描述
基本上我选择0-24之间的随机数:
Basically I pick a random number between 0-24:
Math.floor(Math.random() * myArray.length); // myArray contains 25 items
假设结果是 8.现在我想得到另一个在 0-24 范围内的数字,但这次,我不想要 8.下一次,我可能会掷出 15.现在我想要再次滚动,但我不想要 8 或 15.我现在处理此问题的方式是使用 do while 循环,如果数字相同,我只需重新滚动.
Lets say it comes out to be 8. Now I want to get another number in the same range 0-24 but this time, I do not want an 8. The next time, I might roll a 15. Now I want to roll again but I don't want an 8 or 15. The way I am handling this now is by using do while loops and if the number comes out the same, I just reroll.
这是我家庭作业的一小部分,事实上,我已经让它满足所有要求,所以我想你可以说这是为了我个人的利益,所以我可以正确地写这个而不是结束每日wtf".
This is a small portion of my homework and I, in fact, have it working to meet all the requirements so I guess you could say this is for my own personal benefit so I can write this properly and not end up on "the daily wtf".
推荐答案
设置一个包含所有值的数组(如果你只做小数字,这只是一个有效的选项,比如你的例子中的 25),像这样:
Set an array with all the values (this is only a valid option if you're only doing small numbers, like the 25 in your example), like this:
var array = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24];
然后,在 0 和数组长度之间选择一个随机数:
then, pick a random number between 0 and the array length:
var num = Math.floor(Math.random() * array.length);
从数组中删除该索引号:
var roll = array.splice(num, 1);
Javascript splice()从数组中删除索引项并将项作为数组返回.非常适合您使用.
Javascript splice() removes indexed items from an array and returns the item(s) as an array. Perfect for your use.
从卷中获取第一个索引,因为无论如何我们只删除了 1 个:
Grab the first index from the roll, since we only cut 1 out anyway:
var yourNumber = roll[ 0 ];
继续做尽可能多的卷.此外,您可能希望将原始数组存储为副本,以便轻松重置"数字.
Keep doing for as many rolls as you want. Also, you might want to store the original array as a copy so that you can "reset" the numbers easily.
这篇关于如何生成一个范围内的随机数但排除一些?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何生成一个范围内的随机数但排除一些?


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07