复杂决策树生成器

时间:2015-07-19 08:37:41

标签: c# algorithm data-structures tree generator

我试图编写一种二叉树,但它非常大,我不想把每个元素都保存在内存中。我希望在需要时使用生成器函数来构造每个节点。

树模拟游戏中的决策。游戏以 n 选项框架开始。玩家选择两个选项(不能相同),并使用不同的操作组合它们。因此,一个框架具有(n *(n-1))* t 可能的步骤,其中 t 是操作的数量。

做出决定后,会产生 n - 1 选项的新框架,其中上次选择的两个选项已被删除,但这些选项的结果已包含在内。现在可能的不同选择的数量为((n - 1)*(n - 2))* t 。此过程一直持续到当前帧中的选项数<= 1。

我希望以特定的方式遍历决策树中的所有可能路线 - 每条路线的完整遍历一直到最后一帧(其中 n = 1),然后继续下一条可能的路线,从最大的帧(大小= n )开始,但在每帧中进行下一系列选择。除了我在这里描述的内容之外,决策的结果对于这些目的并不重要。所有路线必须一直到最后一帧(其中 n = 1) - 我不需要包含部分遍历的路线。

我有以下代码,我想生成一个决策的地图。 :

public class PathStep
{
    public int FrameSize;
    public int Index1;
    public int Index2;
    public int Operation;

    public override string ToString()
    {
        return String.Format("F:{0} I1:{1} I2:{2} O{3}", this.FrameSize, this.Index1, this.Index2, this.Operation);
    }
}

public class Frame
{
    public int Size { get; private set; }

    public Frame(int size)
    {
        this.Size = size;
    }

    public IEnumerable<PathStep> AllPossibleSteps()
    {
        return this.step_helper(this.Size, 0);
    }

    private IEnumerable<PathStep> step_helper(int frame_size, int depth)
    {
        throw new NotImplementedException(); //TODO
    }


    private static IEnumerable<Frame> frames_in_game(int initial_frame_size)
    {
        for (var i = initial_frame_size; i > 0; i--)
            yield return new Frame(i);
    }

    private static IEnumerable<PathStep> steps_in_frame(int frame_size)
    {
        int op_count = Operation.Operations().Count();

        for (var first = 0; first < frame_size; first++)
        {
            for (var second = 0; second < frame_size - 1; second++)
            {
                for (var i = 0; i < op_count; i++)
                {
                    yield return new PathStep() { FrameSize = frame_size, Index1 = first, Index2 = second, Operation = i };
                }
            }
        }
    }



}

我如何填写我的step_helper方法来映射树中每个可能的决策变体,并按连续游戏的顺序产生它们?我需要涵盖所有可能的路线,yield return按顺序在给定路线中采取的每一步,但是我采取完整路线的顺序并不相关,只要我全部覆盖它们。

1 个答案:

答案 0 :(得分:0)

我重新思考了我的问题,并意识到以下几点:

如果 n *(n -1)* t = options_per_frame

然后我可以将每个路径表示为一个选项网格,(如果1个索引)从:

开始
   let t = 4

   n |n-1|t | n = ?
   1 |1  |1 | 6
   1 |1  |1 | 5
   1 |1  |1 | 4
   1 |1  |1 | 3
   1 |1  |1 | 2

其次是:

   n |n-1|t | n = ?
   1 |1  |1 | 6
   1 |1  |1 | 5
   1 |1  |1 | 4
   1 |1  |1 | 3
   1 |1  |2 | 2

结尾
   n |n-1|t | n = ?
   6 |5  |4 | 6
   5 |4  |4 | 5
   4 |3  |4 | 4
   3 |2  |4 | 3
   2 |1  |4 | 2

其中,单元格中的每个值都表示所选选项的索引/ id,并且标题指定可以放入单元格的最大值。所以,你可以把它想象成一个时钟 - 不同大小的“齿轮”用来相互旋转,这样变化会随着幅度的减小而逐渐降低。及时,1000ms“旋转”一秒,60秒“旋转”一小时,24小时“旋转”一天等等所以我创建了一个PathGrid类,它返回了网格的下一次迭代,这使我能够一直遵循每条路径,无需模拟树或使用递归。我上传了我的解决方案here

相关问题