最近再寫一個東西,不過很像是大學時代在練習的題目就是有一個字串 "abc" 我要得到所有的組合
也就是 "abc" , "acb" , "bac" , "bca" , "cab" , "cba" ,也就是有 n! 的組合,目前沒有想到比較快的方法
於是就是暴力破解,反正都寫了寫下程式碼吧

裡面我有用到 Interlocked,因為非同步的關係,我要計算總數量來驗證,所以可能會卡點速度
C# code:
static int CurrentCount = 0;
static void Main(){
var str = "abcedfghi_";
Stopwatch sp = new Stopwatch();
sp.Start();
Console.WriteLine(str.Length);
ListAllPossibleP(str.ToArray(), 0, str.Length);
Console.WriteLine("count:" + CurrentCount.ToString("#,##0"));
Console.WriteLine(sp.Elapsed);
}
public static void ListAllPossibleP(char[] chars, int start, int end)
{
char temp;
Parallel.For(start, end - 1, i =>
{
Parallel.For(i + 1, end, j =>
{
temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
ListAllPossibleP(chars, i + 1, end);
temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
});
});
Console.WriteLine(new String(chars));
Interlocked.Increment(ref CurrentCount);
}
很簡單就不贅述了
給一下我電腦的數據大概 10 個字的組合我電腦跑了 00:07:51.9577405,快八分鐘
跑出來總計有 3,628,800 ,就是 10! ,這就很好算了,筆記一下,之後需要用到就直接複製貼上
reference:
https://www.javatpoint.com/program-to-find-all-permutations-of-a-string