Better way of doing this exercise

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]

Is there a better way to do it?

2 Likes

You can simplify this way :

func main() {
  myslice := []float32{10.5, 75.5, 89.8, 90.0, 75.0}
  added := addIndexToValue(myslice)
  fmt.Printf("Original Slice = %v\nAdding Index = %v\n", myslice, added)
}

func addIndexToValue(orig []float32) ([]float32) {
  param := make([]float32, len(orig))
  for index, value := range orig {
     param[index] = value + float32(index)
  }
  return param
}
2 Likes

Yamil,
Thank you.

1 Like

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
}

And here’s the answer:

C:\Users\pritesh\go\src\github.com\pritesh-ugrankar\slices1>go run slices1.go
Orig : [10.5 20.5 30.5 40.5 50.5]
Added: [10.5 21.5 32.5 43.5 54.5]
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.