简体   繁体   English

避免递归的最佳方法

[英]Optimal way to avoid a recursion for tree walking

so I am fairly new to javascript and I was trying to write a special shift scheduling code for a friend. 所以我对javascript还是很陌生,我试图为一个朋友编写一个特殊的班次调度代码。 The way it currently works is as follow : 当前的工作方式如下:

function walk(currentDay) {
    var today = allWorkDays[currentDay]; // An array of all workdays we need to schedule
    var vertices = fetchCombinationsForToday(today); // Fetch an array of 0 length or more
                                                // containing possibilities for the day
                                                // according to rules set by user
    for (var i=0; i<vertices.length; i++) {
         [we add the vertices[i] to a running array]
         walk(currentDay+1);
    }
    if (currentDay == sumOfAllDays) { // We are at a leaf
           analyzeSchedule(); // This will keep a copy of the current schedule 
                              // if it has a higher score than X
    }
    [some business to pop the last node/day we added to our global array]
}

Now the rules specified in the comments are rules that usually analyze the last 5-10 last added elements(days) and return what could be the shifts for today. 现在,注释中指定的规则是通常分析最近5-10个最后添加的元素(天)并返回今天的班次的规则。

The problem I have here is that I want the program to be able to come up with schedules even with an array of more than a thousand days, but I would exceed the function calls limit due to recursion. 我在这里遇到的问题是,我希望程序即使有超过一千天的数组也能够提出计划,但是由于递归,我将超出函数调用的限制。 Is there any way to walk a tree without using recursion in javascript? 有没有办法在不使用javascript递归的情况下走树? I can't seem to find one even though most say that problems solvable by recursion can be solved by loops and vice versa. 即使大多数人都说可以通过循环解决递归问题,反之亦然,我似乎找不到一个。

Keep in mind that the vertices array is big (20-30 elements) early in the tree but quickly gets small (0-5 elements). 请记住,顶点数组在树的开头很大(20-30个元素),但是很快变小了(0-5个元素)。 I never ran this code [EDIT: and got a "function calls limit reached" error] by the way it is all theory [EDIT: the fact that I will reach it] for now. 我从来没有运行过此代码[编辑:并达到了“函数调用限制已达到”错误],这是理论上的全部[编辑:我将达到它的事实]。

JavaScript Arrays provide methods to push/pop and shift/unshift values onto/off of their beginning and end, so you can use them like a queue. JavaScript数组提供了将值推入/弹出和将值移入/移出和移出它们的开始和结束的方法,因此您可以像使用队列一样使用它们。 For example: 例如:

var a = [0, 1, 2];
a.push(3); // => 3
a; // [0, 1, 2, 3]
a.shift(); // => 0
a; // [1, 2, 3]
a.pop(); // => 3
a; // [1, 2]

This way you can walk a tree structure and keep track of nodes to-be-visited by pushing and popping/unshifting from an array. 这样,您可以遍历树结构并通过从数组中推入和弹出/取消移动来跟踪要访问的节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM