구 CircleMud 현 tbaMud의 C로 작성된 dice 함수를 Go언어 코드로 작성한 함수입니다. tbaMud 라이선스는 아래 링크를 참고 바랍니다.
과거에는 GPL 비슷한 라이선스로 봤었는데.. 일부 소스를 타 언어로 포팅한다던지 하는 경우에 오픈소스여야 한다던가 하는 조항이 어디갔는지를 모르겠네요 ;;
여튼 참고만 하시고 상용 프로젝트나 라이선스에 민감한 케이스에는 사용을 자제하시기 바랍니다.
Go
package main
import "time"
//
// random util from tbaMud
//
type dice struct {
randM int64
randQ int64
randA int64
randR int64
randSeed int64
}
func newDice() *dice {
nd := dice{}
nd.init()
return &nd
}
func (d *dice) init() {
d.randM = 2147483647
d.randQ = 127773
d.randA = 16807
d.randR = 2836
d.randSeed = time.Now().Unix()
}
func (d *dice) random() int64 {
hi := d.randSeed / d.randQ
lo := d.randSeed % d.randQ
test := d.randA*lo - d.randR*hi
if test > 0 {
d.randSeed = test
} else {
d.randSeed = test + d.randM
}
return d.randSeed
}
func (d *dice) randNumber(from int64, to int64) int64 {
if from > to {
tmp := from
from = to
to = tmp
}
return ((d.random() % (to - from + 1)) + from)
}
func (d *dice) dice(num int64, size int64) int64 {
var sum int64
sum = 0
if size <= 0 || num <= 0 {
return 0
}
for {
if num <= 0 {
break
}
sum += d.randNumber(1, size)
num--
}
return sum
}
사용법은 다음과 같습니다.
Go
d := newDice()
// 6면 주사위를 1번 굴림
d.dice( 1, 6 )
// 6면 주사위를 10번 굴린 합
d.dice( 10, 6 )
// 1 ~ 10 중에 랜덤
d.randNumber( 1, 10 )