周末在家,忽然想到洗牌排牌问题,那用于双色球上就是如何随机取出不重复的数字,目前想到最简单的 ruby 写法如下:
class ColourBalls
def self.pick
red_balls = (1..33).to_a
blue_balls = (1..16).to_a
picked_balls = []
picked_balls << red_balls.sample(6).sort
picked_balls << blue_balls.sample(1).first
picked_balls
end
end
5.times { p ColourBalls.pick } 运行效果如下 $ ruby color_balls_v1.rb [[2, 4, 5, 6, 11, 32], 7] [[6, 14, 20, 22, 23, 28], 9] [[1, 7, 8, 10, 14, 18], 13] [[1, 3, 7, 18, 27, 30], 3] [[2, 5, 8, 9, 13, 27], 10]
大家有更好的写法吗?