[Solved] How can I convert my for loop into a recursive algorithm?

You do it by actually using the i parameter. private static final String ALPHABET = “abcdefghijklmnopqrstuvwxyz”; public static void binary(int n, String str, int i) { if (i == ALPHABET.length()) return; if (n == 0) { System.out.println(str); return; } binary(n – 1, str + ALPHABET.charAt(i), 0); // next letter starts at beginning of alphabet binary(n, … Read more

[Solved] A program which is difficult

Essentially, your question is this: given a graph with nodes represented as indices and edges as index pairs, and given an index i that represents a node, find all nodes which are connected to the given node. UnionFind algorithm to find connected components over nodes with indices: Initialize an array father of size number of … Read more

[Solved] C# Dynamic for-loop

It can be done without recursion. var s = “A,B,C|1,2|a|u,v,w”; var u = s.Split(‘|’).Select(v => v.Split(‘,’)).ToList(); var buffer = new List<string>(); buffer.Add(“COMMAND “); while (u.Count > 0) { var t = from a in buffer from b in u.First() select a + ‘ ‘ + b; buffer = t.ToList(); u.RemoveAt(0); } The buffer list will … Read more

[Solved] Python recursion facts

1) A recursive solution has a few benefits. Generally it is more readable, and smaller in terms of lines of code. When it doesn’t work, it’s almost always harder to debug. It’s usually preferable when it runs faster than a non-recursive solution (see merge sort). 2) By definition. 3) True — the point of recursion … Read more

[Solved] Operations on Strings

If two strings are equal to each other. When comparing two strings, you have to pass in the strings. public static boolean isEquals(String a, String b) { if (a.length() != b.length()) return false; return isEquals(a, b, 0); } private static boolean isEquals(String a, String b, int index) { if (index >= a.length()) return true; if … Read more

[Solved] does cout before return statement of recursive function stops it?

The body of an if-statement can be either a compound statement, which is a list of statements surrounded by {}, or it is the single statement following the if‘s condition. That means that this code: if(n>=2) cout<<“number of times the function called: “<<endl; return n*factorial(n-1); is completely equivalent to: if(n>=2){ cout<<“number of times the function … Read more