无法在多维数组中随机生成数字

时间:2023-01-24 22:25:42

I'm trying to generate coordinates in a mulidimensional array.

我正在尝试在多维数组中生成坐标。

the range for each digit in the coords is -1 to 1. <=> seems like the way to go comparing two random numbers. I'm having trouble because randomizing it takes forever, coords duplicate and sometimes don't fill all the way through. I've tried uniq! which only causes the initialization to run forever while it tries to come up with the different iterations.

coords中每个数字的范围是-1到1. <=>似乎是比较两个随机数的方法。我遇到了麻烦,因为随机化它需要永远,coords复制,有时不会一直填写。我试过uniq!这只会导致初始化在尝试提出不同的迭代时永远运行。

the coords look something like this. (-1, 0, 1, 0, 0)

坐标看起来像这样。 (-1,0,1,0,0)

5 digits give position. I could write them out but I'd like to generate the coords each time the program is initiated. The coords would then be assigned to a hash tied to a key. 1 - 242.

5位给出位置。我可以把它们写出来但我想在每次启动程序时生成coords。然后将coords分配给与密钥绑定的散列。 1 - 242。

I could really use some advice.

我真的可以使用一些建议。

edited to add code. It does start to iterate but it doesn't fill out properly. Short of just writing out an array with all possible combos and randomizing before merging it with the key. I can't figure out how.

编辑以添加代码。它确实开始迭代,但它没有正确填写。只需编写一个包含所有可能组合的数组并在将其与密钥合并之前进行随机化。我无法弄清楚如何。

room_range = (1..241)
room_num = [*room_range]
p room_num
$rand_loc_cords = []

def Randy(x)

    srand(x)
    y = (rand(100) + 1) * 1500
    z = (rand(200) + 1) * 1000
    return z <=> y

end

def rand_loc


   until $rand_loc_cords.length == 243 do
     x = Time.new.to_i
    $rand_loc_cords.push([Randy(x), Randy(x), Randy(x), Randy(x), Randy(x)])
    $rand_loc_cords.uniq!
    p $rand_loc_cords
end

   #p $rand_loc_cords

end

rand_loc

1 个解决方案

#1


0  

You are trying to get all possible permutations of -1, 0 and 1 with a length of 5 by sheer luck, which can take forever. There are 243 of them (3**5) indeed:

你试图通过纯粹的运气获得-1,0和1的所有可能的排列长度为5,这可能需要永远。确实有243个(3 ** 5):

coords = [-1,0,1].repeated_permutation(5).to_a 

Shuffle the array if the order should be randomized.

如果订单应该随机化,则对阵列进行随机播放。

#1


0  

You are trying to get all possible permutations of -1, 0 and 1 with a length of 5 by sheer luck, which can take forever. There are 243 of them (3**5) indeed:

你试图通过纯粹的运气获得-1,0和1的所有可能的排列长度为5,这可能需要永远。确实有243个(3 ** 5):

coords = [-1,0,1].repeated_permutation(5).to_a 

Shuffle the array if the order should be randomized.

如果订单应该随机化,则对阵列进行随机播放。