I'm new in Go programming, so how to implement recursion instead of a for loop in this code?
package main
import (
"fmt"
)
func main() {
var n int
fmt.Scan(&n)
set(n)
}
func set(n int) {
a := make([]int, n)
for i := 0; i < n; i++ {
fmt.Scan(&a[i])
}
fmt.Println(a)
}
I am not sure what you want to be recursive. But as I understand your question as changing a for-loop into a recursion, I made it into a tail recursion in a closure, in a functional programing style.
func set(n int) {
a := make([]int, n)
var setRecursive func(int) // declare a function variable, which take an int as param.
setRecursive = func(i int) { // set the function in closure, so a and n is available to it.
if i == 0 { // end point of the recursion, return.
return
}
Scan(&a[n-i]) // Use fmt.Scan out of playground
setRecursive(i - 1) // tail recursion.
}
setRecursive(n) // call the function, start the recursion.
fmt.Println(a)
}
If you want the matter simpler, you can remove the closure part and move the line Scan(&a[n-i])
behind the line setRecursive(n)
, Like below:
func SetRecursive(a []int, n int) {
if n==0 {
return
}
SetRecursive(a,n-1) // recurse first, so we can scan in the right order.
Scan(&a[n-1])
}
Playground: https://play.golang.org/p/0io190tyviE
My syntax may be a little off, so I commented what each line does. Essentially, you would get one item of the array each time, and attach an array of one smaller in front of it, which you get by getting a value and attaching an array of one smaller in front of that, until that value is 1 and you're just getting a value.
func set(n int) []int { // declare a function that takes an int as a parameter
// and returns an int array
var recRet = []int{} // need a temporary array to store return value
a := make([]int, 1) // make an array of one to get the value this iteration
if n < 1 { //should never be here but prevents looping
return nil // escape
}
if n > 1 { // if we're not in the base case
recRet = set(n-1) // recurse on a list one smaller and store it
}
fmt.Scan(&a[1]) // get the value for this iteration
fmt.Println(a) // print it
return append(a, recRet...)// send this value plus the values gotten from recursion
// back up
}