Ranking and unranking permutations with applications