Skip to content

Commit e3f4535

Browse files
committed
Generate random number using LCG.
1 parent fa804f7 commit e3f4535

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Problems/generate_random_number.rb

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# ref: https://rosettacode.org/wiki/Linear_congruential_generator
2+
# Linear congruential generator Rn+1 = A * Rn + C (mod M)
3+
4+
module LCG
5+
module Common
6+
# The original seed of this generator.
7+
attr_reader :seed
8+
9+
# Creates a linear congruential generator with the given _seed_.
10+
def initialize(seed)
11+
@seed = @r = seed
12+
end
13+
end
14+
15+
# LCG::Berkeley generates 31-bit integers using the same formula
16+
# as BSD rand().
17+
class Berkeley
18+
include Common
19+
def rand
20+
@r = (1103515245 * @r + 12345) % 0x7fff_ffff
21+
end
22+
end
23+
24+
# LCG::Microsoft generates 15-bit integers using the same formula
25+
# as rand() from the Microsoft C Runtime.
26+
class Microsoft
27+
include Common
28+
def rand
29+
@r = (214013 * @r + 2531011) % 0x7fff_ffff
30+
@r >> 16
31+
end
32+
end
33+
end
34+
35+
@random = LCG::Microsoft.new(Time.now.to_i)
36+
def rand5
37+
@random.rand % 5
38+
end
39+
40+
p [rand5, rand5, rand5, rand5]
41+
42+
def rand7
43+
@random.rand % 7
44+
end
45+
46+
p [rand7, rand7, rand7, rand7]
47+
p [rand(7), rand(7), rand(7), rand(7)]

0 commit comments

Comments
 (0)