It is not hard to shuffle an array
in O(n), with in place swapping,
How to do it for list
in OCaml, with O(n)?
Requirement:
No array or in place usage
Consider this as an interview question
rev ( List. map f l) , but is tail-recursive and more efficient. filter_map f l applies f to every element of l , filters out the None elements and returns the list of the arguments of the Some elements.
Randomly shuffling the data first is a quick way of ensuring that you really do end up with all cases turning up with equal probability, and therefore that this worst case will be as rare as any other case.
List. map returns a new list formed from the results of calling the supplied function.
Lists are immutable, and there's often a log n price to pay for working with immutable data. If you're willing to pay this cost, there's an obvious n log n approach: tag each list element with a random value, sort based on random value, remove random values. This is the way I shuffle lists in my production code.
Here is the shuffle code from the iOS apps that I sell:
let shuffle d =
let nd = List.map (fun c -> (Random.bits (), c)) d in
let sond = List.sort compare nd in
List.map snd sond
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With