Created
November 16, 2023 13:41
-
-
Save nordinrahman/665da41dbdbec79af51df1b77f039ab7 to your computer and use it in GitHub Desktop.
Get permutation of array, and take out only array with specified length
This file contains 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
IEnumerable<IList<Type>> GetPermutations(IList<Type> arraySource, int takeArrayLength) | |
{ | |
// Short circuit process if take array length is 0 | |
if (takeArrayLength == 0) | |
{ | |
yield return Array.Empty<Type>(); | |
yield break; | |
} | |
var uniqueValues = new List<string>(); | |
var array = arraySource.OrderBy(x => x.Name).ToList(); | |
while (array.Count > 0) | |
{ | |
var i = array.Count - 1; | |
var j = array.Count - 1; | |
var k = array.Count - 1; | |
while (i > 0 && string.CompareOrdinal(array[i - 1].Name, array[i].Name) >= 0) | |
{ | |
i--; | |
} | |
if (i <= 0) | |
{ | |
break; | |
} | |
while (string.CompareOrdinal(array[j].Name, array[i - 1].Name) <= 0) | |
{ | |
j--; | |
} | |
var temp = array[i - 1]; | |
array[i - 1] = array[j]; | |
array[j] = temp; | |
k = array.Count - 1; | |
while (i < k) | |
{ | |
temp = array[i]; | |
array[i] = array[k]; | |
array[k] = temp; | |
i++; | |
k--; | |
} | |
var value = new Type[takeArrayLength]; | |
array.CopyTo(0, value, 0, takeArrayLength); | |
var uniqueValue = string.Join(",", value.Select(x => x.Name)); | |
if (uniqueValues.Contains(uniqueValue)) continue; | |
uniqueValues.Add(uniqueValue); | |
yield return value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment