• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Programming: Help With Recursive Function

Yes, its for homework, so if you don't want to help thats fine.

The problem is more specific, but basically I need to write a recurisive algorithm that searches for a substring in an array and returns the leftmost occurrence if it is present.

Right now, the only thing I can think of is just using recursion to mimic a for loop and compare. Im really trying to find a way where I dont have to look at each character... any ideas? I dont need the algorithm, just suggestions.
 
Your function should:

check the array to see if it begins with the substring.
If so, return the string. If not, pop the first character off the array, and run again with the new shorter string.

It returns when it matches the string or the array length is 0.
 
You could also simulate a tree structure by doing a divide and conquer type of thing. The recursive step can test to see if the String that your dealing with has 2 characters. If it doesn't, split the String in 2 and process the left String by calling the same string recursively.

notfred's solution would be the right way to do it though 😀
 
Originally posted by: notfred
Your function should:

check the array to see if it begins with the substring.
If so, return the string. If not, pop the first character off the array, and run again with the new shorter string.

It returns when it matches the string or the array length is 0.
This is basically what I had in mind initially, I was just looking for a less "linear" solution. That is how I would solve it iteratively, so I figured it wasn't the best recursive solution.
 
Originally posted by: HardcoreRobot
Originally posted by: notfred
Your function should:

check the array to see if it begins with the substring.
If so, return the string. If not, pop the first character off the array, and run again with the new shorter string.

It returns when it matches the string or the array length is 0.
This is basically what I had in mind initially, I was just looking for a less "linear" solution. That is how I would solve it iteratively, so I figured it wasn't the best recursive solution.

Honestly, it sounds like a stupid assignment to teach recusion, IMO. Just do it the pseudo-iteratively way.
 
What do you store in trees?

It's not the type of data that you're storing, it's what you want to do with it and the performance that you need that dictates the structure.

 
Back
Top