Click here to Skip to main content
15,891,905 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

How to generate many random various numbers?

Rate me:
Please Sign up or sign in to vote.
1.00/5 (2 votes)
12 Sep 2011CPOL 13.3K   10
Found this little peace of code in book and kept it.using System.Security.Cryptography;public static int RandomNumber(int maxvalue){ RandomGenerator random = RandomGenerator.Create(); byte[] r = new byte[1]; random.GetBytes(r); double val = (double)r[0]/byte.MaxValue; ...
Found this little peace of code in book and kept it.

C#
using System.Security.Cryptography;
public static int RandomNumber(int maxvalue)
{
  RandomGenerator random = RandomGenerator.Create();
  byte[] r = new byte[1];
  random.GetBytes(r);
  double val = (double)r[0]/byte.MaxValue;
  int i = (int)Math.Round(val * maxvalue, 0);
  return i; 
}


Like I said not exactly my peace of code.
So to whom, thans..

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Belgium Belgium
Developer within C#, Dynamics NAV (Navision), Php environments.

Comments and Discussions

 
GeneralRe: (A) A byte is restricted to max. 256 distinct values because... Pin
Ansgar Hellwig27-Sep-11 4:26
professionalAnsgar Hellwig27-Sep-11 4:26 
GeneralRe: OK for the kiddy's @home [A] please explain why by using the... Pin
kribo27-Sep-11 3:36
professionalkribo27-Sep-11 3:36 
GeneralRe: I did not say that the maximum value is restricted to 256, b... Pin
Ansgar Hellwig27-Sep-11 1:50
professionalAnsgar Hellwig27-Sep-11 1:50 
GeneralRe: Then I dare you to run the next console application, written... Pin
KenBonny27-Sep-11 1:47
KenBonny27-Sep-11 1:47 
GeneralRe: Please have a closer look to the source code. He is using a ... Pin
Ansgar Hellwig26-Sep-11 21:16
professionalAnsgar Hellwig26-Sep-11 21:16 
GeneralRe: If I call RandomNumber(1024), what's the probability that it... Pin
Henry.Ayoola19-Sep-11 0:55
Henry.Ayoola19-Sep-11 0:55 
GeneralReason for my vote of 1 Doesn't work Pin
Shahin Khorshidnia14-Sep-11 21:37
professionalShahin Khorshidnia14-Sep-11 21:37 
GeneralReason for my vote of 1 It restricts to 256 possible return ... Pin
Henry.Ayoola13-Sep-11 3:03
Henry.Ayoola13-Sep-11 3:03 
GeneralRe: OK you've lost me, say again...? Pin
kribo13-Sep-11 4:00
professionalkribo13-Sep-11 4:00 
OK you've lost me, say again...?
GeneralRe: I don't see it either, unless I'm missing something. The va... Pin
KenBonny14-Sep-11 0:05
KenBonny14-Sep-11 0:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.