可以简化此随机数生成器逻辑吗? [英] Can this random number generator logic be simplified?

查看:79
本文介绍了可以简化此随机数生成器逻辑吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习F#,想知道以下生成随机数的逻辑是否可以接受.

I am learning F# and would like to know if the following logic to generate random numbers is acceptable.

这可以更容易维护的方式编写吗?这段代码安全吗?

Could this be written in a more maintainable fashion? Is this code safe?

let hashset = System.Collections.Generic.HashSet<int>()
let mutable continueLooping = true

while (continueLooping) do 
   let value = System.Random().Next(0, 12)
   let success = hashset.Add(value)
   continueLooping <- hashset.Count <> 12

更新

let hashset = System.Collections.Generic.HashSet<int>()
let randomGenerator = System.Random()
let mutable continueLooping = true
let expectedLength = 12

while (continueLooping) do 
   let value = randomGenerator.Next(0, expectedLength)
   let success = hashset.Add(value)
   continueLooping <- hashset.Count <> expectedLength

推荐答案

您可以定义一个辅助函数来执行Fisher-Yates随机播放.这种随机播放功能通常非常有用,因为它可以在任何 seq<'a> 上运行,因此您有很多机会可以重用它.

You could define a helper function to perform a Fisher-Yates shuffle. This shuffle function is pretty generally useful since it will work on any seq<'a> so you have plenty of opportunities to reuse it.

// shuffle a sequence into random order
let shuffle xs =
    // swap two elements in the supplied array
    let swap i j (array : _[]) =
        let tmp = array.[i]
        array.[i] <- array.[j]
        array.[j] <- tmp
    let rnd = System.Random()
    let xArray = Seq.toArray xs
    let n = Array.length xArray
    for i in [0..(n-2)] do
        let j = rnd.Next(i, n-1)
        swap i j xArray
    xArray |> Seq.ofArray

然后只需将其应用于列表或使用

Then just apply it to a list or something using

let shuffledList = [0..11] |> shuffle |> Seq.toList

这篇关于可以简化此随机数生成器逻辑吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