[英]Recursion - javascript
I am trying to solve an extra credit problem using recursion. 我正在尝试使用递归解决额外的信用问题。 Basically there is a "tree" that has matching "leaves" and I need to use recursion to check those matching leaves and return true if they match and return false if they do not.
基本上,有一棵具有匹配的“叶子”的“树”,我需要使用递归来检查那些匹配的叶子,如果匹配则返回true,否则返回false。
I have no idea how to do this and no materials I can find are helping me understand recursion any better. 我不知道该怎么做,没有资料可以帮助我更好地理解递归。 This is for an online program to learn how to program.
这是用于在线程序的学习程序的方法。
Any help would be appreciated! 任何帮助,将不胜感激!
Psuedo:
// initialize some value
// initialize some flag.. boolean
// initialize some helper function and pass obj...leaf checker recursive function
// check all the keys ...for loop/forEach
// if a key is an object && value is undefined
// assign value
// return
// if a value is an object ==> recurse
// if a value is found and it doesn't match our initial value
// trip our flag to false
// return
// return true or false
const checkMatchingLeaves = (obj) => {
};
My attempt: 我的尝试:
const checkMatchingLeaves = (obj) => {
// return true if every property on `obj` is the same
// otherwise return false
let checker = Object.values(obj);
if (Object.values(obj).length === 1) return true;
if (checker.map(checker[i] === checker[i + 1])) {
i > checker.length; i++;
}
};
This isn't exactly what (I think) you're asking for, but you should be able to use it as a template to figure out what to do: 这是不是你要求什么 (我认为),但你应该能够使用它作为模板来弄清楚该怎么做:
// searchTree takes a value to try to match and an array/primitive
// value.
function searchTree(val, node) {
// Check if it's a value or an array. If it's a value we can
// do the test and return, otherwise we recursively call
// searchTree on all the children.
// Array.some returns true if any of the function calls return
// true. This is a shorthand for your boolean flag: it lets us
// return early as soon as we find a match.
return Array.isArray(node) ?
node.some(child => searchTree(val, child)) : // recursive call
val === node;
}
searchTree(3, [1, 2, [8], [[[3]]]]); // true
searchTree('abc', 'a'); // false
searchTree('abc', ['ab', 'bc', ['abc']]); // true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.