繁体   English   中英

如何从随机数组中选择随机元素?

[英]How do I choose a random element from a random array?

我是一个Ruby初学者,他试图在我的刽子手游戏中添加多个类别。

我知道如何从数组中选择一个随机元素。 例如:

animals = ['dog', 'cat', 'mouse']
random = animals[rand(animals.length)] 
puts random

但是,我想随机选择整个数组,然后从该随机数组中选择一个随机元素。 例如:

animals = ['dog', 'cat', 'mouse']
planets = [['jupiter'], ['mars']]
fruits = [['apple'], ['orange'], ['mango']]

categories =[[animals], [planets], [fruits]]

#the code I tried was:
random_array = categories[rand(categories.length)]
random_element = random_array[rand(random_array.length)]
puts random_element

但这会产生一个完整的数组,而不是一个元素。 请帮忙! 谢谢

animals = ['dog', 'cat', 'mouse']
planets = [['jupiter'], ['mars']]
fruits = [['apple'], ['orange'], ['mango']]

categories = [animals, planets, fruits]
puts categories.sample.sample #=> jupiter

正如Sawa所说,这将返回一个字符串或一个子数组。 *categories.sample.sample (一个splat)总是返回一个字符串。

你的代码是正确的,但数组初始化不是。 这是你要做的:

animals = ['dog', 'cat', 'mouse']
planets = ['jupiter', 'mars'] 
fruits = ['apple', 'orange', 'mango']

categories = [animals, planets, fruits]

在你的代码中, animals是数组, planetsfruits是数组的数组,而categories是三个数组的数组,每个数组中都有一个变量

你有什么应该工作,这是你的categories数组不起作用。 它应该是:

categories =[animals, planets, fruits]

而不是数组中的数组混合。

为什么不把它们弄平或者是一种矫枉过正

a = (animals.flatten + fruits.flatten + planets.flatten)
r = a[rand(a.flatten.size)]
=> "dog"

您也可以使用更高效的<<来连接数组。

使用Array#sample方法

这应该是最短,最干净的方法。

animals = ['dog', 'cat', 'mouse']
planets = [['jupiter'], ['mars']]
fruits = [['apple'], ['orange'], ['mango']]

[animals, planets, fruits].flatten.sample

#flatten返回一个包含所有元素但只有一个维度的新数组。

#sample从您的数组中返回一个随机元素

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM