-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
123 lines (96 loc) · 2.11 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"bufio"
"flag"
"io"
"log"
"math/rand"
"os"
"sort"
"strings"
"time"
)
var (
count = flag.Int("n", 1, "the number of names to pick from the list")
)
type person struct {
Name string
Score int
}
type byScore []person
func (a byScore) Len() int { return len(a) }
func (a byScore) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byScore) Less(i, j int) bool { return a[i].Score < a[j].Score }
func init() {
rand.Seed(time.Now().UnixNano())
}
func main() {
flag.Parse()
// open the list of names
// TODO: should be able to accept STDIN as well
f, err := os.Open("data/test_data.txt")
defer f.Close()
if err != nil {
log.Fatal(err)
}
// read the names into memory and assign each a random score
//r := bufio.NewReader(f)
// pick names from the list
//results, _ := pickRandom(*count, r)
results, _ := pickRandom2(*count, f)
// return the number of names requested
log.Printf("results: %d\n", len(results))
for c := 0; c < *count; c++ {
log.Printf("%s\n", results[c])
}
}
func pickRandom(n int, r *bufio.Reader) (p []string, e error) {
p = make([]string, n)
var list []person
for {
name, err := r.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
p := person{
Name: strings.TrimRight(name, "\n"),
Score: rand.Int(),
}
list = append(list, p)
}
// sort the list in ascending order
sort.Sort(byScore(list))
// return the number of names requested
for c := 0; c < *count; c++ {
p[c] = list[c].Name
}
return
}
func pickRandom2(n int, f *os.File) (p []string, e error) {
p = make([]string, n)
var list []string
r := bufio.NewReader(f)
lines := 0
for {
name, e := r.ReadString('\n')
if e == io.EOF {
break
}
list = append(list, strings.TrimRight(name, "\n"))
lines++
}
if *count > lines {
log.Fatalf("asking for more names (%d) than we have in the input file (%d)\n", *count, lines)
}
for c := 0; c < *count; c++ {
i := rand.Intn(len(list))
p[c] = list[i]
// delete value so it can't be selected again
list[i] = list[len(list)-1]
list = list[:len(list)-1]
}
return
}