Hi @Jay-R Hayashi , Welcome to Microsoft Q&A,
I still don't understand your question. Are you pursuing such code? You can use C#'s LINQ library to accomplish this task.
using System;
using System.Collections.Generic;
using System.Linq;
namespace xxx
{
internal class Program
{
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4 };
int limit = 2;//3
var permutations = GetPermutations(arr, limit);
foreach (var perm in permutations)
{
Console.WriteLine(string.Join(", ", perm));
}
Console.ReadLine();
}
static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> items, int limit)
{
if (limit <= 0 || items == null)
yield break;
var itemsList = items.ToList();
var indices = Enumerable.Range(0, itemsList.Count);
foreach (var indicesPerm in GetPermutations(indices, limit))
{
yield return indicesPerm.Select(i => itemsList[i]);
}
}
static IEnumerable<IEnumerable<int>> GetPermutations(IEnumerable<int> indices, int limit)
{
if (limit == 1)
{
foreach (var index in indices)
yield return new[] { index };
yield break;
}
var indicesList = indices.ToList();
var subPermutations = GetPermutations(indices, limit - 1);
foreach (var index in indicesList)
{
foreach (var subPerm in subPermutations)
{
if (!subPerm.Contains(index))
{
yield return subPerm.Append(index);
}
}
}
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.