简体   繁体   中英

How to avoid a specific number when creating a random number in F#?

I'm trying to generate a random number from 0 to 3 for each direction - n, e, s, w. Whatever the previous direction was in the recursive function can't be used again, and I'm trying to figure out the best way to do that. I'd also like to avoid using mutables. Below is what I have so far and it will work but I'm sure there is a better way to do this...

open System

let width = Console.WindowWidth
let height = Console.WindowHeight
let (map: int[,]) = Array2D.zeroCreate width height
let random = Random()

let main x y d =
    let mutable nd = random.Next(4)
    while nd = d do
        nd <- random.Next(4)

You only want one of 3 values:

let nd1 = random.Next 3
let nd = if nd1 >= d then nd1 + 1 else nd1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM