aboutsummaryrefslogtreecommitdiff
path: root/core/math/rand/rand.odin
blob: 14894e82c41c2145180d9f6280d02425695d34ca (plain)
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
/*
Package core:math/rand implements various random number generators
*/
package rand

import "base:intrinsics"
import "core:math"
import "core:mem"

Rand :: struct {
	state: u64,
	inc:   u64,
	is_system: bool,
}


@(private)
global_rand := create(u64(intrinsics.read_cycle_counter()))

/*
Sets the seed used by the global random number generator.

Inputs:
- seed: The seed value

Example:
	import "core:math/rand"
	import "core:fmt"

	set_global_seed_example :: proc() {
		rand.set_global_seed(1)
		fmt.println(rand.uint64())
	}

Possible Output:

	10

*/
set_global_seed :: proc(seed: u64) {
	init(&global_rand, seed)
}

/*
Creates a new random number generator.

Inputs:
- seed: The seed value to create the random number generator with

Returns:
- res: The created random number generator

Example:
	import "core:math/rand"
	import "core:fmt"

	create_example :: proc() {
		my_rand := rand.create(1)
		fmt.println(rand.uint64(&my_rand))
	}

Possible Output:

	10

*/
@(require_results)
create :: proc(seed: u64) -> (res: Rand) {
	r: Rand
	init(&r, seed)
	return r
}


/*
Initialises a random number generator.

Inputs:
- r: The random number generator to initialise
- seed: The seed value to initialise this random number generator

Example:
	import "core:math/rand"
	import "core:fmt"

	init_example :: proc() {
		my_rand: rand.Rand
		rand.init(&my_rand, 1)
		fmt.println(rand.uint64(&my_rand))
	}

Possible Output:

	10

*/
init :: proc(r: ^Rand, seed: u64) {
	r.state = 0
	r.inc = (seed << 1) | 1
	_random_u64(r)
	r.state += seed
	_random_u64(r)
}

/*
Initialises a random number generator to use the system random number generator.  
The system random number generator is platform specific.  
On `linux` refer to the `getrandom` syscall.  
On `darwin` refer to `getentropy`.  
On `windows` refer to `BCryptGenRandom`.

All other platforms are not supported

Inputs:
- r: The random number generator to use the system random number generator

WARNING: Panics if the system is not either `windows`, `darwin` or `linux`

Example:
	import "core:math/rand"
	import "core:fmt"

	init_as_system_example :: proc() {
		my_rand: rand.Rand
		rand.init_as_system(&my_rand)
		fmt.println(rand.uint64(&my_rand))
	}

Possible Output:

	10

*/
init_as_system :: proc(r: ^Rand) {
	if !#defined(_system_random) {
		panic(#procedure + " is not supported on this platform yet")
	}
	r.state = 0
	r.inc   = 0
	r.is_system = true
}

@(private)
_random_u64 :: proc(r: ^Rand) -> u64 {
	r := r
	if r == nil {
		r = &global_rand
	}
	when #defined(_system_random) {
		if r.is_system {
			return _system_random()
		}
	}


	old_state := r.state
	r.state = old_state * 6364136223846793005 + (r.inc|1)
	xor_shifted := (((old_state >> 59) + 5) ~ old_state) * 12605985483714917081
	rot := (old_state >> 59)
	return (xor_shifted >> rot) | (xor_shifted << ((-rot) & 63))
}

/*
Generates a random 32 bit value using the provided random number generator. If no generator is provided the global random number generator will be used.

Inputs:
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random unsigned 32 bit value

Example:
	import "core:math/rand"
	import "core:fmt"

	uint32_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.uint32())
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.uint32(&my_rand))
	}

Possible Output:

	10
	389

*/
@(require_results)
uint32 :: proc(r: ^Rand = nil) -> (val: u32) { return u32(_random_u64(r)) }

/*
Generates a random 64 bit value using the provided random number generator. If no generator is provided the global random number generator will be used.

Inputs:
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random unsigned 64 bit value

Example:
	import "core:math/rand"
	import "core:fmt"

	uint64_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.uint64())
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.uint64(&my_rand))
	}

Possible Output:

	10
	389

*/
@(require_results)
uint64 :: proc(r: ^Rand = nil) -> (val: u64) { return _random_u64(r) }

