# Calculate rang and derang of ordering of subsets

We have all the subsets of the set {1, 2, …, n} for some natural number n. We define the ordering of these subsets as follows:

• The empty set has rank 0.
• Following are all the sets whose smallest element is 1. These are first ordered by cardinality, and sets of the same cardinality are then ordered lexicographically.
• Following are all the sets whose smallest element is 2. These are first ordered by cardinality, and sets of the same cardinality are then ordered lexicographically. …
• Following are all the sets whose smallest element is n-1. These are first ordered by cardinality, and sets of the same cardinality are then ordered lexicographically.
• Following are all the sets whose smallest element is n. Thus, at the last position is the set {n}.

Example: n=4 Ordering of subsets: ∅, {1}, {1, 2}, {1, 3}, {1, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {1, 2, 3, 4}, {2}, {2, 3}, {2, 4}, {2, 3, 4}, {3}, {3, 4}, {4}

1. Write a method rang that returns the rank of a given subset according to the above ordering. You can use the function kSubsetLexRang(subset, k, n), which returns the rank of the k-subset of a set with n elements in lexicographic order.
2. Write a method derang that, given integers r and n, returns a subset of the set {1, 2, …, n} whose rank according to the above ordering is r. You can use the function kSubsetLexRang(r, k, n), which returns the derangement of the k-subset of a set with n elements in lexicographic order.

I can’t find any connection between the lexicographical ordering of the k-subsets of the n-tuple and this ordering. Any idea? Similarly with derang, I have no idea how to construct the corresponding set.