How to resolve the algorithm Permutations step by step in the F# programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Permutations step by step in the F# programming language

Table of Contents

Problem Statement

Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!)

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Permutations step by step in the F# programming language

Source code in the fsharp programming language

let rec insert left x right = seq {
    match right with
    | [] -> yield left @ [x]
    | head :: tail -> 
        yield left @ [x] @ right
        yield! insert (left @ [head]) x tail
    }

let rec perms permute =
    seq {
        match permute with
        | [] -> yield []
        | head :: tail -> yield! Seq.collect (insert [] head) (perms tail)
    }
            
[<EntryPoint>]
let main argv = 
    perms (Seq.toList argv)
    |> Seq.iter (fun x -> printf "%A\n" x)
    0


let permutations xs = 
    let rec insert x = function
        | [] -> [[x]]
        | head :: tail -> (x :: (head :: tail)) :: (List.map (fun l -> head :: l) (insert x tail))
    List.fold (fun s e -> List.collect (insert e) s) [[]] xs


  

You may also check:How to resolve the algorithm Abelian sandpile model/Identity step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Mertens function step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Vala programming language
You may also check:How to resolve the algorithm Sorting algorithms/Selection sort step by step in the BASIC programming language
You may also check:How to resolve the algorithm Boolean values step by step in the Fantom programming language