F# 这个随机数发生器逻辑可以简化吗?
我正在学习F#,想知道以下生成随机数的逻辑是否可以接受 是否可以以更易于维护的方式编写? 这个密码安全吗F# 这个随机数发生器逻辑可以简化吗?,f#,F#,我正在学习F#,想知道以下生成随机数的逻辑是否可以接受 是否可以以更易于维护的方式编写? 这个密码安全吗 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
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()
让可变的continueLooping=true
当(继续)做的时候
让value=System.Random().Next(0,12)
让success=hashset.Add(值)
continueLooping您可以定义一个helper函数来执行Fisher-Yates洗牌。这个shuffle函数通常非常有用,因为它适用于任何seq您可以定义一个助手函数来执行Fisher-Yates shuffle。这个洗牌函数通常非常有用,因为它可以处理任何序列。这难道不是创建包含[0..11]
的集合的一种低效方法吗?不,因为它可能包含重复。我想要唯一的数字。再一次,我只是想寻求指导…oops的可能重复是的-我看到太晚了-确实有点奇怪,你从散列集中的0..11
中提取12个随机数,这将失去这些随机数的任何顺序这难道不是创建包含[0..11]
的集合的一种低效方法吗?不,因为它可能包含重复。我想要唯一的数字。再一次,我只是想寻求指导…oops的可能重复是的-我看到太晚了-在散列集中从0..11
中提取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
// 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
let shuffledList = [0..11] |> shuffle |> Seq.toList