/*
Generates a random 128 bit value using the provided random number generator. If no generator is provided the global random number generator will be used.

Inputs:
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random unsigned 128 bit value

Example:
	import "core:math/rand"
	import "core:fmt"

	uint128_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.uint128())
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.uint128(&my_rand))
	}

Possible Output:

	10
	389

*/
@(require_results)
uint128 :: proc(r: ^Rand = nil) -> (val: u128) {
	a := u128(_random_u64(r))
	b := u128(_random_u64(r))
	return (a<<64) | b
}

/*
Generates a random 31 bit value using the provided random number generator. If no generator is provided the global random number generator will be used.  
The sign bit will always be set to 0, thus all generated numbers will be positive.

Inputs:
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random 31 bit value

Example:
	import "core:math/rand"
	import "core:fmt"

	int31_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.int31())
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.int31(&my_rand))
	}

Possible Output:

	10
	389

*/
@(require_results) int31  :: proc(r: ^Rand = nil) -> (val: i32)  { return i32(uint32(r) << 1 >> 1) }

/*
Generates a random 63 bit value using the provided random number generator. If no generator is provided the global random number generator will be used.  
The sign bit will always be set to 0, thus all generated numbers will be positive.

Inputs:
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random 63 bit value

Example:
	import "core:math/rand"
	import "core:fmt"

	int63_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.int63())
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.int63(&my_rand))
	}

Possible Output:

	10
	389

*/
@(require_results) int63  :: proc(r: ^Rand = nil) -> (val: i64)  { return i64(uint64(r) << 1 >> 1) }

/*
Generates a random 127 bit value using the provided random number generator. If no generator is provided the global random number generator will be used.  
The sign bit will always be set to 0, thus all generated numbers will be positive.

Inputs:
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random 127 bit value

Example:
	import "core:math/rand"
	import "core:fmt"

	int127_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.int127())
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.int127(&my_rand))
	}

Possible Output:

	10
	389

*/
@(require_results) int127 :: proc(r: ^Rand = nil) -> (val: i128) { return i128(uint128(r) << 1 >> 1) }

/*
Generates a random 31 bit value in the range `[0, n)` using the provided random number generator. If no generator is provided the global random number generator will be used.

Inputs:
- n: The upper bound of the generated number, this value is exclusive
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random 31 bit value in the range `[0, n)`

WARNING: Panics if n is less than 0

Example:
	import "core:math/rand"
	import "core:fmt"

	int31_max_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.int31_max(16))
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.int31_max(1024, &my_rand))
	}

Possible Output:

	6
	500

*/
@(require_results)
int31_max :: proc(n: i32, r: ^Rand = nil) -> (val: i32) {
	if n <= 0 {
		panic("Invalid argument to int31_max")
	}
	if n&(n-1) == 0 {
		return int31(r) & (n-1)
	}
	max := i32((1<<31) - 1 - (1<<31)%u32(n))
	v := int31(r)
	for v > max {
		v = int31(r)
	}
	return v % n
}

/*
Generates a random 63 bit value in the range `[0, n)` using the provided random number generator. If no generator is provided the global random number generator will be used.

Inputs:
- n: The upper bound of the generated number, this value is exclusive
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random 63 bit value in the range `[0, n)`

WARNING: Panics if n is less than 0

Example:
	import "core:math/rand"
	import "core:fmt"

	int63_max_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.int63_max(16))
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.int63_max(1024, &my_rand))
	}

Possible Output:

	6
	500

*/
@(require_results)
int63_max :: proc(n: i64, r: ^Rand = nil) -> (val: i64) {
	if n <= 0 {
		panic("Invalid argument to int63_max")
	}
	if n&(n-1) == 0 {
		return int63(r) & (n-1)
	}
	max := i64((1<<63) - 1 - (1<<63)%u64(n))
	v := int63(r)
	for v > max {
		v = int63(r)
	}
	return v % n
}

