如何在数组中获得不同的随机数? [重复]

时间:2022-08-27 00:23:18

This question already has an answer here:

这个问题在这里已有答案:

I have this code -

我有这个代码 -

number1, number2, number3, number4, number5 = Array.new(5) { rand(99999)+1 }

How can I make sure that each number is unique? Also - is it possible to output all numbers as 5 digit? Like 00147 instead of 147?

如何确保每个数字都是唯一的?另外 - 是否可以将所有数字输出为5位数?比如00147而不是147?

Thanks for help!

感谢帮助!

3 个解决方案

#1


3  

list = []
(list << '%05i' % (rand(99999)+1)).uniq! while list.length < 5
number1, number2, number3, number4, number5 = list

#2


0  

This seems like the simplest approach to me. Each number is guaranteed to be unique.

这对我来说似乎是最简单的方法。每个号码都保证是唯一的。

array = (1...99999).to_a
unique_randoms = 5.times.map { '%05i' % array.delete_at(rand(array.length)) }

#3


0  

def get_unique_random(n)
  a = []
  while n > 0 do
    r = "%05d" % (rand(99999)+1)
    (a << r; n -= 1) unless a.include?(r)
  end
  a
end

get_unique_random(5)

[Edit: I fixed an error I had introduced with an edit. (Ever done that?) Previously I had:

[编辑:我修复了我在编辑时引入的错误。 (曾经这样做过?)以前我曾经:

r = rand(99999)+1;
(a << "%05d" % r; n -= 1) unless a.include?(r)

I will leave it as an exercise to spot the error.]

我会把它留作练习来发现错误。]

#1


3  

list = []
(list << '%05i' % (rand(99999)+1)).uniq! while list.length < 5
number1, number2, number3, number4, number5 = list

#2


0  

This seems like the simplest approach to me. Each number is guaranteed to be unique.

这对我来说似乎是最简单的方法。每个号码都保证是唯一的。

array = (1...99999).to_a
unique_randoms = 5.times.map { '%05i' % array.delete_at(rand(array.length)) }

#3


0  

def get_unique_random(n)
  a = []
  while n > 0 do
    r = "%05d" % (rand(99999)+1)
    (a << r; n -= 1) unless a.include?(r)
  end
  a
end

get_unique_random(5)

[Edit: I fixed an error I had introduced with an edit. (Ever done that?) Previously I had:

[编辑:我修复了我在编辑时引入的错误。 (曾经这样做过?)以前我曾经:

r = rand(99999)+1;
(a << "%05d" % r; n -= 1) unless a.include?(r)

I will leave it as an exercise to spot the error.]

我会把它留作练习来发现错误。]