Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I noticed that your updated getPerms function contains duplicates. Here's my crack at a dupe-free version. Hopefully the comments speak for themselves. The hardest part was writing an efficient <code>distrib</code> function, because the concatenation operator has to be used somewhere. Luckily it's only used on small sublists, so the performance remains reasonable. My getAllPerms code below generates all permutations of [1..9] in around a quarter of a second, all 10-element permutations in around 2.5 seconds.</p> <p><em>Edit: funny, I didn't look at Tomas' code, but his combinations function and my picks function are nearly identical.</em></p> <pre><code>// All ordered picks {x_i1, x_i2, .. , x_ik} of k out of n elements {x_1,..,x_n} // where i1 &lt; i2 &lt; .. &lt; ik let picks n L = let rec aux nleft acc L = seq { match nleft,L with | 0,_ -&gt; yield acc | _,[] -&gt; () | nleft,h::t -&gt; yield! aux (nleft-1) (h::acc) t yield! aux nleft acc t } aux n [] L // Distribute an element y over a list: // {x1,..,xn} --&gt; {y,x1,..,xn}, {x1,y,x2,..,xn}, .. , {x1,..,xn,y} let distrib y L = let rec aux pre post = seq { match post with | [] -&gt; yield (L @ [y]) | h::t -&gt; yield (pre @ y::post) yield! aux (pre @ [h]) t } aux [] L // All permutations of a single list = the head of a list distributed // over all permutations of its tail let rec getAllPerms = function | [] -&gt; Seq.singleton [] | h::t -&gt; getAllPerms t |&gt; Seq.collect (distrib h) // All k-element permutations out of n elements = // all permutations of all ordered picks of length k combined let getPerms2 n lst = picks n lst |&gt; Seq.collect getAllPerms </code></pre> <p><em>Edit: more code in response to comments</em></p> <pre><code>// Generates the cartesian outer product of a list of sequences LL let rec outerProduct = function | [] -&gt; Seq.singleton [] | L::Ls -&gt; L |&gt; Seq.collect (fun x -&gt; outerProduct Ls |&gt; Seq.map (fun L -&gt; x::L)) // Generates all n-element combination from a list L let getPermsWithRep2 n L = List.replicate n L |&gt; outerProduct </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload