Tag Archives: F-Sharp

Permutation Generation In F-Sharp

Someone asks you to generate all the perumtations from a set of objects and you might think that this is an easy problem  And it isn’t that challenging but I had to think about it for a bit to come up with away to do this.  I thought it would be fun to code this up in F# to see if my algorithm was correct and to learn about the language a bit more.

The algorithm I came up with is essentially a depth first search like approach.  Taking the first element and printing it and then moving it to the ancestor list and printing it with the next one and so on.  This will print the permutations in lexicographic order providing the input elements are sorted.  Here is the source code below.

#light
/// List printing function need a generic version
let ListPrinter format a n =
 printf  "%A. " n
 a|> List.iter (fun x -> (printf format x))
 printf "\n"

/// Print all the permutation of a list of elements
/// Algorithm Pseudo Code
/// PermutationGenerator(list items)
///    PermuationHelper([], items)
/// end
///
/// PermutationHelper(list ancestors, list descendants)
///  if descandants is null return
///  foreach descendant
///    newAncestors  = ancestors + descendant
///    print(newAncestors)
///    newDescandants = descendants - descendant
///    PernumationHelper(newAncestors, newDescandants)
///  end
/// end
let PermutationGenerator printer items =
 ///internal counter function
 let counter =
  let count = ref 0I
  fun () -> count.contents <- count.contents + 1I; !count
 /// Helper recursive function that does the work
 let rec PermutationHelper ancestors descendants =
  if ancestors <> [] then printer ancestors (counter())

  match descendants with
  | [] -> ()
  | y::ys -> let fn = (fun (front, back : 'a list) curr ->
                 let newFront = front @ [curr]
                 let newBack = back.Tail
                 let newAncestors = ancestors @ [curr]
                 let newDescendants = front @ newBack
                 PermutationHelper newAncestors newDescendants
                 (newFront, newBack))
   in List.fold_left fn ([],descendants) descendants |> ignore
 // call the nested function
 PermutationHelper [] items

let items = ["apple";"banana"; "canteloupe";]
 //"cherry"; "grape";"orange";
 //"peach";"pear"; "strawberry"]
let numbers = [ 1..5 ]

let chars = ['a'..'e']

let StringPrinter = ListPrinter "%s "
let NumericPrinter = ListPrinter "%d"
let CharPrinter = ListPrinter "%c"

let StringPermutations = PermutationGenerator StringPrinter
let NumericPermutations = PermutationGenerator NumericPrinter
let CharPermutations = PermutationGenerator CharPrinter

You can load the above into the F# interactive window and run the following command and see the following results.

> StringPermutations items;;
1I. apple
2I. apple banana
3I. apple banana canteloupe
4I. apple canteloupe
5I. apple canteloupe banana
6I. banana
7I. banana apple
8I. banana apple canteloupe
9I. banana canteloupe
10I. banana canteloupe apple
11I. canteloupe
12I. canteloupe apple
13I. canteloupe apple banana
14I. canteloupe banana
15I. canteloupe banana apple

Some of the more interesting parts as someone learning functional programming include the use of curried functions, the fold operator, and pattern matching.

PermutationGenerator is a generic function that can work with any list of items of  type a’ list as long as a corresponding printer for the items is supplied of type  a’ list -> bigint -> unit.  The basic algorithm is listed above PermutationGeneration in the comments.  Although, F# supports loops the functional way to iterate over elements is to use a function like map or fold, so the foreach loop is replaced by List.fold_left with fn essentially being the body of the loop.

I then build a ListPrinter function that takes a format string.  From this I create printers for three different types using partial application or currying, StringPrinter, NumericPrinter, and CharPrinter.  This allows the creation of three new more specialized functions from the ListPrinter.  Currying is also used to create three specific Permutation Generators, StringPermutations, NumericPermutations, CharPermutations from PermutationGenerator by applying the particular printer.

There are other techniques for generating permutations.  Some involve shuffling of positions of elements after selecting the number of items.  Another technique is to use factoradics which give a way to select elements or permutations based on the factorial number system.

Birthday Paradox and Probability of Collisions

The birthday paradox is the phenomenon where even with a small fraction of the number of days in the year the probability of two people having the same birthday becomes large.  For instance if there are 36 people in a room (10% of 365) there is a 83% probability that two of them have the same birthday.  With only 23 people we are already over 50%.

This same logic doesn’t only apply, though, to birthdays.  One can calculate the probability of collision for any set of elements given the number of samples.  For instance, assume you want to assign a unique number to each of your customers.  And let’s say you were going to choose the number at random from a huge pool of numbers say 999,999,999. If you anticipate having 100,000 customers then one would expect with probability 99.3% to sample a number that was previously sampled for another customer, even though you have only selected .01% of the available numbers. I thought it would be fun to write an F# program to calculate this.

The probability is calculated as follows P = 1 – Probability of no collisions

It is easier to calculate the probability that there aren’t collisions and subtract that from one. We can use simple counting principles to calculate the probability of choosing n samples without any collisions. For example if we have 365 days as the elements and we have 3 people (samples), then the first person has 365 possibble days he could choose without collision. The second person has 364 possible days out of 365 and the third 363 possible days. So

Probabiliby of No Collisions = (365/365)*(364/365)*(363/365)
and
Probabiliby of Collision = 1 – (365/365)*(364/365)*(363/365)

Here is the following code which implements the above algorithm in F#

let collisionProbability  elements samples =
 let probNthSample n =
  let a = (float  elements)
  let b = (float  (elements - n + 1))
  b / a
 let rec probNoCollision  counter answer =
  match counter with
  | 0 -> answer
  | _ -> probNoCollision (counter - 1) (answer *  (probNthSample counter))
 in
  1.0 - (probNoCollision samples 1.0)

Some things I like about F# are its terseness. You don’t have to provide type annotations for everything unlike in C# or Java. The compiler infers them based on how they are used. Here, I am also using nested functions, which are great for breaking up an algorithm into smaller bits while still maintaining the scope of the functions to where they will be used. Also, nested functions can use values in scope. For instance elements is not passed into probNthSample. This algorithm was coded using tail-recursion to iterate over the different samples. Typically one would use a loop for this in imperative programming, but in a functional style recursion is used more often. (One could also make a list of the samples and fold_left.) Tail-recursion prevents the stack size from growing by not keeping previously called procedures on the stack if there is no additional work to be done. In the inner probNoCollision method, this is the case. The last thing that is used here is pattern matching. Stylistically, I like pattern matching better than if statements.

The probNoCollision function calculates what it name says. It multiplies together the probability of all the samples not colliding.

probNthSample is a helper function which just gets a float of the probability of the nth sample not colliding. For instance, in the birthday problem for the 2nd sample this method would return 364/365.

The last step just returns 1-probNoCollision.

To run this you could load this in the F# interactive window. And then run the command
collisionProbability 365 23;;
collisionProbability 999999999 100000;;

I am really enjoying F# and OCAML programming so far. I will be posting an article soon on permutations that I also coded in F#. This will also be in a functional style and will show more techniques of code reuse that are powerful, that one doesn’t typically enjoy in languages like C#.

Update -

I have rewritten the above function in a more functional style.


let collisionProb2 elements samples =
 let probNoCollision answer n =
  let a = (float elements)
  let b = (float (elements - n + 1))
  answer * b / a
 let answer = seq { 1 .. samples } |> Seq.fold probNoCollision 1.0
 1.0 - answer

This version of the code is more succinct and uses the fold function, as opposed to explicitly recursing over the elements.