Want to reduce number of for loop I used in the given link to create a func which returns mode for the given data

Below is the playground link to a program which gives mode('s) of the particular data_set
https://play.golang.org/p/rgZJhJ-gtY7

is there a way to optimize it more?

“I am doing it for practice data science with golang”

1 Like

second loop can be merged into first one `

package main
import "fmt"

type data []float64

func main() {
numFriends := []float64{100.0, 49, 41, 40, 25, 21, 21, 19, 19, 18, 18, 16, 15, 15, 15, 15, 14, 14, 13, 13, 13, 13, 12, 12, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
var mode []float64
m := make(map[float64]int)
// entering data to a map and creating counter
var maxFreq int
for _, i := range numFriends {
	m[i]++
	if m[i] > maxFreq {
		maxFreq = m[i]
	}
}

// getting the mode on the basis of max value in the map 
for i, _ := range m {
	if maxFreq == m[i] {
		mode = append(mode, i)
	}
}
fmt.Println(mode)

}
1 Like