프로그래밍/C#

N * M * K .. 다중 루프

흔한티벳여우 2021. 7. 5. 20:49
반응형
private static void Main()
{
    var data = new List<List<int>>
    {
        new List<int> {1, 2, 3},
        new List<int> {11, 12, 13, 14},
        new List<int> {21, 22, 23, 24},
        new List<int> { 31, 32, 33, 34 }
    };

    foreach (var item in IterateDynamicLoop(data))
    {
        foreach (var it in item)
        {
            Console.Write(it.ToString() + " ");
        }
        Console.WriteLine();
    }

    Console.ReadLine();
}

public static IEnumerable<IEnumerable<T>> IterateDynamicLoop<T>(IList<List<T>> data)
{
    var count = data.Count;

    var loopIndex = count - 1;
    var counters = new int[count];
    var bounds = data.Select(x => x.Count).ToArray();

    do
    {
        yield return Enumerable.Range(0, count).Select(x => data[x][counters[x]]);
    } while (IncrementLoopState(counters, bounds, ref loopIndex));
}

private static bool IncrementLoopState(IList<int> counters, IList<int> bounds, ref int loopIndex)
{
    if (loopIndex < 0)
        return false;

    counters[loopIndex] = counters[loopIndex] + 1;

    var result = true;

    if (counters[loopIndex] >= bounds[loopIndex])
    {
        counters[loopIndex] = 0;
        loopIndex--;
        result = IncrementLoopState(counters, bounds, ref loopIndex);
        loopIndex++;
    }

    return result;
}
반응형