Recursion Example
This page was last reviewed on Dec 15, 2021.
Dot Net Perls
Recursion. A recursive func calls itself. We can perform an exhaustive search (one that generates all possibilities) with recursion.
A possible use. Suppose we wish to find all possible 3-letter strings with a Go program. We can use recursion for this. We can recursively add letters.
An example program. To begin, we introduce an AddLetter method. This loops over all possible letters to add to a string. It converts them to strings, and appends them to a new string.
Then We call AddLetter() recursively to add more letters after we add a letter.
Finally When the length of the string passed into AddLetter() reaches 3, we have a completed string. We print it to the console.
package main import ( "fmt" ) func AddLetter(value string) { // If we have reached 3 letters, print the completed string. if len(value) == 3 { fmt.Println("Completed string:", value) return } // Loop over all lowercase ASCII chars. for i := 0; i < 26; i++ { // Get string from int. letter := string(97 + i) // Create new string with additional letter. valueTemp := value + letter // Add another letter using recursion. AddLetter(valueTemp) } } func main() { // Start with empty string. AddLetter("") }
[Omitted...] Completed string: zzs Completed string: zzt Completed string: zzu Completed string: zzv Completed string: zzw Completed string: zzx Completed string: zzy Completed string: zzz
Notes, recursion. With recursion, we can perform an exhaustive search. It is also possible to reduce the search by returning early, to avoid unneeded work.
In Go, we have support for recursion. We can call a method within its own body. This can be used to develop powerful brute-search algorithms.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 15, 2021 (edit link).
© 2007-2024 Sam Allen.