Permutation with no Repetition but Randomized
Interesting problem from a friend: permutation with no repetition but random without shuffling at the end (without extra memory). Same concept as standard permutation with no repetition, just randomly swap the direction of the sweep. Code is down below, cheers, ACC
private void PermutationNoRepetitionRandomOrder(string str, string currentStr, Hashtable indexVisited, Random rdObj) { if (currentStr.Length == str.Length) { Console.WriteLine(currentStr); return; } Hashtable localCharUsedAtPosition = new Hashtable(); int left = 0; int right = str.Length - 1; while (left <= right) { if (rdObj.Next(0, 2) == 0) { if (!indexVisited.ContainsKey(left) && !localCharUsedAtPosition.ContainsKey(str[left])) { localCharUsedAtPosition.Add(str[left], true); indexVisited.Add(left, true); PermutationNoRepetitionRandomOrder(str, currentStr + str[left].ToString(), indexVisited, rdObj); indexVisited.Remove(left); } left++; } else { if (!indexVisited.ContainsKey(right) && !localCharUsedAtPosition.ContainsKey(str[right])) { localCharUsedAtPosition.Add(str[right], true); indexVisited.Add(right, true); PermutationNoRepetitionRandomOrder(str, currentStr + str[right].ToString(), indexVisited, rdObj); indexVisited.Remove(right); } right--; } } }
Running against the input "yolo", you've got:
Comments
Post a Comment