在Ruby中生成不等于其他数字的数字?

时间:2022-11-04 13:03:06

Basically I am generating numbers and they can't be equal to any other numbers I've generated. Is there a quicker way to do this because it looks slightly ridiculous.

基本上我在生成数字它们不能等于我生成的任何其他数字。有没有一种更快的方法,因为它看起来有点可笑。

Thanks

谢谢

#possible generated values
x1 = 0
x2 = 1
x3 = 2

#generate co-ordinates
x4 = rand(7)
until x4 != x1 && x4 != x1+1 && x4 != x1+2 && x4 != x2 && x4 != x2+1 && x4 != x2+2 && x4 != x3 && x4 != x3+1 && x4 != x3+2 do
  x4 = rand(7)
end

#possible generated values
y1 = 0
y2 = 1
y3 = 2

y4 = rand(7)
until y4 != y1 && y4 != y1+1 && y4 != y1+2 && y4 != y2 && y4 != y2+1 && y4 != y2+2 && y4 != y3 && y4 != y3+1 && y4 != y3+2 do
  y4 = rand(7)
end

1 个解决方案

#1


6  

For Ruby 1.9+

Ruby 1.9 +

(0..6).to_a.sample(x)

or for older versions

或旧版本

(0..6).to_a.shuffle.take(x)

where x is the number of integers you want to take. Since rand(7) does not include the number 7, you need your range to be one less than the number you'd pass to rand.

其中x是要取的整数的个数。由于rand(7)不包含数字7,所以您需要您的范围小于您传递给rand的数字。

And obviously you can't take more numbers than are in the range.

显然,你不能取比范围更大的数。

#1


6  

For Ruby 1.9+

Ruby 1.9 +

(0..6).to_a.sample(x)

or for older versions

或旧版本

(0..6).to_a.shuffle.take(x)

where x is the number of integers you want to take. Since rand(7) does not include the number 7, you need your range to be one less than the number you'd pass to rand.

其中x是要取的整数的个数。由于rand(7)不包含数字7,所以您需要您的范围小于您传递给rand的数字。

And obviously you can't take more numbers than are in the range.

显然,你不能取比范围更大的数。