Skip to content

Instantly share code, notes, and snippets.

@rosalogia
Created April 10, 2021 03:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rosalogia/52a191e740cbf46926bf800acd1e994d to your computer and use it in GitHub Desktop.
Save rosalogia/52a191e740cbf46926bf800acd1e994d to your computer and use it in GitHub Desktop.
Short F# script to generate and count the number of simultaneously symmetric and anti-symmetric relations on a set A = {1, 2, 3, 4, 5}
module List =
// Some code for generating permutations of a list
// Please disregard it, I copied it off the internet :)
let rec permutations l =
let rec aux = function
| [] -> seq [List.empty]
| x :: xs -> Seq.collect (insertions x) (aux xs)
aux l |> Seq.toList
and insertions x = function
| [] -> [[x]]
| (y :: ys) as xs -> (x::xs)::(List.map (fun x -> y::x) (insertions x ys))
// Define a function on an integer n
// that generates a list of lists, each
// containing the elements of a relation
// of size n which is both symmetric
// and anti-symmetric
let relationsOfSize n =
[1..5] // For the list of numbers from 1 through 5 (similar to our set A)
|> List.permutations // Generate a list of permutations
|> List.map (List.take n // Take the first n elements of each permutation
>> List.sort) // ... and sort them all
|> List.distinct // Remove all the duplicates
// For the sake of outputting some interesting
// information, print out the various relations
// as well as the number of relations of each size
// from 0 through 5
[0..5]
|> List.map (fun i ->
let r = relationsOfSize i
printfn "Relations of size %i: %A\nQuantity: %i" i r (List.length r))
// Compute the max number of simultaneously
// symmetric and anti-symmetric relations
// of sizes 0 through 5 on a set of numbers 1
// through 5.
let maxRelations =
[0..5] // For the list of numbers 0 through 5
|> List.map relationsOfSize // Generate all simultaneously symmetric and anti-symmetric relations of corresponding size
|> List.concat // Combine the lists of lists of relations into one list of relations
|> List.length // and output the resulting list's length
// Print out the max number of relations, should be 32
printfn "%i" maxRelations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment