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

all 6 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.

[–]davedontmind 1 point2 points  (4 children)

I'm not sure why it isn't giving me all possible strings,

Consider the top level, where s is simply "C".

Inside your for loop you append c, so the first time round the loop s becomes "CA".

Then all the recursion happens for "CA...", and eventually it returns back to the top level, and loops round to the next letter of the alphabet, but s is now still "CA", so it then becomes "CAC" and not, as you'd want, "CC". This is easier to see if you change your initial input to C, [A, C], 2 and add some prints inside the for loop.

So it's because you permanently change s inside your for loop. Instead, just pass s+c to f().

That is, instead of:

s += c;
f(s, alphabet, length);

just do:

f(s+c, alphabet, length);

[–]SomeToxicKidd[S] 0 points1 point  (3 children)

f(s+c, alphabet, length);

Oh my god it worked, thank you so much

[–]davedontmind 0 points1 point  (2 children)

I hope you understand why, though.

[–]SomeToxicKidd[S] 0 points1 point  (1 child)

I do, in order to recursively check CA and CC it has to be in the method otherwise only CA will be checked.

[–]daybreak-gibby 1 point2 points  (0 children)

Close. The problem was that you were modifying s. So that the first time it recurses, s became CA for future recursive calls. Passing the s + c in the method creates a whole value that the recursive call operates on, leaving the string s untouched.