/*
Generates a random 127 bit value in the range `[0, n)` using the provided random number generator. If no generator is provided the global random number generator will be used.

Inputs:
- n: The upper bound of the generated number, this value is exclusive
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random 127 bit value in the range `[0, n)`

WARNING: Panics if n is less than 0

Example:
	import "core:math/rand"
	import "core:fmt"

	int127_max_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.int127_max(16))
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.int127_max(1024, &my_rand))
	}

Possible Output:

	6
	500

*/
@(require_results)
int127_max :: proc(n: i128, r: ^Rand = nil) -> (val: i128) {
	if n <= 0 {
		panic("Invalid argument to int127_max")
	}
	if n&(n-1) == 0 {
		return int127(r) & (n-1)
	}
	max := i128((1<<127) - 1 - (1<<127)%u128(n))
	v := int127(r)
	for v > max {
		v = int127(r)
	}
	return v % n
}

/*
Generates a random integer value in the range `[0, n)` using the provided random number generator. If no generator is provided the global random number generator will be used.

Inputs:
- n: The upper bound of the generated number, this value is exclusive
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random integer value in the range `[0, n)`

WARNING: Panics if n is less than 0

Example:
	import "core:math/rand"
	import "core:fmt"

	int_max_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.int_max(16))
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.int_max(1024, &my_rand))
	}

Possible Output:

	6
	500

*/
@(require_results)
int_max :: proc(n: int, r: ^Rand = nil) -> (val: int) {
	if n <= 0 {
		panic("Invalid argument to int_max")
	}
	when size_of(int) == 4 {
		return int(int31_max(i32(n), r))
	} else {
		return int(int63_max(i64(n), r))
	}
}

/*
Generates a random double floating point value in the range `[0, 1)` using the provided random number generator. If no generator is provided the global random number generator will be used.

Inputs:
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random double floating point value in the range `[0, 1)`

Example:
	import "core:math/rand"
	import "core:fmt"

	float64_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.float64())
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.float64(&my_rand))
	}

Possible Output:

	0.043
	0.511

*/
@(require_results) float64 :: proc(r: ^Rand = nil) -> (val: f64) { return f64(int63_max(1<<53, r)) / (1 << 53) }

/*
Generates a random single floating point value in the range `[0, 1)` using the provided random number generator. If no generator is provided the global random number generator will be used.

Inputs:
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random single floating point value in the range `[0, 1)`

Example:
	import "core:math/rand"
	import "core:fmt"

	float32_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.float32())
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.float32(&my_rand))
	}

Possible Output:

	0.043
	0.511

*/
@(require_results) float32 :: proc(r: ^Rand = nil) -> (val: f32) { return f32(int31_max(1<<24, r)) / (1 << 24) }

/*
Generates a random double floating point value in the range `[low, high)` using the provided random number generator. If no generator is provided the global random number generator will be used.

WARNING: Panics if `high < low`

Inputs:
- low: The lower bounds of the value, this value is inclusive
- high: The upper bounds of the value, this value is exclusive
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random double floating point value in the range [low, high)

Example:
	import "core:math/rand"
	import "core:fmt"

	float64_range_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.float64_range(-10, 300))
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.float64_range(600, 900, &my_rand))
	}

Possible Output:

	15.312
	673.130

*/
@(require_results) float64_range :: proc(low, high: f64, r: ^Rand = nil) -> (val: f64) {
	assert(low <= high, "low must be lower than or equal to high")
	val = (high-low)*float64(r) + low
	if val >= high {
		val = max(low, high * (1 - math.F64_EPSILON))
	}
	return
}

/*
Generates a random single floating point value in the range `[low, high)` using the provided random number generator. If no generator is provided the global random number generator will be used.

Inputs:
- low: The lower bounds of the value, this value is inclusive
- high: The upper bounds of the value, this value is exclusive
- r: The random number generator to use, or nil for the global generator

Returns:
- val: A random single floating point value in the range [low, high)

WARNING: Panics if `high < low`

Example:
	import "core:math/rand"
	import "core:fmt"

	float32_range_example :: proc() {
		// Using the global random number generator
		fmt.println(rand.float32_range(-10, 300))
		// Using local random number generator
		my_rand := rand.create(1)
		fmt.println(rand.float32_range(600, 900, &my_rand))
	}

Possible Output:

	15.312
	673.130

*/
@(require_results) float32_range :: proc(low, high: f32, r: ^Rand = nil) -> (val: f32) {
	assert(low <= high, "low must be lower than or equal to high")
	val = (high-low)*float32(r) + low
	if val >= high {
		val = max(low, high * (1 - math.F32_EPSILON))
	}
	return
}

