Hi This function takes an array with some integers and my goal is to have a new array with just positive integers. However, I am keep getting the same error saying panic: runtime error: index out of range
Can anybody please help me..??
func domath(newarray[] int, i int, array[] int)([]int){
if i < len(newarray) {
if newarray[i] < 0{
i ++
domath(newarray, i, array)
}
if newarray[i] >= 0 {
array = append(array, newarray[i])
i ++
domath(newarray, i, array)
}
}
return array
}
Do you want write a recursive function?, you can see my code below :
func domath(newarray []int, i int, array []int) []int {
if i < len(array) {
if array[i] >= 0 {
newarray = append(newarray, array[i])
}
i++
} else {
return newarray
}
return domath(newarray, i, array)
}
The problem with that implementation is that it's incrementing i inside the first if block and then using the new i value to check newarray[i] >= 0 on the second if block, so when you call domath(a, x, b) with x = len(a)-1 it tries to do newarray[x+1] (i.e. newarray[len(newarray)]) which is out of bounds.
You probably meant to write something like:
func domath(newarray []int, i int, array []int) []int {
if i < len(newarray) {
if newarray[i] < 0 {
return domath(newarray, i+1, array)
}
if newarray[i] >= 0 {
array = append(array, newarray[i])
return domath(newarray, i+1, array)
}
}
return array
}
A simplified version of your algorithm could be:
func domath(newarray []int, i int, array []int) []int {
if len(newarray) == i {
return array
}
if newarray[i] >= 0 {
array = append(array, newarray[i])
}
return domath(newarray, i+1, array)
}
Yet you should probably be using an implementation more idiomatic like the following one, which will also be faster:
func domath(ns []int) []int {
var ps []int
for _, n := range ns {
if n >= 0 {
ps = append(ps, n)
}
}
return ps
}