Created
March 10, 2020 15:10
-
-
Save kentkost/a95c6dbb682f5b1796671d84b7227fb5 to your computer and use it in GitHub Desktop.
Unique permutations of a list of strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace PermutationsUnqiue | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
List<String> str = new List<string>() { "hello", "world", "hello" }; | |
List<string> results = new List<string>(); | |
int n = str.Count; | |
Permute(str, 0, n - 1, ref results); | |
Console.WriteLine("yeet"); | |
foreach (string s in results) { | |
Console.WriteLine(s); | |
} | |
Console.ReadKey(); | |
} | |
#region permutations | |
private static bool ShouldSwap(List<string> phr, int start, int curr) | |
{ | |
for (int i = start; i < curr; i++) { | |
if (phr[i] == phr[curr]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
private static List<string> Permutations(List<string> phrase) | |
{ | |
List<string> results = new List<string>(); | |
int n = phrase.Count; | |
Permute(phrase, 0, n - 1, ref results); | |
return results; | |
} | |
private static void Permute(List<string> phrase, int l, int r, ref List<string> results) | |
{ | |
if (l == r) { | |
results.Add(String.Join(" ", phrase.ToArray())); | |
} | |
else { | |
for (int i = l; i <= r; i++) { | |
bool check = ShouldSwap(phrase, l, i); | |
if (check) { | |
phrase = Swap(phrase, l, i); | |
Permute(phrase, l + 1, r, ref results); | |
phrase = Swap(phrase, l, i); | |
} | |
} | |
} | |
} | |
private static List<string> Swap(List<String> words, int i, int j) | |
{ | |
string temp; | |
temp = words[i]; | |
words[i] = words[j]; | |
words[j] = temp; | |
return words; | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment