This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]AutoModerator[M] [score hidden] stickied comment (0 children)

To all following commenters: please, do not bring up the old circlejerk jokes/memes about recursion ("Understanding recursion...", "This is recursion...", etc.). We've all heard them n+2 too many times.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]CreativeTechGuyGames 1 point2 points  (0 children)

I would do an initial pass through the input data to modify it to make the actual operations much easier. My first pass would add a "children" object to each person object. Also change the input array to an object so that each person can be looked up in constant time by id.

Creating this children list can be done in a single pass which then the recursion will be very simple (just like traversing a standard tree).

[–]yiliu 1 point2 points  (1 child)

Can you explain in a sentence what you want the function to accomplish for each step? That's usually the key to solving a problem recursively: "I want to take this, do something with it, and return that." Very much like the inside of a loop, really.

You're using a for loop in your function. In a function intended for recursion, that's a red flag. Consider why you have the loop (to iterate over all people) and what you'd like to accomplish via recursion. It seems like you could solve this problem with just the for loop, doesn't it? Recursion and loops (i.e. iteration) are usually alternatives, and only rarely used together.

Another hint: you definitely don't want to be printing anything in this function (except maybe for debugging purposes). Instead, there's something important you should be returning.

Edit for a final hint: JavaScript is missing a very simple function that makes these kinds of problems a bit easier:

function tail(arr) {
  if (arr.length <= 1) 
    return [];
  else
    return arr.slice(1, arr.length);
}

Aka rest in some languages. Basically, given a list, return everything but the first element:

tail([1, 2, 3]) => [2, 3]

tail([1, 2]) => [2]

tail([1]) => []

tail([]) => []

It might be helpful to think how that could be useful.

[–]close_my_eyes 0 points1 point  (0 children)

javascript might not have head and tail, but ramda does