Skip to content

Instantly share code, notes, and snippets.

@narusemotoki
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save narusemotoki/ae81ff209975daa5cc0a to your computer and use it in GitHub Desktop.
Save narusemotoki/ae81ff209975daa5cc0a to your computer and use it in GitHub Desktop.
% for i in {1..100000}; do echo `od -An -N2 -l < /dev/urandom`; done > a
package main
import (
"fmt"
"strconv"
"bufio"
"io"
"os"
"testing"
)
func setup() []int {
res := make([]int, 0)
f, _ := os.Open("/var/tmp/a")
r := bufio.NewReader(f)
for line, _, err := r.ReadLine(); err!=io.EOF; line, _, err = r.ReadLine() {
s := string(line[:])
i, _ := strconv.Atoi(s)
res = append(res, i)
}
return res
}
func mode(arr []int) int {
f := func(arr []int) (max_key int, max_value int) {
for k, v := range arr {
if max_value < v {
max_key, max_value = k, v
}
}
return max_key, max_value
}
_, limit := f(arr)
r := make([]int, limit + 1)
for _, a := range arr {
r[a]++
}
mode, _ := f(r)
return mode
}
func BenchmarkMode(b *testing.B) {
arr := setup()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = mode(arr)
}
}
func main() {
arr := setup()
fmt.Println(mode(arr))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment