我需要帮助找到一种更简单的方法来遍历呈指数增长的列表,以找到用于代码出现的灯笼鱼的总数

I need help finding an easier way of going through an exponentially growing list to find the total count of lanternfish for advent of code

所以我目前正在研究代码答案显示的出现。这段代码有点笨拙。我想知道是否有人偶然知道编写代码的更简单方法?
(第 6 天 - 2021 年 - Adventofcode)

数据如下:3,4,3,1,2
以下是预期的答案:26984457539

public static List<string> Star()
    {
        StreamReader sr = new("./Data/2021/Day06.txt");
        string data = sr.ReadToEnd();
        sr.Close();
        List<int> allLanternCycle = Array.ConvertAll(data.Split(","), int.Parse).ToList();
        for (int i = 0; i < 256; i++)
        {
            for (int j = 0; j < allLanternCycle.Count; j++)
            {
                if (allLanternCycle[j] == 0)
                {
                    allLanternCycle[j] = 7;
                    allLanternCycle.Add(9);
                }
                allLanternCycle[j]--;
            }
        }



        return new List<string>() { "", "true" };
    }

每条灯笼鱼只有 9 种可能的状态,其中 1 种会立即“重置”,因此您只需要跟踪 有多少 条灯笼鱼处于其余 8 种状态中的每一种在任何给定时间。

这意味着您只需要一个包含 8 个计数器的数组即可解决对它们进行计数的问题:

var fishPerState = new long[8];
foreach(int state in Array.ConvertAll(data.Split(","), int.Parse))
{
    fishPerState[state - 1]++;
}

现在我们有了跟踪机制,我们需要一种方法来推进程序。每天,每条鱼都会更改为较低的状态(例如 8 -> 7),但状态 1 中的鱼除外,它将“重置并重新填充”:

for (int i = 0; i < 256; i++)
{
    // move all fish in states 2-8 to one state lower
    var temp = new long[8];
    Array.Copy(fishPerState, 1, temp, 0, 7);

    // reproduce
    temp[7] = fishPerState[0];

    // reset
    temp[5] += fishPerState[0];

    // assign new state counts to array variable
    fishPerState = temp;
}

现在您无需担心内存限制,因为无论您数多少灯笼鱼,您都只会使用 128 字节(8 长 * 8 字节 * 2 数组)内存。

如果目标计数超过 long (2^63-1) 的容量,请改用 BigInteger 数组元素类型:)