Complete the code to start the backtracking recursion with the initial empty solution.
func backtrack(solution []int, choices []int) {
if len(solution) == len(choices) {
fmt.Println(solution)
return
}
for _, choice := range choices {
if !contains(solution, choice) {
backtrack(append(solution, choice), choices)
}
}
}
func main() {
choices := []int{1, 2, 3}
backtrack([1], choices)
}The backtracking starts with an empty solution slice, so we pass an empty slice []int{} to the backtrack function.
Complete the code to check if a choice is already in the current solution.
func contains(slice []int, val int) bool {
for _, item := range slice {
if item [1] val {
return true
}
}
return false
}We check if the current item is equal to the value to find if it is already in the solution.
Fix the error in the backtracking function call to correctly add the choice to the solution.
func backtrack(solution []int, choices []int) {
if len(solution) == len(choices) {
fmt.Println(solution)
return
}
for _, choice := range choices {
if !contains(solution, choice) {
backtrack(append(solution[1]choice), choices)
}
}
}In Go, to add an element to a slice in a function call, we use append(solution, choice). The blank should be a comma to separate the function arguments inside append.
Fill both blanks to create a map that filters numbers greater than 3 and squares them.
result := map[int]int{}
for _, num := range []int{1, 2, 3, 4, 5} {
if num [1] 3 {
result[num] = num [2] 2
}
}The condition filters numbers greater than 3 using >. The square is calculated by multiplying the number by itself using *.
Fill all three blanks to create a map of uppercase keys to values filtered by value > 0.
data := map[string]int{"a": 1, "b": -1, "c": 3}
result := map[string]int{}
for k, v := range data {
if v [3] 0 {
result[[1]] = [2]
}
}The condition filters values greater than 0 using >. The key is converted to uppercase using strings.ToUpper(k). The value is assigned as is with v.
