【问题标题】:Ruby how to generate a random number from a given numberRuby如何从给定数字生成随机数
【发布时间】:2015-07-23 11:10:47
【问题描述】:

我知道如何在 ruby​​ 中生成一个范围内的随机数:

rand(10..45)

但是如何从给定的数字中生成一个数字呢?

示例:

def generate_random_number(n)
  #what to put here
end

如果我跑步:

generate_random_number(123)

它将从给定的数字返回一个可能生成的数字数组:

[123, 321, 231, 132 etc ...]

有没有 ruby​​ 函数可以解决这个问题?

【问题讨论】:

    标签: ruby algorithm


    【解决方案1】:

    你要找的是permutation:

    123.to_s.chars.permutation.map {|a| a.join.to_i}
    # => [123, 132, 213, 231, 312, 321]
    

    如果你希望顺序是随机的,shuffle它:

    123.to_s.chars.permutation.map {|a| a.join.to_i}.shuffle
    # => [312, 123, 213, 132, 231, 321]
    

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 2021-05-31
      相关资源
      最近更新 更多