Here is one of C # that should work even with duplicate characters. For example, on a "banana" for permutations of length 2 it gives:
ba bn ab aa an nb na nn
The basic idea is to correct the first character, then form all permutations of length k-1, and then add the character to these permutations of length k-1. To deal with duplicate characters, we track the counter on the left (i.e. the one that can be used for permutations).
Not sample code, but should give you this idea. (If you find errors, let me know and I can edit).
static List<string> Permutations(Dictionary<char, int> input, int length) { List<string> permutations = new List<string>(); List<char> chars = new List<char>(input.Keys);
And here is the complete program that I use:
using System; using System.Collections.Generic; namespace StackOverflow { class Program { static void Main(string[] args) { List<string> p = Permutations("abracadabra", 3); foreach (string s in p) { Console.WriteLine(s); } } static List<string> Permutations(string s, int length) { Dictionary<char, int> input = new Dictionary<char, int>(); foreach (char c in s) { if (input.ContainsKey(c)) { input[c]++; } else { input[c] = 1; } } return Permutations(input, length); } static List<string> Permutations(Dictionary<char, int> input, int length) { List<string> permutations = new List<string>(); List<char> chars = new List<char>(input.Keys); if (length == 0) { permutations.Add(string.Empty); return permutations; } foreach (char c in chars) { if (input[c] > 0) { input[c]--; List<string> subpermutations = Permutations(input, length - 1); input[c]++; foreach (string s in subpermutations) { permutations.Add(s.Insert(0,new string(c,1))); } } } return permutations; } } }
Aryabhatta
source share