Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shuffle list in O(n) in OCaml?

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:

  1. No array or in place usage

  2. Consider this as an interview question

like image 845
Jackson Tale Avatar asked Feb 26 '13 17:02

Jackson Tale


People also ask

What is list Rev in Ocaml?

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.

Why does Quicksort shuffle?

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.

What does list map do in Ocaml?

List. map returns a new list formed from the results of calling the supplied function.


1 Answers

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
like image 101
Jeffrey Scofield Avatar answered Sep 19 '22 05:09

Jeffrey Scofield