random.nim 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Nim's standard random number generator.
  10. ##
  11. ## Its implementation is based on the ``xoroshiro128+``
  12. ## (xor/rotate/shift/rotate) library.
  13. ## * More information: http://xoroshiro.di.unimi.it/
  14. ## * C implementation: http://xoroshiro.di.unimi.it/xoroshiro128plus.c
  15. ##
  16. ## **Do not use this module for cryptographic purposes!**
  17. ##
  18. ## Basic usage
  19. ## ===========
  20. ##
  21. ## To get started, here are some examples:
  22. ##
  23. ## .. code-block::
  24. ##
  25. ## import random
  26. ##
  27. ## # Call randomize() once to initialize the default random number generator
  28. ## # If this is not called, the same results will occur every time these
  29. ## # examples are run
  30. ## randomize()
  31. ##
  32. ## # Pick a number between 0 and 100
  33. ## let num = rand(100)
  34. ## echo num
  35. ##
  36. ## # Roll a six-sided die
  37. ## let roll = rand(1..6)
  38. ## echo roll
  39. ##
  40. ## # Pick a marble from a bag
  41. ## let marbles = ["red", "blue", "green", "yellow", "purple"]
  42. ## let pick = sample(marbles)
  43. ## echo pick
  44. ##
  45. ## # Shuffle some cards
  46. ## var cards = ["Ace", "King", "Queen", "Jack", "Ten"]
  47. ## shuffle(cards)
  48. ## echo cards
  49. ##
  50. ## These examples all use the default random number generator. The
  51. ## `Rand type<#Rand>`_ represents the state of a random number generator.
  52. ## For convenience, this module contains a default Rand state that corresponds
  53. ## to the default random number generator. Most procs in this module which do
  54. ## not take in a Rand parameter, including those called in the above examples,
  55. ## use the default generator. Those procs are **not** thread-safe.
  56. ##
  57. ## Note that the default generator always starts in the same state.
  58. ## The `randomize proc<#randomize>`_ can be called to initialize the default
  59. ## generator with a seed based on the current time, and it only needs to be
  60. ## called once before the first usage of procs from this module. If
  61. ## ``randomize`` is not called, then the default generator will always produce
  62. ## the same results.
  63. ##
  64. ## Generators that are independent of the default one can be created with the
  65. ## `initRand proc<#initRand,int64>`_.
  66. ##
  67. ## Again, it is important to remember that this module must **not** be used for
  68. ## cryptographic applications.
  69. ##
  70. ## See also
  71. ## ========
  72. ## * `math module<math.html>`_ for basic math routines
  73. ## * `mersenne module<mersenne.html>`_ for the Mersenne Twister random number
  74. ## generator
  75. ## * `stats module<stats.html>`_ for statistical analysis
  76. ## * `list of cryptographic and hashing modules
  77. ## <lib.html#pure-libraries-hashing>`_
  78. ## in the standard library
  79. import algorithm #For upperBound
  80. include "system/inclrtl"
  81. {.push debugger: off.}
  82. when defined(JS):
  83. type Ui = uint32
  84. const randMax = 4_294_967_295u32
  85. else:
  86. type Ui = uint64
  87. const randMax = 18_446_744_073_709_551_615u64
  88. type
  89. Rand* = object ## State of a random number generator.
  90. ##
  91. ## Create a new Rand state using the `initRand proc<#initRand,int64>`_.
  92. ##
  93. ## The module contains a default Rand state for convenience.
  94. ## It corresponds to the default random number generator's state.
  95. ## The default Rand state always starts with the same values, but the
  96. ## `randomize proc<#randomize>`_ can be used to seed the default generator
  97. ## with a value based on the current time.
  98. ##
  99. ## Many procs have two variations: one that takes in a Rand parameter and
  100. ## another that uses the default generator. The procs that use the default
  101. ## generator are **not** thread-safe!
  102. a0, a1: Ui
  103. when defined(JS):
  104. var state = Rand(
  105. a0: 0x69B4C98Cu32,
  106. a1: 0xFED1DD30u32) # global for backwards compatibility
  107. else:
  108. # racy for multi-threading but good enough for now:
  109. var state = Rand(
  110. a0: 0x69B4C98CB8530805u64,
  111. a1: 0xFED1DD3004688D67CAu64) # global for backwards compatibility
  112. proc rotl(x, k: Ui): Ui =
  113. result = (x shl k) or (x shr (Ui(64) - k))
  114. proc next*(r: var Rand): uint64 =
  115. ## Computes a random ``uint64`` number using the given state.
  116. ##
  117. ## See also:
  118. ## * `rand proc<#rand,Rand,Natural>`_ that returns an integer between zero and
  119. ## a given upper bound
  120. ## * `rand proc<#rand,Rand,range[]>`_ that returns a float
  121. ## * `rand proc<#rand,Rand,HSlice[T,T]>`_ that accepts a slice
  122. ## * `rand proc<#rand,typedesc[T]>`_ that accepts an integer or range type
  123. ## * `skipRandomNumbers proc<#skipRandomNumbers,Rand>`_
  124. runnableExamples:
  125. var r = initRand(2019)
  126. doAssert r.next() == 138_744_656_611_299'u64
  127. doAssert r.next() == 979_810_537_855_049_344'u64
  128. doAssert r.next() == 3_628_232_584_225_300_704'u64
  129. let s0 = r.a0
  130. var s1 = r.a1
  131. result = s0 + s1
  132. s1 = s1 xor s0
  133. r.a0 = rotl(s0, 55) xor s1 xor (s1 shl 14) # a, b
  134. r.a1 = rotl(s1, 36) # c
  135. proc skipRandomNumbers*(s: var Rand) =
  136. ## The jump function for the generator.
  137. ##
  138. ## This proc is equivalent to 2^64 calls to `next<#next,Rand>`_, and it can
  139. ## be used to generate 2^64 non-overlapping subsequences for parallel
  140. ## computations.
  141. ##
  142. ## When multiple threads are generating random numbers, each thread must
  143. ## own the `Rand<#Rand>`_ state it is using so that the thread can safely
  144. ## obtain random numbers. However, if each thread creates its own Rand state,
  145. ## the subsequences of random numbers that each thread generates may overlap,
  146. ## even if the provided seeds are unique. This is more likely to happen as the
  147. ## number of threads and amount of random numbers generated increases.
  148. ##
  149. ## If many threads will generate random numbers concurrently, it is better to
  150. ## create a single Rand state and pass it to each thread. After passing the
  151. ## Rand state to a thread, call this proc before passing it to the next one.
  152. ## By using the Rand state this way, the subsequences of random numbers
  153. ## generated in each thread will never overlap as long as no thread generates
  154. ## more than 2^64 random numbers.
  155. ##
  156. ## The following example below demonstrates this pattern:
  157. ##
  158. ## .. code-block::
  159. ## # Compile this example with --threads:on
  160. ## import random
  161. ## import threadpool
  162. ##
  163. ## const spawns = 4
  164. ## const numbers = 100000
  165. ##
  166. ## proc randomSum(rand: Rand): int =
  167. ## var r = rand
  168. ## for i in 1..numbers:
  169. ## result += rand(1..10)
  170. ##
  171. ## var r = initRand(2019)
  172. ## var vals: array[spawns, FlowVar[int]]
  173. ## for val in vals.mitems:
  174. ## val = spawn(randomSum(r))
  175. ## r.skipRandomNumbers()
  176. ##
  177. ## for val in vals:
  178. ## echo ^val
  179. ##
  180. ## See also:
  181. ## * `next proc<#next,Rand>`_
  182. when defined(JS):
  183. const helper = [0xbeac0467u32, 0xd86b048bu32]
  184. else:
  185. const helper = [0xbeac0467eba5facbu64, 0xd86b048b86aa9922u64]
  186. var
  187. s0 = Ui 0
  188. s1 = Ui 0
  189. for i in 0..high(helper):
  190. for b in 0 ..< 64:
  191. if (helper[i] and (Ui(1) shl Ui(b))) != 0:
  192. s0 = s0 xor s.a0
  193. s1 = s1 xor s.a1
  194. discard next(s)
  195. s.a0 = s0
  196. s.a1 = s1
  197. proc random*(max: int): int {.benign, deprecated:
  198. "Deprecated since v0.18.0; use 'rand' instead".} =
  199. while true:
  200. let x = next(state)
  201. if x < randMax - (randMax mod Ui(max)):
  202. return int(x mod uint64(max))
  203. proc random*(max: float): float {.benign, deprecated:
  204. "Deprecated since v0.18.0; use 'rand' instead".} =
  205. let x = next(state)
  206. when defined(JS):
  207. result = (float(x) / float(high(uint32))) * max
  208. else:
  209. let u = (0x3FFu64 shl 52u64) or (x shr 12u64)
  210. result = (cast[float](u) - 1.0) * max
  211. proc random*[T](x: HSlice[T, T]): T {.deprecated:
  212. "Deprecated since v0.18.0; use 'rand' instead".} =
  213. result = T(random(x.b - x.a)) + x.a
  214. proc random*[T](a: openArray[T]): T {.deprecated:
  215. "Deprecated since v0.18.0; use 'sample' instead".} =
  216. result = a[random(a.low..a.len)]
  217. proc rand*(r: var Rand; max: Natural): int {.benign.} =
  218. ## Returns a random integer in the range `0..max` using the given state.
  219. ##
  220. ## See also:
  221. ## * `rand proc<#rand,int>`_ that returns an integer using the default
  222. ## random number generator
  223. ## * `rand proc<#rand,Rand,range[]>`_ that returns a float
  224. ## * `rand proc<#rand,Rand,HSlice[T,T]>`_ that accepts a slice
  225. ## * `rand proc<#rand,typedesc[T]>`_ that accepts an integer or range type
  226. runnableExamples:
  227. var r = initRand(123)
  228. doAssert r.rand(100) == 0
  229. doAssert r.rand(100) == 96
  230. doAssert r.rand(100) == 66
  231. if max == 0: return
  232. while true:
  233. let x = next(r)
  234. if x <= randMax - (randMax mod Ui(max)):
  235. return int(x mod (uint64(max)+1u64))
  236. proc rand*(max: int): int {.benign.} =
  237. ## Returns a random integer in the range `0..max`.
  238. ##
  239. ## If `randomize<#randomize>`_ has not been called, the sequence of random
  240. ## numbers returned from this proc will always be the same.
  241. ##
  242. ## This proc uses the default random number generator. Thus, it is **not**
  243. ## thread-safe.
  244. ##
  245. ## See also:
  246. ## * `rand proc<#rand,Rand,Natural>`_ that returns an integer using a
  247. ## provided state
  248. ## * `rand proc<#rand,float>`_ that returns a float
  249. ## * `rand proc<#rand,HSlice[T,T]>`_ that accepts a slice
  250. ## * `rand proc<#rand,typedesc[T]>`_ that accepts an integer or range type
  251. runnableExamples:
  252. randomize(123)
  253. doAssert rand(100) == 0
  254. doAssert rand(100) == 96
  255. doAssert rand(100) == 66
  256. rand(state, max)
  257. proc rand*(r: var Rand; max: range[0.0 .. high(float)]): float {.benign.} =
  258. ## Returns a random floating point number in the range `0.0..max`
  259. ## using the given state.
  260. ##
  261. ## See also:
  262. ## * `rand proc<#rand,float>`_ that returns a float using the default
  263. ## random number generator
  264. ## * `rand proc<#rand,Rand,Natural>`_ that returns an integer
  265. ## * `rand proc<#rand,Rand,HSlice[T,T]>`_ that accepts a slice
  266. ## * `rand proc<#rand,typedesc[T]>`_ that accepts an integer or range type
  267. runnableExamples:
  268. var r = initRand(234)
  269. let f = r.rand(1.0)
  270. ## f = 8.717181376738381e-07
  271. let x = next(r)
  272. when defined(JS):
  273. result = (float(x) / float(high(uint32))) * max
  274. else:
  275. let u = (0x3FFu64 shl 52u64) or (x shr 12u64)
  276. result = (cast[float](u) - 1.0) * max
  277. proc rand*(max: float): float {.benign.} =
  278. ## Returns a random floating point number in the range `0.0..max`.
  279. ##
  280. ## If `randomize<#randomize>`_ has not been called, the sequence of random
  281. ## numbers returned from this proc will always be the same.
  282. ##
  283. ## This proc uses the default random number generator. Thus, it is **not**
  284. ## thread-safe.
  285. ##
  286. ## See also:
  287. ## * `rand proc<#rand,Rand,range[]>`_ that returns a float using a
  288. ## provided state
  289. ## * `rand proc<#rand,int>`_ that returns an integer
  290. ## * `rand proc<#rand,HSlice[T,T]>`_ that accepts a slice
  291. ## * `rand proc<#rand,typedesc[T]>`_ that accepts an integer or range type
  292. runnableExamples:
  293. randomize(234)
  294. let f = rand(1.0)
  295. ## f = 8.717181376738381e-07
  296. rand(state, max)
  297. proc rand*[T: Ordinal or SomeFloat](r: var Rand; x: HSlice[T, T]): T =
  298. ## For a slice `a..b`, returns a value in the range `a..b` using the given
  299. ## state.
  300. ##
  301. ## Allowed types for `T` are integers, floats, and enums without holes.
  302. ##
  303. ## See also:
  304. ## * `rand proc<#rand,HSlice[T,T]>`_ that accepts a slice and uses the
  305. ## default random number generator
  306. ## * `rand proc<#rand,Rand,Natural>`_ that returns an integer
  307. ## * `rand proc<#rand,Rand,range[]>`_ that returns a float
  308. ## * `rand proc<#rand,typedesc[T]>`_ that accepts an integer or range type
  309. runnableExamples:
  310. var r = initRand(345)
  311. doAssert r.rand(1..6) == 4
  312. doAssert r.rand(1..6) == 4
  313. doAssert r.rand(1..6) == 6
  314. let f = r.rand(-1.0 .. 1.0)
  315. ## f = 0.8741183448756229
  316. when T is SomeFloat:
  317. result = rand(r, x.b - x.a) + x.a
  318. else: # Integers and Enum types
  319. result = T(rand(r, int(x.b) - int(x.a)) + int(x.a))
  320. proc rand*[T: Ordinal or SomeFloat](x: HSlice[T, T]): T =
  321. ## For a slice `a..b`, returns a value in the range `a..b`.
  322. ##
  323. ## Allowed types for `T` are integers, floats, and enums without holes.
  324. ##
  325. ## If `randomize<#randomize>`_ has not been called, the sequence of random
  326. ## numbers returned from this proc will always be the same.
  327. ##
  328. ## This proc uses the default random number generator. Thus, it is **not**
  329. ## thread-safe.
  330. ##
  331. ## See also:
  332. ## * `rand proc<#rand,Rand,HSlice[T,T]>`_ that accepts a slice and uses
  333. ## a provided state
  334. ## * `rand proc<#rand,int>`_ that returns an integer
  335. ## * `rand proc<#rand,float>`_ that returns a floating point number
  336. ## * `rand proc<#rand,typedesc[T]>`_ that accepts an integer or range type
  337. runnableExamples:
  338. randomize(345)
  339. doAssert rand(1..6) == 4
  340. doAssert rand(1..6) == 4
  341. doAssert rand(1..6) == 6
  342. result = rand(state, x)
  343. proc rand*[T](r: var Rand; a: openArray[T]): T {.deprecated:
  344. "Deprecated since v0.20.0; use 'sample' instead".} =
  345. result = a[rand(r, a.low..a.high)]
  346. proc rand*[T: SomeInteger](t: typedesc[T]): T =
  347. ## Returns a random integer in the range `low(T)..high(T)`.
  348. ##
  349. ## If `randomize<#randomize>`_ has not been called, the sequence of random
  350. ## numbers returned from this proc will always be the same.
  351. ##
  352. ## This proc uses the default random number generator. Thus, it is **not**
  353. ## thread-safe.
  354. ##
  355. ## See also:
  356. ## * `rand proc<#rand,int>`_ that returns an integer
  357. ## * `rand proc<#rand,float>`_ that returns a floating point number
  358. ## * `rand proc<#rand,HSlice[T,T]>`_ that accepts a slice
  359. runnableExamples:
  360. randomize(567)
  361. doAssert rand(int8) == 55
  362. doAssert rand(int8) == -42
  363. doAssert rand(int8) == 43
  364. doAssert rand(uint32) == 578980729'u32
  365. doAssert rand(uint32) == 4052940463'u32
  366. doAssert rand(uint32) == 2163872389'u32
  367. doAssert rand(range[1..16]) == 11
  368. doAssert rand(range[1..16]) == 4
  369. doAssert rand(range[1..16]) == 16
  370. when T is range:
  371. result = rand(state, low(T)..high(T))
  372. else:
  373. result = cast[T](state.next)
  374. proc rand*[T](a: openArray[T]): T {.deprecated:
  375. "Deprecated since v0.20.0; use 'sample' instead".} =
  376. result = a[rand(a.low..a.high)]
  377. proc sample*[T](r: var Rand; s: set[T]): T =
  378. ## Returns a random element from the set ``s`` using the given state.
  379. ##
  380. ## See also:
  381. ## * `sample proc<#sample,set[T]>`_ that uses the default random number
  382. ## generator
  383. ## * `sample proc<#sample,Rand,openArray[T]>`_ for openarrays
  384. ## * `sample proc<#sample,Rand,openArray[T],openArray[U]>`_ that uses a
  385. ## cumulative distribution function
  386. runnableExamples:
  387. var r = initRand(987)
  388. let s = {1, 3, 5, 7, 9}
  389. doAssert r.sample(s) == 5
  390. doAssert r.sample(s) == 7
  391. doAssert r.sample(s) == 1
  392. assert card(s) != 0
  393. var i = rand(r, card(s) - 1)
  394. for e in s:
  395. if i == 0: return e
  396. dec(i)
  397. proc sample*[T](s: set[T]): T =
  398. ## Returns a random element from the set ``s``.
  399. ##
  400. ## If `randomize<#randomize>`_ has not been called, the order of outcomes
  401. ## from this proc will always be the same.
  402. ##
  403. ## This proc uses the default random number generator. Thus, it is **not**
  404. ## thread-safe.
  405. ##
  406. ## See also:
  407. ## * `sample proc<#sample,Rand,set[T]>`_ that uses a provided state
  408. ## * `sample proc<#sample,openArray[T]>`_ for openarrays
  409. ## * `sample proc<#sample,openArray[T],openArray[U]>`_ that uses a
  410. ## cumulative distribution function
  411. runnableExamples:
  412. randomize(987)
  413. let s = {1, 3, 5, 7, 9}
  414. doAssert sample(s) == 5
  415. doAssert sample(s) == 7
  416. doAssert sample(s) == 1
  417. sample(state, s)
  418. proc sample*[T](r: var Rand; a: openArray[T]): T =
  419. ## Returns a random element from ``a`` using the given state.
  420. ##
  421. ## See also:
  422. ## * `sample proc<#sample,openArray[T]>`_ that uses the default
  423. ## random number generator
  424. ## * `sample proc<#sample,Rand,openArray[T],openArray[U]>`_ that uses a
  425. ## cumulative distribution function
  426. ## * `sample proc<#sample,Rand,set[T]>`_ for sets
  427. runnableExamples:
  428. let marbles = ["red", "blue", "green", "yellow", "purple"]
  429. var r = initRand(456)
  430. doAssert r.sample(marbles) == "blue"
  431. doAssert r.sample(marbles) == "yellow"
  432. doAssert r.sample(marbles) == "red"
  433. result = a[r.rand(a.low..a.high)]
  434. proc sample*[T](a: openArray[T]): T =
  435. ## Returns a random element from ``a``.
  436. ##
  437. ## If `randomize<#randomize>`_ has not been called, the order of outcomes
  438. ## from this proc will always be the same.
  439. ##
  440. ## This proc uses the default random number generator. Thus, it is **not**
  441. ## thread-safe.
  442. ##
  443. ## See also:
  444. ## * `sample proc<#sample,Rand,openArray[T]>`_ that uses a provided state
  445. ## * `sample proc<#sample,openArray[T],openArray[U]>`_ that uses a
  446. ## cumulative distribution function
  447. ## * `sample proc<#sample,set[T]>`_ for sets
  448. runnableExamples:
  449. let marbles = ["red", "blue", "green", "yellow", "purple"]
  450. randomize(456)
  451. doAssert sample(marbles) == "blue"
  452. doAssert sample(marbles) == "yellow"
  453. doAssert sample(marbles) == "red"
  454. result = a[rand(a.low..a.high)]
  455. proc sample*[T, U](r: var Rand; a: openArray[T]; cdf: openArray[U]): T =
  456. ## Returns an element from ``a`` using a cumulative distribution function
  457. ## (CDF) and the given state.
  458. ##
  459. ## The ``cdf`` argument does not have to be normalized, and it could contain
  460. ## any type of elements that can be converted to a ``float``. It must be
  461. ## the same length as ``a``. Each element in ``cdf`` should be greater than
  462. ## or equal to the previous element.
  463. ##
  464. ## The outcome of the `cumsum<math.html#cumsum,openArray[T]>`_ proc and the
  465. ## return value of the `cumsummed<math.html#cumsummed,openArray[T]>`_ proc,
  466. ## which are both in the math module, can be used as the ``cdf`` argument.
  467. ##
  468. ## See also:
  469. ## * `sample proc<#sample,openArray[T],openArray[U]>`_ that also utilizes
  470. ## a CDF but uses the default random number generator
  471. ## * `sample proc<#sample,Rand,openArray[T]>`_ that does not use a CDF
  472. ## * `sample proc<#sample,Rand,set[T]>`_ for sets
  473. runnableExamples:
  474. from math import cumsummed
  475. let marbles = ["red", "blue", "green", "yellow", "purple"]
  476. let count = [1, 6, 8, 3, 4]
  477. let cdf = count.cumsummed
  478. var r = initRand(789)
  479. doAssert r.sample(marbles, cdf) == "red"
  480. doAssert r.sample(marbles, cdf) == "green"
  481. doAssert r.sample(marbles, cdf) == "blue"
  482. assert(cdf.len == a.len) # Two basic sanity checks.
  483. assert(float(cdf[^1]) > 0.0)
  484. #While we could check cdf[i-1] <= cdf[i] for i in 1..cdf.len, that could get
  485. #awfully expensive even in debugging modes.
  486. let u = r.rand(float(cdf[^1]))
  487. a[cdf.upperBound(U(u))]
  488. proc sample*[T, U](a: openArray[T]; cdf: openArray[U]): T =
  489. ## Returns an element from ``a`` using a cumulative distribution function
  490. ## (CDF).
  491. ##
  492. ## This proc works similarly to
  493. ## `sample[T, U](Rand, openArray[T], openArray[U])
  494. ## <#sample,Rand,openArray[T],openArray[U]>`_.
  495. ## See that proc's documentation for more details.
  496. ##
  497. ## If `randomize<#randomize>`_ has not been called, the order of outcomes
  498. ## from this proc will always be the same.
  499. ##
  500. ## This proc uses the default random number generator. Thus, it is **not**
  501. ## thread-safe.
  502. ##
  503. ## See also:
  504. ## * `sample proc<#sample,Rand,openArray[T],openArray[U]>`_ that also utilizes
  505. ## a CDF but uses a provided state
  506. ## * `sample proc<#sample,openArray[T]>`_ that does not use a CDF
  507. ## * `sample proc<#sample,set[T]>`_ for sets
  508. runnableExamples:
  509. from math import cumsummed
  510. let marbles = ["red", "blue", "green", "yellow", "purple"]
  511. let count = [1, 6, 8, 3, 4]
  512. let cdf = count.cumsummed
  513. randomize(789)
  514. doAssert sample(marbles, cdf) == "red"
  515. doAssert sample(marbles, cdf) == "green"
  516. doAssert sample(marbles, cdf) == "blue"
  517. state.sample(a, cdf)
  518. proc initRand*(seed: int64): Rand =
  519. ## Initializes a new `Rand<#Rand>`_ state using the given seed.
  520. ##
  521. ## `seed` must not be zero. Providing a specific seed will produce
  522. ## the same results for that seed each time.
  523. ##
  524. ## The resulting state is independent of the default random number
  525. ## generator's state.
  526. ##
  527. ## See also:
  528. ## * `randomize proc<#randomize,int64>`_ that accepts a seed for the default
  529. ## random number generator
  530. ## * `randomize proc<#randomize>`_ that initializes the default random
  531. ## number generator using the current time
  532. runnableExamples:
  533. from times import getTime, toUnix, nanosecond
  534. var r1 = initRand(123)
  535. let now = getTime()
  536. var r2 = initRand(now.toUnix * 1_000_000_000 + now.nanosecond)
  537. doAssert seed != 0 # 0 causes `rand(int)` to always return 0 for example.
  538. result.a0 = Ui(seed shr 16)
  539. result.a1 = Ui(seed and 0xffff)
  540. discard next(result)
  541. proc randomize*(seed: int64) {.benign.} =
  542. ## Initializes the default random number generator with the given seed.
  543. ##
  544. ## `seed` must not be zero. Providing a specific seed will produce
  545. ## the same results for that seed each time.
  546. ##
  547. ## See also:
  548. ## * `initRand proc<#initRand,int64>`_
  549. ## * `randomize proc<#randomize>`_ that uses the current time instead
  550. runnableExamples:
  551. from times import getTime, toUnix, nanosecond
  552. randomize(123)
  553. let now = getTime()
  554. randomize(now.toUnix * 1_000_000_000 + now.nanosecond)
  555. state = initRand(seed)
  556. proc shuffle*[T](r: var Rand; x: var openArray[T]) =
  557. ## Shuffles a sequence of elements in-place using the given state.
  558. ##
  559. ## See also:
  560. ## * `shuffle proc<#shuffle,openArray[T]>`_ that uses the default
  561. ## random number generator
  562. runnableExamples:
  563. var cards = ["Ace", "King", "Queen", "Jack", "Ten"]
  564. var r = initRand(678)
  565. r.shuffle(cards)
  566. doAssert cards == ["King", "Ace", "Queen", "Ten", "Jack"]
  567. for i in countdown(x.high, 1):
  568. let j = r.rand(i)
  569. swap(x[i], x[j])
  570. proc shuffle*[T](x: var openArray[T]) =
  571. ## Shuffles a sequence of elements in-place.
  572. ##
  573. ## If `randomize<#randomize>`_ has not been called, the order of outcomes
  574. ## from this proc will always be the same.
  575. ##
  576. ## This proc uses the default random number generator. Thus, it is **not**
  577. ## thread-safe.
  578. ##
  579. ## See also:
  580. ## * `shuffle proc<#shuffle,Rand,openArray[T]>`_ that uses a provided state
  581. runnableExamples:
  582. var cards = ["Ace", "King", "Queen", "Jack", "Ten"]
  583. randomize(678)
  584. shuffle(cards)
  585. doAssert cards == ["King", "Ace", "Queen", "Ten", "Jack"]
  586. shuffle(state, x)
  587. when not defined(nimscript) and not defined(standalone):
  588. import times
  589. proc randomize*() {.benign.} =
  590. ## Initializes the default random number generator with a value based on
  591. ## the current time.
  592. ##
  593. ## This proc only needs to be called once, and it should be called before
  594. ## the first usage of procs from this module that use the default random
  595. ## number generator.
  596. ##
  597. ## **Note:** Does not work for NimScript.
  598. ##
  599. ## See also:
  600. ## * `randomize proc<#randomize,int64>`_ that accepts a seed
  601. ## * `initRand proc<#initRand,int64>`_
  602. when defined(JS):
  603. let time = int64(times.epochTime() * 1000) and 0x7fff_ffff
  604. randomize(time)
  605. else:
  606. let now = times.getTime()
  607. randomize(convert(Seconds, Nanoseconds, now.toUnix) + now.nanosecond)
  608. {.pop.}
  609. when isMainModule:
  610. proc main =
  611. var occur: array[1000, int]
  612. var x = 8234
  613. for i in 0..100_000:
  614. x = rand(high(occur))
  615. inc occur[x]
  616. for i, oc in occur:
  617. if oc < 69:
  618. doAssert false, "too few occurrences of " & $i
  619. elif oc > 150:
  620. doAssert false, "too many occurrences of " & $i
  621. var a = [0, 1]
  622. shuffle(a)
  623. doAssert a[0] == 1
  624. doAssert a[1] == 0
  625. doAssert rand(0) == 0
  626. doAssert rand("a") == 'a'
  627. when compileOption("rangeChecks"):
  628. try:
  629. discard rand(-1)
  630. doAssert false
  631. except RangeError:
  632. discard
  633. try:
  634. discard rand(-1.0)
  635. doAssert false
  636. except RangeError:
  637. discard
  638. # don't use causes integer overflow
  639. doAssert compiles(random[int](low(int) .. high(int)))
  640. main()