-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
116 lines (98 loc) · 1.83 KB
/
util.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
package main
import (
crand "crypto/rand"
"math/rand"
"strings"
)
func Abs(i int) int {
if i < 0 {
return -i
}
return i
}
func Max(a int, b int) int {
if a > b {
return a
}
return b
}
func Min(a int, b int) int {
if a < b {
return a
}
return b
}
func RandSeed() int64 {
rbuf := make([]byte, 4)
_, err := crand.Read(rbuf)
if err != nil {
panic(err)
}
var seed int64 = int64(rbuf[0])<<24 + int64(rbuf[1])<<16 + int64(rbuf[2])<<8 + int64(rbuf[3])
return seed
}
// random value from [a, b]
func RandRange(r *rand.Rand, a, b int) int {
return r.Intn(b-a+1) + a
}
func ChoosePlaneType(r *rand.Rand, a []*PlaneType) *PlaneType {
count := 0
for _, e := range a {
count += e.weight
}
val := r.Intn(count)
for _, e := range a {
val -= e.weight
if val < 0 {
return e
}
}
panic("should not happen")
}
func ChooseRoute(r *rand.Rand, a []Route) Route {
count := 0
for _, e := range a {
count += e.weight
}
if count == 0 {
panic("no route to choose from")
}
val := r.Intn(count)
for _, e := range a {
val -= e.weight
if val < 0 {
return e
}
}
panic("should not happen")
}
// split and deindent lines (1st line as reference)
func SplitLines(s string) []string {
lines := strings.Split(s, "\n")
for lines[0] == "" {
lines = lines[1:]
}
l0 := lines[0]
var deindent int
for deindent = 0; deindent < len(l0) && l0[deindent] == ' '; deindent += 1 {
}
for n, _ := range lines {
if len(lines[n]) >= deindent {
lines[n] = lines[n][deindent:]
} else {
lines[n] = ""
}
}
return lines
}
func FirstRune(s string) rune {
for _, r := range s {
return r
}
return 0
}
const PAD_SPACE = " "
func Pad(width int, left string, right string) string {
pad := Max(0, width-len(left)-len(right))
return left + PAD_SPACE[0:pad] + right
}