Hi,
I’m trying to solve an exercise where, given a slice, a function should be written that will print the original slice, and in the next line, it will print the slice element+index number.
Here’s how I have done it:
package main
import "fmt"
func main() {
myslice := []float32{10.5, 75.5, 89.8, 90.0, 75.0}
original, added := addIndexToValue(myslice)
fmt.Printf("Original Slice = %v\nAdding Index = %v\n", original, added)
}
func addIndexToValue(param []float32) ([]float32, []float32) {
orig := make([]float32, len(param))
copy(orig, param)
for index, value := range param {
orig[index] = value
param[index] = value + float32(index)
}
return orig, param
}
And here is the output I get:
pritesh@debian:~/go/src/github.com/pritesh-ugrankar/slices1$ go run slices1.go
Original Slice = [10.5 75.5 89.8 90 75]
Adding Index = [10.5 76.5 91.8 93 79]
Hi Yamil,
Here’s another way I found. The restriction for the exercise was that the returning values of the function must contain both the original value and the value after adding index to the value.
package main
import "fmt"
func main() {
mySlice := []float32{10.5, 20.5, 30.5, 40.5, 50.5}
origMySlice, indexAddedMyslice := addIndexToValue(mySlice)
fmt.Printf("Orig : %v\nAdded: %v\n", origMySlice, indexAddedMyslice)
}
func addIndexToValue(orig []float32) ([]float32, []float32) {
param := make([]float32, len(orig))
for index, _ := range param {
param[index] = orig[index] + float32(index)
}
/*
Could also be written as this:
for index, value := range orig {
param[index] = value + float32(index)
}
*/
return orig, param
}