SquareOrSquareRoot
should get an array of integers and return a new array. If the number at index i
is a "square" number the returned array at index i
should have its square root. If the original number is not a "square" number then the returned array in index i
should be the number squared.
Coming from Python (where this could be done in a single line using list comprehension or using map
), I find it very odd that this is probably one of the shortest ways to achieve that in Go (please prove me wrong).
package main
import (
"fmt"
"math"
)
func SquareOrSquareRoot(arr []int) []int{
arr_to_return := make([]int, len(arr))
for index, value := range arr {
val_sqrt := math.Sqrt(float64(value))
if val_sqrt == math.Trunc(val_sqrt) {
arr_to_return[index] = int(val_sqrt)
} else {
arr_to_return[index] = value * value
}
}
return arr_to_return
}
func main() {
arr := []int{100, 101, 5, 5, 1, 1}
fmt.Println(SquareOrSquareRoot(arr))
// [10 10201 25 25 1 1]
}