/
RandomExtensions.cs
1832 lines (1646 loc) · 113 KB
/
RandomExtensions.cs
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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region Copyright
///////////////////////////////////////////////////////////////////////////////
// File: RandomExtensions.cs
///////////////////////////////////////////////////////////////////////////////
// Copyright (C) KGy SOFT, 2005-2018 - All Rights Reserved
//
// You should have received a copy of the LICENSE file at the top-level
// directory of this distribution. If not, then this file is considered as
// an illegal copy.
//
// Unauthorized copying of this file, via any medium is strictly prohibited.
///////////////////////////////////////////////////////////////////////////////
#endregion
#region Usings
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
#if !NET35 && !NET40
using System.Runtime.CompilerServices;
#endif
#if NETSTANDARD2_1
using System.Runtime.InteropServices;
#endif
using System.Security;
using System.Text;
using KGySoft.Reflection;
using KGySoft.Security.Cryptography;
#endregion
namespace KGySoft.CoreLibraries
{
/// <summary>
/// Contains extension methods for the <see cref="Random"/> type.
/// <br/>See the <strong>Examples</strong> section for an example.
/// </summary>
/// <example>
/// <note type="tip">Try also <a href="https://dotnetfiddle.net/EPHRIx" target="_blank">online</a>.</note>
/// <code lang="C#"><![CDATA[
/// using System;
/// using System.Collections;
/// using System.Collections.Generic;
/// using System.Globalization;
/// using System.Linq;
/// using System.Reflection;
/// using KGySoft.CoreLibraries;
///
/// public static class Example
/// {
/// public static void Main()
/// {
/// var rnd = new Random();
///
/// // Next... for all simple types:
/// Console.WriteLine(rnd.NextBoolean());
/// Console.WriteLine(rnd.NextDouble(Double.PositiveInfinity)); // see also the overloads
/// Console.WriteLine(rnd.NextString()); // see also the overloads
/// Console.WriteLine(rnd.NextDateTime()); // also NextDate, NextDateTimeOffset, NextTimeSpan
/// Console.WriteLine(rnd.NextEnum<ConsoleColor>());
/// // and NextByte, NextSByte, NextInt16, NextDecimal, etc.
///
/// // NextObject: for practically anything. See also GenerateObjectSettings.
/// Console.WriteLine(rnd.NextObject<Person>().Dump()); // custom type
/// Console.WriteLine(rnd.NextObject<(int, string)>()); // tuple
/// Console.WriteLine(rnd.NextObject<IConvertible>()); // interface implementation
/// Console.WriteLine(rnd.NextObject<MarshalByRefObject>()); // abstract type implementation
/// Console.WriteLine(rnd.NextObject<int[]>().Dump()); // array
/// Console.WriteLine(rnd.NextObject<IList<IConvertible>>().Dump()); // some collection of an interface
/// Console.WriteLine(rnd.NextObject<Func<DateTime>>().Invoke()); // delegate with random result
///
/// // specific type for object (useful for non-generic collections)
/// Console.WriteLine(rnd.NextObject<ArrayList>(new GenerateObjectSettings
/// {
/// SubstitutionForObjectType = typeof(ConsoleColor)
/// }).Dump());
///
/// // literally any random object
/// Console.WriteLine(rnd.NextObject<object>(new GenerateObjectSettings
/// {
/// AllowDerivedTypesForNonSealedClasses = true
/// })/*.Dump()*/); // dump may end up in an exception for property getters or even in an endless recursion
/// }
///
/// private static string Dump(this object o)
/// {
/// if (o == null)
/// return "<null>";
///
/// if (o is IConvertible convertible)
/// return convertible.ToString(CultureInfo.InvariantCulture);
///
/// if (o is IEnumerable enumerable)
/// return $"[{String.Join(", ", enumerable.Cast<object>().Select(Dump))}]";
///
/// return $"{{{String.Join("; ", o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => $"{p.Name} = {Dump(p.GetValue(o))}"))}}}";
/// }
/// }
///
/// public class Person
/// {
/// public string FirstName { get; set; }
/// public string LastName { get; set; }
/// public DateTime BirthDate { get; set; }
/// public List<string> PhoneNumbers { get; set; }
/// }
///
/// // A possible output of the code above can be the following:
/// // False
/// // 1,65543763243888E+266
/// // }\&qc54# d
/// // 8806. 02. 18. 6:25:21
/// // White
/// // {FirstName = Jemp; LastName = Aeltep; BirthDate = 07/04/2003 00:00:00; PhoneNumbers = [17251827, 7099649772]}
/// // (1168349297, oufos)
/// // Renegotiated
/// // System.Net.Sockets.NetworkStream
/// // [336221768]
/// // [Off, Invalid]
/// // 1956. 08. 24. 4:28:57
/// // [Yellow, Gray]
/// // System.Xml.XmlCharCheckingReader+<ReadElementContentAsBinHexAsync>d__40 *
/// ]]></code>
/// </example>
public static partial class RandomExtensions
{
// ReSharper disable CompareOfFloatsByEqualityOperator - in this class this is intended
#region Methods
#region Byte Array
/// <summary>
/// Returns an <see cref="Array"/> of random bytes that has the specified <paramref name="length"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="length">The desired length of the result.</param>
/// <returns>An array of random bytes that has the specified <paramref name="length"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is less than 0.</exception>
public static byte[] NextBytes(this Random random, int length)
{
if (random == null)
Throw.ArgumentNullException(Argument.random);
if (length < 0)
Throw.ArgumentOutOfRangeException(Argument.length, Res.ArgumentMustBeGreaterThanOrEqualTo(0));
if (length == 0)
return Reflector.EmptyArray<byte>();
var result = new byte[length];
random.NextBytes(result);
return result;
}
#endregion
#region Boolean
/// <summary>
/// Returns a random <see cref="bool"/> value.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <returns>A <see cref="bool"/> value that is either <see langword="true"/> or <see langword="false"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
public static bool NextBoolean(this Random random)
{
if (random == null)
Throw.ArgumentNullException(Argument.random);
return (random.Next() & 1) == 0;
}
#endregion
#region Integers
/// <summary>
/// Returns a random <see cref="sbyte"/> value.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <returns>An 8-bit signed integer that is greater than or equal to <see cref="SByte.MinValue">SByte.MinValue</see> and less or equal to <see cref="SByte.MaxValue">SByte.MaxValue</see>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
[CLSCompliant(false)]
public static sbyte NextSByte(this Random random)
=> (sbyte)random.Next();
/// <summary>
/// Returns a random <see cref="sbyte"/> value that is less or equal to the specified <paramref name="maxValue"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="maxValue">The upper bound of the random number returned.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>An 8-bit signed integer that is greater than or equal to 0 and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="maxValue"/> equals 0, then 0 is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than 0.</exception>
[CLSCompliant(false)]
public static sbyte NextSByte(this Random random, sbyte maxValue, bool inclusiveUpperBound = false)
=> (sbyte)random.NextInt32(0, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="sbyte"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The inclusive lower bound of the random number returned.</param>
/// <param name="maxValue">The upper bound of the random number returned. Must be greater or equal to <paramref name="minValue"/>.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>An 8-bit signed integer that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="maxValue"/> is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>.</exception>
[CLSCompliant(false)]
public static sbyte NextSByte(this Random random, sbyte minValue, sbyte maxValue, bool inclusiveUpperBound = false)
=> (sbyte)random.NextInt32(minValue, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="byte"/> value.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <returns>An 8-bit unsigned integer that is greater than or equal to 0 and less or equal to <see cref="Byte.MaxValue">Byte.MaxValue</see>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
public static byte NextByte(this Random random)
=> (byte)random.Next();
/// <summary>
/// Returns a random <see cref="byte"/> value that is less or equal to the specified <paramref name="maxValue"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="maxValue">The upper bound of the random number returned.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>An 8-bit unsigned integer that is greater than or equal to 0 and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="maxValue"/> equals 0, then 0 is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
public static byte NextByte(this Random random, byte maxValue, bool inclusiveUpperBound = false)
=> (byte)random.NextUInt32(0U, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="byte"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The inclusive lower bound of the random number returned.</param>
/// <param name="maxValue">The upper bound of the random number returned. Must be greater or equal to <paramref name="minValue"/>.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>An 8-bit unsigned integer that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="maxValue"/> is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>.</exception>
public static byte NextByte(this Random random, byte minValue, byte maxValue, bool inclusiveUpperBound = false)
=> (byte)random.NextUInt32(minValue, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="short"/> value.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <returns>A 16-bit signed integer that is greater than or equal to <see cref="Int16.MinValue">Int16.MinValue</see> and less or equal to <see cref="Int16.MaxValue">Int16.MaxValue</see>.</returns>
/// <remarks>Similarly to the <see cref="Random.Next()">Random.Next()</see> method this one returns an <see cref="int"/> value; however, the result can be negative and
/// the maximum possible value can be <see cref="Int32.MaxValue">Int32.MaxValue</see>.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
public static short NextInt16(this Random random)
=> (short)random.Next();
/// <summary>
/// Returns a random <see cref="short"/> value that is less or equal to the specified <paramref name="maxValue"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="maxValue">The upper bound of the random number returned.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 16-bit signed integer that is greater than or equal to 0 and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="maxValue"/> equals 0, then 0 is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than 0.</exception>
public static short NextInt16(this Random random, short maxValue, bool inclusiveUpperBound = false)
=> (short)random.NextInt32(0, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="short"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The inclusive lower bound of the random number returned.</param>
/// <param name="maxValue">The upper bound of the random number returned. Must be greater or equal to <paramref name="minValue"/>.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 16-bit signed integer that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="maxValue"/> is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>.</exception>
public static short NextInt16(this Random random, short minValue, short maxValue, bool inclusiveUpperBound = false)
=> (short)random.NextInt32(minValue, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="ushort"/> value.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <returns>A 16-bit unsigned integer that is greater than or equal to 0 and less or equal to <see cref="UInt16.MaxValue">UInt16.MaxValue</see>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
[CLSCompliant(false)]
public static ushort NextUInt16(this Random random)
=> (ushort)random.Next();
/// <summary>
/// Returns a random <see cref="ushort"/> value that is less or equal to the specified <paramref name="maxValue"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="maxValue">The upper bound of the random number returned.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 16-bit unsigned integer that is greater than or equal to 0 and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="maxValue"/> equals 0, then 0 is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
[CLSCompliant(false)]
public static ushort NextUInt16(this Random random, ushort maxValue, bool inclusiveUpperBound = false)
=> (ushort)random.NextUInt32(0U, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="ushort"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The inclusive lower bound of the random number returned.</param>
/// <param name="maxValue">The upper bound of the random number returned. Must be greater or equal to <paramref name="minValue"/>.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 16-bit unsigned integer that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="maxValue"/> is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>.</exception>
[CLSCompliant(false)]
public static ushort NextUInt16(this Random random, ushort minValue, ushort maxValue, bool inclusiveUpperBound = false)
=> (ushort)random.NextUInt32(minValue, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="int"/> value.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <returns>A 32-bit signed integer that is greater than or equal to <see cref="Int32.MinValue">Int32.MinValue</see> and less or equal to <see cref="Int32.MaxValue">Int32.MaxValue</see>.</returns>
/// <remarks>Similarly to the <see cref="Random.Next()">Random.Next()</see> method this one returns an <see cref="int"/> value; however, the result can be negative and
/// the maximum possible value can be <see cref="Int32.MaxValue">Int32.MaxValue</see>.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
#if !NET35
[SecuritySafeCritical]
#endif
public static unsafe int NextInt32(this Random random)
{
#if !(NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0)
// In practice, in .NET Core 3.0 this is still slower than the fallback version but
// we hope the best for the future and at least we spare some heap allocation
Span<byte> bytes = stackalloc byte[4];
random.NextBytes(bytes);
#if NETSTANDARD2_1
return MemoryMarshal.Read<int>(bytes); // Unsafe.As would be much faster but that is not available in Standard
#else
return Unsafe.As<byte, int>(ref bytes[0]);
#endif // NETSTANDARD2_1
#else // !(NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0)
var bytes = new byte[4];
random.NextBytes(bytes);
fixed (byte* p = bytes)
return *(int*)p;
#endif
}
/// <summary>
/// Returns a random <see cref="int"/> value that is less or equal to the specified <paramref name="maxValue"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="maxValue">The upper bound of the random number returned.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 32-bit signed integer that is greater than or equal to 0 and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="maxValue"/> equals 0, then 0 is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than 0.</exception>
public static int NextInt32(this Random random, int maxValue, bool inclusiveUpperBound = false)
=> random.NextInt32(0, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="int"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The inclusive lower bound of the random number returned.</param>
/// <param name="maxValue">The upper bound of the random number returned. Must be greater or equal to <paramref name="minValue"/>.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 64-bit signed integer that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="maxValue"/> is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>.</exception>
public static int NextInt32(this Random random, int minValue, int maxValue, bool inclusiveUpperBound = false)
{
if (random == null)
Throw.ArgumentNullException(Argument.random);
if (minValue == maxValue)
return minValue;
if (maxValue < minValue)
Throw.ArgumentOutOfRangeException(Argument.maxValue, Res.MaxValueLessThanMinValue);
uint range = (uint)(maxValue - minValue);
bool shift = false;
if (inclusiveUpperBound)
{
if (range == UInt32.MaxValue)
return random.NextInt32();
range += 1;
shift = maxValue == Int32.MaxValue;
}
if (!shift)
return random.Next(minValue, (int)(minValue + range));
Debug.Assert(minValue > Int32.MinValue, "Unconditional NextInt32 should have been called");
return random.Next(minValue - 1, (int)(minValue - 1 + range)) + 1;
}
/// <summary>
/// Returns a random <see cref="uint"/> value.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <returns>A 32-bit unsigned integer that is greater than or equal to 0 and less or equal to <see cref="UInt32.MaxValue">UInt32.MaxValue</see>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
[CLSCompliant(false)]
#if !NET35
[SecuritySafeCritical]
#endif
public static unsafe uint NextUInt32(this Random random)
{
#if !(NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0)
// In practice, in .NET Core 3.0 this is still slower than the fallback version but
// we hope the best for the future and at least we spare some heap allocation
Span<byte> bytes = stackalloc byte[4];
random.NextBytes(bytes);
#if NETSTANDARD2_1
return MemoryMarshal.Read<uint>(bytes); // Unsafe.As would be much faster but that is not available in Standard
#else
return Unsafe.As<byte, uint>(ref bytes[0]);
#endif // NETSTANDARD2_1
#else // !(NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0)
var bytes = new byte[4];
random.NextBytes(bytes);
fixed (byte* p = bytes)
return *(uint*)p;
#endif
}
/// <summary>
/// Returns a random <see cref="uint"/> value that is less or equal to the specified <paramref name="maxValue"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="maxValue">The upper bound of the random number returned.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 32-bit unsigned integer that is greater than or equal to 0 and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="maxValue"/> equals 0, then 0 is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
[CLSCompliant(false)]
public static uint NextUInt32(this Random random, uint maxValue, bool inclusiveUpperBound = false)
=> random.NextUInt32(0U, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="uint"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The inclusive lower bound of the random number returned.</param>
/// <param name="maxValue">The upper bound of the random number returned. Must be greater or equal to <paramref name="minValue"/>.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 32-bit unsigned integer that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="maxValue"/> is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>.</exception>
[CLSCompliant(false)]
public static uint NextUInt32(this Random random, uint minValue, uint maxValue, bool inclusiveUpperBound = false)
{
if (random == null)
Throw.ArgumentNullException(Argument.random);
if (minValue == maxValue)
return minValue;
if (maxValue < minValue)
Throw.ArgumentOutOfRangeException(Argument.maxValue, Res.MaxValueLessThanMinValue);
uint range = maxValue - minValue;
if (inclusiveUpperBound)
{
if (range == UInt32.MaxValue)
return random.NextUInt32();
range += 1;
}
if (range < Int32.MaxValue)
return (uint)random.Next((int)range) + minValue;
long low = (long)Int32.MaxValue - range;
return (uint)(random.Next((int)low, Int32.MaxValue) - low + minValue);
}
/// <summary>
/// Returns a random <see cref="long"/> value.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <returns>A 64-bit unsigned integer that is greater than or equal to <see cref="Int64.MinValue">Int64.MinValue</see> and less or equal to <see cref="Int64.MaxValue">Int64.MaxValue</see>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
#if !NET35
[SecuritySafeCritical]
#endif
public static unsafe long NextInt64(this Random random)
{
#if !(NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0)
// In practice, in .NET Core 3.0 this is still slower than the fallback version but
// we hope the best for the future and at least we spare some heap allocation
Span<byte> bytes = stackalloc byte[8];
random.NextBytes(bytes);
#if NETSTANDARD2_1
return MemoryMarshal.Read<long>(bytes); // Unsafe.As would be much faster but that is not available in Standard
#else
return Unsafe.As<byte, long>(ref bytes[0]);
#endif // NETSTANDARD2_1
#else // !(NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0)
var bytes = new byte[8];
random.NextBytes(bytes);
fixed (byte* p = bytes)
return *(long*)p;
#endif
}
/// <summary>
/// Returns a random <see cref="long"/> value that is less or equal to the specified <paramref name="maxValue"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="maxValue">The upper bound of the random number returned.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 64-bit signed integer that is greater than or equal to 0 and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="maxValue"/> equals 0, then 0 is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than 0.</exception>
public static long NextInt64(this Random random, long maxValue, bool inclusiveUpperBound = false)
=> random.NextInt64(0L, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="long"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The inclusive lower bound of the random number returned.</param>
/// <param name="maxValue">The upper bound of the random number returned. Must be greater or equal to <paramref name="minValue"/>.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 64-bit signed integer that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="maxValue"/> is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>.</exception>
public static long NextInt64(this Random random, long minValue, long maxValue, bool inclusiveUpperBound = false)
{
if (random == null)
Throw.ArgumentNullException(Argument.random);
if (minValue == maxValue)
return minValue;
if (maxValue < minValue)
Throw.ArgumentOutOfRangeException(Argument.maxValue, Res.MaxValueLessThanMinValue);
ulong range = (ulong)(maxValue - minValue);
if (inclusiveUpperBound)
{
if (range == UInt64.MaxValue)
return random.NextInt64();
range += 1;
}
ulong limit = UInt64.MaxValue - (UInt64.MaxValue % range);
ulong sample;
do
{
sample = random.NextUInt64();
}
while (sample > limit);
return (long)((sample % range) + (ulong)minValue);
}
/// <summary>
/// Returns a random <see cref="ulong"/> value.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <returns>A 64-bit unsigned integer that is greater than or equal to 0 and less or equal to <see cref="UInt64.MaxValue">UInt64.MaxValue</see>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
[CLSCompliant(false)]
#if !NET35
[SecuritySafeCritical]
#endif
public static unsafe ulong NextUInt64(this Random random)
{
#if !(NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0)
// In practice, in .NET Core 3.0 this is still slower than the fallback version but
// we hope the best for the future and at least we spare some heap allocation
Span<byte> bytes = stackalloc byte[8];
random.NextBytes(bytes);
#if NETSTANDARD2_1
return MemoryMarshal.Read<ulong>(bytes); // Unsafe.As would be much faster but that is not available in Standard
#else
return Unsafe.As<byte, ulong>(ref bytes[0]);
#endif // NETSTANDARD2_1
#else // !(NETFRAMEWORK || NETSTANDARD2_0 || NETCOREAPP2_0)
var bytes = new byte[8];
random.NextBytes(bytes);
fixed (byte* p = bytes)
return *(ulong*)p;
#endif
}
/// <summary>
/// Returns a random <see cref="ulong"/> value that is less or equal to the specified <paramref name="maxValue"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="maxValue">The upper bound of the random number returned.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 64-bit unsigned integer that is greater than or equal to 0 and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="maxValue"/> equals 0, then 0 is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
[CLSCompliant(false)]
public static ulong NextUInt64(this Random random, ulong maxValue, bool inclusiveUpperBound = false)
=> random.NextUInt64(0UL, maxValue, inclusiveUpperBound);
/// <summary>
/// Returns a random <see cref="ulong"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The inclusive lower bound of the random number returned.</param>
/// <param name="maxValue">The upper bound of the random number returned. Must be greater or equal to <paramref name="minValue"/>.</param>
/// <param name="inclusiveUpperBound"><see langword="true"/> to allow that the generated value is equal to <paramref name="maxValue"/>; otherwise, <see langword="false"/>. This parameter is optional.
/// <br/>Default value: <see langword="false"/>.</param>
/// <returns>A 64-bit unsigned integer that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.
/// If <paramref name="inclusiveUpperBound"/> is <see langword="false"/>, then <paramref name="maxValue"/> is an exclusive upper bound; however, if <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="maxValue"/> is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>.</exception>
[CLSCompliant(false)]
public static ulong NextUInt64(this Random random, ulong minValue, ulong maxValue, bool inclusiveUpperBound = false)
{
if (random == null)
Throw.ArgumentNullException(Argument.random);
if (minValue == maxValue)
return minValue;
if (maxValue < minValue)
Throw.ArgumentOutOfRangeException(Argument.maxValue, Res.MaxValueLessThanMinValue);
ulong range = maxValue - minValue;
if (inclusiveUpperBound)
{
if (range == UInt64.MaxValue)
return random.NextUInt64();
range += 1;
}
ulong limit = UInt64.MaxValue - (UInt64.MaxValue % range);
ulong sample;
do
{
sample = random.NextUInt64();
}
while (sample > limit);
return (sample % range) + minValue;
}
#endregion
#region Floating-point types
/// <summary>
/// Returns a random <see cref="float"/> value that is greater than or equal to 0.0 and less than 1.0.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <returns>A single-precision floating point number that is greater than or equal to 0.0 and less than 1.0.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
public static float NextSingle(this Random random)
{
if (random == null)
Throw.ArgumentNullException(Argument.random);
return (float)random.NextDouble();
}
/// <summary>
/// Returns a random <see cref="float"/> value that is less or equal to the specified <paramref name="maxValue"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="maxValue">The upper bound of the random number returned.</param>
/// <param name="scale">The scale to use to generate the random number. This parameter is optional.
/// <br/>Default value: <see cref="FloatScale.Auto"/>.</param>
/// <returns>A single-precision floating point number that is greater than or equal to 0.0 and less or equal to <paramref name="maxValue"/>.</returns>
/// <remarks>
/// <para>In most cases return value is less than <paramref name="maxValue"/>. Return value can be equal to <paramref name="maxValue"/> in very edge cases.
/// With <see cref="FloatScale.ForceLinear"/> <paramref name="scale"/> the result will be always less than <paramref name="maxValue"/>.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than 0.0
/// <br/>-or-.
/// <br/><paramref name="scale"/> is not a valid value of <see cref="FloatScale"/>.</exception>
public static float NextSingle(this Random random, float maxValue, FloatScale scale = FloatScale.Auto)
=> random.NextSingle(0f, maxValue, scale);
/// <summary>
/// Returns a random <see cref="float"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The lower bound of the random number returned.</param>
/// <param name="maxValue">The upper bound of the random number returned. Must be greater or equal to <paramref name="minValue"/>.</param>
/// <param name="scale">The scale to use to generate the random number. This parameter is optional.
/// <br/>Default value: <see cref="FloatScale.Auto"/>.</param>
/// <returns>A single-precision floating point number that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.</returns>
/// <remarks>
/// <para>In most cases return value is less than <paramref name="maxValue"/>. Return value can be equal to <paramref name="maxValue"/> in very edge cases such as
/// when <paramref name="minValue"/> is equal to <paramref name="maxValue"/> or when integer parts of both limits are beyond the precision of the <see cref="double"/> type.</para>
/// With <see cref="FloatScale.ForceLinear"/> <paramref name="scale"/> the result will be always less than <paramref name="maxValue"/>.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>
/// <br/>-or-
/// <br/><paramref name="scale"/> is not a valid value of <see cref="FloatScale"/>.</exception>
public static float NextSingle(this Random random, float minValue, float maxValue, FloatScale scale = FloatScale.Auto)
{
static float AdjustValue(float value) => Single.IsNegativeInfinity(value) ? Single.MinValue : (Single.IsPositiveInfinity(value) ? Single.MaxValue : value);
// both are the same infinity
if (Single.IsPositiveInfinity(minValue) && Single.IsPositiveInfinity(maxValue) || Single.IsNegativeInfinity(minValue) && Single.IsNegativeInfinity(maxValue))
Throw.ArgumentOutOfRangeException(Argument.minValue);
return (float)random.NextDouble(AdjustValue(minValue), AdjustValue(maxValue), scale);
}
/// <summary>
/// Returns a random <see cref="double"/> value that is less or equal to the specified <paramref name="maxValue"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="maxValue">The upper bound of the random number returned.</param>
/// <param name="scale">The scale to use to generate the random number. This parameter is optional.
/// <br/>Default value: <see cref="FloatScale.Auto"/>.</param>
/// <returns>A double-precision floating point number that is greater than or equal to 0.0 and less or equal to <paramref name="maxValue"/>.</returns>
/// <remarks>
/// <para>In most cases return value is less than <paramref name="maxValue"/>. Return value can be equal to <paramref name="maxValue"/> in very edge cases.
/// With <see cref="FloatScale.ForceLinear"/> <paramref name="scale"/> the result will be always less than <paramref name="maxValue"/>.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than 0.0
/// <br/>-or-
/// <br/><paramref name="scale"/> is not a valid value of <see cref="FloatScale"/>.</exception>
public static double NextDouble(this Random random, double maxValue, FloatScale scale = FloatScale.Auto)
=> random.NextDouble(0d, maxValue, scale);
/// <summary>
/// Returns a random <see cref="double"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The lower bound of the random number returned.</param>
/// <param name="maxValue">The upper bound of the random number returned. Must be greater or equal to <paramref name="minValue"/>.</param>
/// <param name="scale">The scale to use to generate the random number. This parameter is optional.
/// <br/>Default value: <see cref="FloatScale.Auto"/>.</param>
/// <returns>A double-precision floating point number that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.</returns>
/// <remarks>
/// <para>In most cases return value is less than <paramref name="maxValue"/>. Return value can be equal to <paramref name="maxValue"/> in very edge cases such as
/// when <paramref name="minValue"/> is equal to <paramref name="maxValue"/> or when integer parts of both limits are beyond the precision of the <see cref="double"/> type.</para>
/// With <see cref="FloatScale.ForceLinear"/> <paramref name="scale"/> the result will be always less than <paramref name="maxValue"/>.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>
/// <br/>-or-
/// <br/><paramref name="scale"/> is not a valid value of <see cref="FloatScale"/>.</exception>
[SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")]
public static double NextDouble(this Random random, double minValue, double maxValue, FloatScale scale = FloatScale.Auto)
{
if (random == null)
Throw.ArgumentNullException(Argument.random);
if (Double.IsPositiveInfinity(minValue) && Double.IsPositiveInfinity(maxValue) || Double.IsNegativeInfinity(minValue) && Double.IsNegativeInfinity(maxValue))
Throw.ArgumentOutOfRangeException(Argument.minValue);
if (Double.IsNaN(minValue) || Double.IsNaN(maxValue))
Throw.ArgumentOutOfRangeException(Double.IsNaN(minValue) ? Argument.minValue : Argument.maxValue);
if (maxValue < minValue)
Throw.ArgumentOutOfRangeException(Argument.maxValue, Res.MaxValueLessThanMinValue);
if (!Enum<FloatScale>.IsDefined(scale))
Throw.EnumArgumentOutOfRange(Argument.scale, scale);
return DoGetNextDouble(random, minValue, maxValue, scale);
}
/// <summary>
/// Returns a random <see cref="decimal"/> value that is greater than or equal to 0.0 and less than 1.0.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <returns>A decimal floating point number that is greater than or equal to 0.0 and less than 1.0.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
public static decimal NextDecimal(this Random random)
{
if (random == null)
Throw.ArgumentNullException(Argument.random);
decimal result;
do
{
// The hi argument of 0.9999999999999999999999999999m is 542101086.
// (MaxInt, MaxInt, 542101086) is actually bigger than 1 but in practice the loop almost never repeats.
result = new Decimal(random.NextInt32(), random.NextInt32(), random.Next(542101087), false, 28);
} while (result >= 1m);
return result;
}
/// <summary>
/// Returns a random <see cref="decimal"/> value that is less or equal to the specified <paramref name="maxValue"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="maxValue">The upper bound of the random number returned.</param>
/// <param name="scale">The scale to use to generate the random number. This parameter is optional.
/// <br/>Default value: <see cref="FloatScale.Auto"/>.</param>
/// <returns>A decimal floating point number that is greater than or equal to 0.0 and less or equal to <paramref name="maxValue"/>.</returns>
/// <remarks>
/// <para>In most cases return value is less than <paramref name="maxValue"/>. Return value can be equal to <paramref name="maxValue"/> in very edge cases.
/// With <see cref="FloatScale.ForceLinear"/> <paramref name="scale"/> the result will be always less than <paramref name="maxValue"/>.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than 0.0
/// <br/>-or-
/// <br/><paramref name="scale"/> is not a valid value of <see cref="FloatScale"/>.</exception>
public static decimal NextDecimal(this Random random, decimal maxValue, FloatScale scale = FloatScale.Auto)
=> NextDecimal(random, 0m, maxValue, scale);
/// <summary>
/// Returns a random <see cref="decimal"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The lower bound of the random number returned.</param>
/// <param name="maxValue">The upper bound of the random number returned. Must be greater or equal to <paramref name="minValue"/>.</param>
/// <param name="scale">The scale to use to generate the random number. This parameter is optional.
/// <br/>Default value: <see cref="FloatScale.Auto"/>.</param>
/// <returns>A single-precision floating point number that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.</returns>
/// <remarks>
/// <para>In most cases return value is less than <paramref name="maxValue"/>. Return value can be equal to <paramref name="maxValue"/> in very edge cases such as
/// when <paramref name="minValue"/> is equal to <paramref name="maxValue"/>.</para>
/// With <see cref="FloatScale.ForceLinear"/> <paramref name="scale"/> the result will be always less than <paramref name="maxValue"/>.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>
/// <br/>-or-
/// <br/><paramref name="scale"/> is not a valid value of <see cref="FloatScale"/>.</exception>
public static decimal NextDecimal(this Random random, decimal minValue, decimal maxValue, FloatScale scale = FloatScale.Auto)
{
if (random == null)
Throw.ArgumentNullException(Argument.random);
if (maxValue < minValue)
Throw.ArgumentOutOfRangeException(Argument.maxValue, Res.MaxValueLessThanMinValue);
if (!Enum<FloatScale>.IsDefined(scale))
Throw.EnumArgumentOutOfRange(Argument.scale, scale);
if (minValue == maxValue)
return minValue;
bool posAndNeg = minValue < 0m && maxValue > 0m;
decimal minAbs = Math.Min(Math.Abs(minValue), Math.Abs(maxValue));
decimal maxAbs = Math.Max(Math.Abs(minValue), Math.Abs(maxValue));
// if linear scaling is forced...
if (scale == FloatScale.ForceLinear
// or we use auto scaling and maximum is UInt16 or when the difference of order of magnitude is smaller than 4
|| (scale == FloatScale.Auto && (maxAbs <= UInt16.MaxValue || !posAndNeg && maxAbs / 16m < minAbs)))
{
return NextDecimalLinear(random, minValue, maxValue);
}
int sign;
if (!posAndNeg)
sign = minValue < 0m ? -1 : 1;
else
{
// if both negative and positive results are expected we select the sign based on the size of the ranges
decimal sample = random.NextDecimal();
var rate = minAbs / maxAbs;
var absMinValue = Math.Abs(minValue);
bool isNeg = absMinValue <= maxValue
? rate / 2m > sample
: rate / 2m < sample;
sign = isNeg ? -1 : 1;
// now adjusting the limits for 0..[selected range]
minAbs = 0m;
maxAbs = isNeg ? absMinValue : Math.Abs(maxValue);
}
// We don't generate too small exponents for big ranges because
// that would cause too many almost zero results
decimal minExponent = minAbs == 0m ? -5m : minAbs.Log10();
decimal maxExponent = maxAbs.Log10();
if (minExponent.Equals(maxExponent))
return minValue;
// We decrease exponents only if the given range is already small.
if (maxExponent < minExponent)
minExponent = maxExponent - 4;
decimal result;
do
{
result = sign * 10m.Pow(NextDecimalLinear(random, minExponent, maxExponent));
} while (result < minValue || result > maxValue);
return result;
}
#endregion
#region Char/String
/// <summary>
/// Returns a random <see cref="char"/> value that is within a specified range.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minValue">The inclusive lower bound of the random character returned. This parameter is optional.
/// <br/>Default value: <see cref="Char.MinValue">Char.MinValue</see>.</param>
/// <param name="maxValue">The inclusive upper bound of the random character returned. Must be greater or equal to <paramref name="minValue"/>. This parameter is optional.
/// <br/>Default value: <see cref="Char.MaxValue">Char.MaxValue</see>.</param>
/// <returns>A <see cref="char"/> value that is greater than or equal to <paramref name="minValue"/> and less or equal to <paramref name="maxValue"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="maxValue"/> is less than <paramref name="minValue"/>.</exception>
public static char NextChar(this Random random, char minValue = Char.MinValue, char maxValue = Char.MaxValue)
=> minValue == Char.MinValue && maxValue == Char.MaxValue
? (char)random.NextUInt16()
: (char)random.NextUInt16(minValue, maxValue, true);
/// <summary>
/// Returns a random <see cref="string"/> that has the length between the specified range and consists of the specified <paramref name="allowedCharacters"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minLength">The inclusive lower bound of the length of the returned string.</param>
/// <param name="maxLength">The inclusive upper bound of the length of the returned string. Must be greater or equal to <paramref name="minLength"/>.</param>
/// <param name="allowedCharacters">A string containing the allowed characters. Recurring characters may appear in the result more frequently than others.</param>
/// <returns>A <see cref="string"/> value that has the length greater than or equal to <paramref name="minLength"/> and less and less or equal to <paramref name="maxLength"/>
/// and contains only the specified characters.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> or <paramref name="allowedCharacters"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="minLength"/> is less than 0 or <paramref name="maxLength"/> is less than <paramref name="minLength"/></exception>
/// <exception cref="ArgumentException"><paramref name="allowedCharacters"/> is empty.</exception>
#if !NET35
[SecuritySafeCritical]
#endif
public static unsafe string NextString(this Random random, int minLength, int maxLength, string allowedCharacters)
{
if (random == null)
Throw.ArgumentNullException(Argument.random);
if (minLength < 0)
Throw.ArgumentOutOfRangeException(Argument.minLength, Res.ArgumentMustBeGreaterThanOrEqualTo(0));
if (maxLength < minLength)
Throw.ArgumentOutOfRangeException(Argument.maxLength, Res.MaxLengthLessThanMinLength);
if (allowedCharacters == null)
Throw.ArgumentNullException(Argument.allowedCharacters);
if (allowedCharacters.Length == 0)
Throw.ArgumentException(Argument.allowedCharacters, Res.ArgumentEmpty);
int length = random.NextInt32(minLength, maxLength, true);
if (length == 0)
return String.Empty;
string result = new String('\0', length);
fixed(char* s = result)
fixed(char* set = allowedCharacters)
FillChars(random, new MutableString(s, length), new MutableString(set, allowedCharacters.Length));
return result;
}
/// <summary>
/// Returns a random <see cref="string"/> that has the length between the specified range and consists of the specified <paramref name="allowedCharacters"/>.
/// </summary>
/// <param name="random">The <see cref="Random"/> instance to use.</param>
/// <param name="minLength">The inclusive lower bound of the length of the returned string.</param>
/// <param name="maxLength">The inclusive upper bound of the length of the returned string. Must be greater or equal to <paramref name="minLength"/>.</param>
/// <param name="allowedCharacters">An array containing the allowed characters. Recurring characters may appear in the result more frequently than others.</param>
/// <returns>A <see cref="string"/> value that has the length greater than or equal to <paramref name="minLength"/> and less and less or equal to <paramref name="maxLength"/>
/// and contains only the specified characters.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random"/> or <paramref name="allowedCharacters"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="minLength"/> is less than 0 or <paramref name="maxLength"/> is less than <paramref name="minLength"/></exception>
/// <exception cref="ArgumentException"><paramref name="allowedCharacters"/> is empty.</exception>
#if !NET35
[SecuritySafeCritical]
#endif
public static unsafe string NextString(this Random random, int minLength, int maxLength, char[] allowedCharacters)
{
if (random == null)