2020年5月30日土曜日

Go - Writing Programs in Go - 簡単な乱数生成器

Go Systems Programming: Master Linux and Unix system level programming with Go (Mihalis Tsoukalos(著)、Packt Publishing)のChapter 2(Writing Programs in Go)、Exercises 7.の解答を求めてみる。

コード

```package main

import (
"fmt"
"os"
"strconv"
"time"
)

func errPrintln(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

var seedN int

func seed(n int64) {
seedN = int(n)
}
func intn(n int) int {
if n <= 0 {
panic("intn(n int) n <= 0")
}
m := seedN % n
seedN = seedN*seedN + 1
if seedN < 0 {
seedN *= -1
}
return m
}
func random(min, max int) int {
return intn(max-min) + min
}
func main() {
MIN := 0
MAX := 0
TOTAL := 0
if len(os.Args) > 3 {
var err error
MIN, err = strconv.Atoi(os.Args[1])
errPrintln(err)
MAX, err = strconv.Atoi(os.Args[2])
errPrintln(err)
TOTAL, err = strconv.Atoi(os.Args[3])
errPrintln(err)
} else {
errPrintln(fmt.Errorf("Usage: %v MIX MAX TOTAL", os.Args[0]))
}
if MIN < 0 || MIN >= MAX {
errPrintln(fmt.Errorf("MIN >= 0 and MIN < MAX"))
}
seed(time.Now().UnixNano())
for i := 0; i < TOTAL; i++ {
myrand := random(MIN, MAX)
fmt.Print(myrand)
fmt.Print(" ")
}
fmt.Println()
}
```

```% ./random
Usage: ./random MIX MAX TOTAL
% ./random 0 a 10
strconv.Atoi: parsing "a": invalid syntax
% ./random 0 0 10
MIN >= 0 and MIN < MAX
% ./random 0 1 10
0 0 0 0 0 0 0 0 0 0
% ./random 0 2 10
0 1 0 1 0 1 0 1 0 1
% ./random 0 2 10
0 1 0 1 0 1 0 1 0 1
% ./random 0 2 10
0 1 0 1 0 1 0 1 0 1
% ./random 0 3 10
2 0 1 1 0 2 0 1 1 1
% ./random 0 3 10
1 0 2 1 1 1 2 0 0 0
% ./random 0 3 10
1 2 1 2 1 2 1 0 2 2
% ./random 0 3 10
0 1 2 0 0 1 2 2 1 0
% ./random 0 4 10
0 3 2 3 2 1 2 1 2 3
% ./random 5 10 10
5 8 6 7 7 5 8 5 9 8
% ./random 5 10 10
5 6 7 5 7 9 9 8 5 8
% ./random 95 105 10
95 96 99 98 99 102 95 102 103 104
% ./random 95 105 10
95 98 97 102 99 98 103 98 95 98
% ./random 95 105 10
95 102 95 100 103 98 99 96 95 104
% ./random 95 105 10
95 96 99 96 103 96 101 104 97 98
% ./random 95 105 10
95 96 103 104 103 102 103 100 97 96
%
```