/*
Fills a byte slice with random values using the provided random number generator. If no generator is provided the global random number generator will be used.  
Due to floating point precision there is no guarantee if the upper and lower bounds are inclusive/exclusive with the exact floating point value.  

Inputs:
- p: The byte slice to fill
- r: The random number generator to use, or nil for the global generator

Returns:
- n: The number of bytes generated

Example:
	import "core:math/rand"
	import "core:fmt"

	read_example :: proc() {
		// Using the global random number generator
		data: [8]byte
		n := rand.read(data[:])
		fmt.println(n)
		fmt.println(data)
	}

Possible Output:

	8
	[32, 4, 59, 7, 1, 2, 2, 119]

*/
@(require_results)
read :: proc(p: []byte, r: ^Rand = nil) -> (n: int) {
	pos := i8(0)
	val := i64(0)
	for n = 0; n < len(p); n += 1 {
		if pos == 0 {
			val = int63(r)
			pos = 7
		}
		p[n] = byte(val)
		val >>= 8
		pos -= 1
	}
	return
}

/*
Creates a slice of `int` filled with random values using the provided random number generator. If no generator is provided the global random number generator will be used.  

*Allocates Using Provided Allocator*

Inputs:
- n: The size of the created slice
- r: The random number generator to use, or nil for the global generator
- allocator: (default: context.allocator)

Returns:
- res: A slice filled with random values
- err: An allocator error if one occured, `nil` otherwise

Example:
	import "core:math/rand"
	import "core:mem"
	import "core:fmt"

	perm_example :: proc() -> (err: mem.Allocator_Error) {
		// Using the global random number generator and using the context allocator
		data := rand.perm(4) or_return
		fmt.println(data)
		defer delete(data, context.allocator)

		// Using local random number generator and temp allocator
		my_rand := rand.create(1)
		data_tmp := rand.perm(4, &my_rand, context.temp_allocator) or_return
		fmt.println(data_tmp)

		return
	}

Possible Output:

	[7201011, 3, 9123, 231131]
	[19578, 910081, 131, 7]

*/
@(require_results)
perm :: proc(n: int, r: ^Rand = nil, allocator := context.allocator) -> (res: []int, err: mem.Allocator_Error) #optional_allocator_error {
	m := make([]int, n, allocator) or_return
	for i := 0; i < n; i += 1 {
		j := int_max(i+1, r)
		m[i] = m[j]
		m[j] = i
	}
	return m, {}
}

/*
Randomizes the ordering of elements for the provided slice. If no generator is provided the global random number generator will be used.  

Inputs:
- array: The slice to randomize
- r: The random number generator to use, or nil for the global generator

Example:
	import "core:math/rand"
	import "core:fmt"

	shuffle_example :: proc() {
		// Using the global random number generator
		data: [4]int = { 1, 2, 3, 4 }
		fmt.println(data) // the contents are in order
		rand.shuffle(data[:])
		fmt.println(data) // the contents have been shuffled
	}

Possible Output:

	[1, 2, 3, 4]
	[2, 4, 3, 1]

*/
shuffle :: proc(array: $T/[]$E, r: ^Rand = nil) {
	n := i64(len(array))
	if n < 2 {
		return
	}

	for i := i64(0); i < n; i += 1 {
		j := int63_max(n, r)
		array[i], array[j] = array[j], array[i]
	}
}

/*
Returns a random element from the provided slice. If no generator is provided the global random number generator will be used.  

Inputs:
- array: The slice to choose an element from
- r: The random number generator to use, or nil for the global generator

Returns:
- res: A random element from `array`

Example:
	import "core:math/rand"
	import "core:fmt"

	choice_example :: proc() {
		// Using the global random number generator
		data: [4]int = { 1, 2, 3, 4 }
		fmt.println(rand.choice(data[:]))
		fmt.println(rand.choice(data[:]))
		fmt.println(rand.choice(data[:]))
		fmt.println(rand.choice(data[:]))
	}

Possible Output:

	3
	2
	2
	4

*/
@(require_results)
choice :: proc(array: $T/[]$E, r: ^Rand = nil) -> (res: E) {
	n := i64(len(array))
	if n < 1 {
		return E{}
	}
	return array[int63_max(n, r)]
}