Click here to Skip to main content
15,867,833 members
Everything / Random

Random

random

Great Reads

by Igor Krein
A library of simple extension methods that could be useful for data generation tasks
by Peter Occil
Algorithms to turn biased "coin flips" into biased "coin flips", and how to code them.
by Kornfeld Eliyahu Peter
“Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch!” - LEWIS CARROLL
by Peter Occil
Python code for partially-sampled random numbers for accurate arbitrary-precision sampling

Latest Articles

by Alexey Shtykov
The thing that could generate pseudo random numbers faster than standard library does
by Member 4201813
How to calculate transition matrix for linear pseudo-random number generator manipulating its internal state
by Jack Devey
This post delves into the perplexing Monty Hall paradox, examining the probabilities associated with sticking or switching doors in the game scenario.
by ToughDev
How to allow only numeric input in TextBox

All Articles

Sort by Score

Random 

29 Jul 2016 by Igor Krein
A library of simple extension methods that could be useful for data generation tasks
2 Sep 2021 by Peter Occil
Algorithms to turn biased "coin flips" into biased "coin flips", and how to code them.
30 Oct 2017 by Kornfeld Eliyahu Peter
“Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch!” - LEWIS CARROLL
2 Feb 2016 by CPallini
I would do the opposite, that is directly random generate a prime number. You know, under 10,000,000,000 there are 455,052,511 prime numbers (see How many primes are there?[^]) so you can randomlly choose r between 0 and 455,052,510 and then use the rth prime number. Possibly a pre-computed ...
16 Mar 2022 by Peter Occil
Python code for partially-sampled random numbers for accurate arbitrary-precision sampling
13 Jun 2023 by Jack Devey
This post delves into the perplexing Monty Hall paradox, examining the probabilities associated with sticking or switching doors in the game scenario.
5 Feb 2016 by BillWoodruff
The problem in your code is that you call 'CheckIfPrime passing it a 'BigInteger, but its parameter is: 'int.There's also a problem in that the Math library 'Sqrt Function will not accept Type 'BigInteger. You can work around that with this:BigInteger sqrt =...
11 Dec 2015 by Sergey Alexandrovich Kryukov
Probably this is because you act in identical way: create the brand new rd and genEngine objects each time you need a random value. You need to create and initialize these objects only once in the whole life cycle of your process. For example, create such objects in main and pass the pointer to...
8 Aug 2013 by Punamchand Dhuppad
Hello Ahmad, You can use this code -- private string GetRandomString() { Random rand = new Random((int)DateTime.Now.Ticks); int randomIndex1 = rand.Next(100, 999); int randomIndex2 = rand.Next(10000, 99999); string randstring =...
26 Dec 2013 by King Fisher
just use this:var chars = "0123456789";var random = new Random();var result = new string(Enumerable.Repeat(chars, 6).Select(s => s[random.Next(s.Length)]).ToArray());string random_num;password = result.ToString();
29 Dec 2020 by Peter Occil
Some of the most common random generation questions based on a Q&A site question analysis.
5 Jan 2022 by OriginalGriff
Quote: Well, your advices are good but I can`t lose my scholarship, so if there`s a volunteer to help with a code, + to your karma There are several problems here: 1) You clearly have misunderstood karma. We wouldn't get good karma for doing...
23 Jul 2013 by OriginalGriff
The way I do it is not to use an array but a List instead:List newOrder = new List();while (users.Count > 0) { int removeIndex = rand.Next(users.Count) newOrder.Add(users[removeIndex]); users.RemoveAt(removeIndex); }What this does is select an item at...
30 Jul 2013 by Ron Beyer
Simple...//Place these two as global class variablesList myChars = new List();Random rnd = new Random(5252);private void FillChars(){ for (int i = 0; i
2 Dec 2013 by Sergey Alexandrovich Kryukov
Your mistake is very common: you need to create an instance of Random only once in the lifetime of your application domain, not in the loop, but before it. Move two first lines inside loop outside of the loop, before it.—SA
22 Feb 2016 by Richard MacCutchan
You need to seed the random generator so it starts at a different value each time. Using the clock time in milliseconds is a useful way of doing it. See Random Constructor (Int32) (System)[^].
13 Apr 2016 by OriginalGriff
Well...What happens if num1 is 11 and num2 is 14, and RandOperation is 74?It passes this test: if (RandOperation % 2 == 0)But it fails this test: if (num2 % num1 == 0 & num2 > num1)And it fails this test: if (num1 % num2 == 0 &...
14 Jul 2016 by OriginalGriff
You can't change RAND_MAX because it's a constant, and its implementation dependant: it can be set to the maximum value that can be stored in a signed integer on the system the compiler is targeting (but it doesn't have to be, it can be smaller): on Windows based systems it is set to 32767 for...
24 Jan 2017 by OriginalGriff
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.Try it yourself, you may find it...
27 May 2018 by Patrice T
Quote: I am almost finished with this program, other than I cannot figure out how to get a new set of random numbers when the user chooses to re-roll (rolling R when prompted the first time) You need to workout the logic, a simple method is take output and note what is going on behind the hood....
23 May 2021 by Richard Deeming
Signed integers in .NET are stored using Two's Complement: Signed number representations - Wikipedia[^] If you keep incrementing a positive integer past its maximum value, it will become negative. If you want to throw an exception if that...
10 Jun 2021 by OriginalGriff
Simplest way is to make a generic method which accepts a list and "shuffles" them: place all the questions (correct and incorrect) in a List and pass it to the method. private List Shuffle(List input) { ...
12 Feb 2023 by Divya Ulasala
Examining the differences between java.util.Random, java.security.SecureRandom, and java.util.concurrent.ThreadLocalRandom to generate random numbers
11 Apr 2013 by E.F. Nijboer
Why not use the variables directly? The if statements aren't necessary. You might just want to check if the range of randoma/randomb is in the lower and upper boundary of the array:whatChoice3 = whatList[randoma];desChoice2 = descriptionList[randomb];Good luck!
29 May 2014 by BobJanova
This is a silly application, but presumably you know that. That algorithm's not useful for anything.Console and windowed desktop applications have somewhat different use paradigms, so it isn't so much a case of 'converting' as working out how your core algorithm should be presented in the...
5 Jan 2015 by OriginalGriff
That isn't quite how it works: you set up an email address which automatically dumps all emails, and you send the message from that - you can't just "invent" an email address and use that! Particularly if it is on someone else's system...that's misrepresentation if nothing else.Just create...
14 Feb 2015 by Richard MacCutchan
Random strings of what; letters, numbers, pictures, types of cheese? Please edit your question and explain exactly what problem you are trying to solve. You could also study the Java API at http://docs.oracle.com/javase/7/docs/api/java/util/Random.html[^].
3 Feb 2016 by Patrice T
Your code have numerous problems.One of them is efficiency, here is your code and 2 trivial changes: public bool CheckIfPrime(int n) //to check if the random number generated is prime { var isPrime = true; var sqrt = Math.Sqrt(n); for...
6 Feb 2016 by HitsugayaHisagi
So I've tried this code, and it works okay to me. Random rand = new Random(); BigInteger p = BigInteger.genPseudoPrime(128, 10, rand); txtP.Text = p.ToString(); Random rand2 = new Random(); BigInteger q = BigInteger.genPseudoPrime(128,...
22 Feb 2016 by OriginalGriff
First off, move the Random instance outside any method, and make it private: class GenData { private Random rand = new Random(); public void GenStats() {That way, it isn't recreated each time you call the method, which can mean repeated values. That's...
11 Oct 2016 by F-ES Sitecore
Random numbers use what's known as a "seed" as the starting value to a mathematical equation that simulates randomness. If you give the random number generator the same seed you'll always get the same sequence of values, so the first number will always be the same. You can specify the seed in...
11 May 2017 by Dave Kreskowiak
If you're asking such a basic question you REALLY need to pickup a beginners book on C# and work through it. You need to assign the value to some other variable in order for anything to make sense and be usable. int result = int1 - int2;
24 Sep 2017 by OriginalGriff
You can't, almost certainly. The bulk of the functionality is likely to be at the server, and you have no access to that code at all - the only code you have access to is the client HTML and Javascript which is sent to your computer as the web page. You can inspect that if you like: right click...
9 Oct 2017 by OriginalGriff
You are required to generate odd numbers only: so the value you add on - C - must be odd, and the original value - rand.nextInt(A) * B must be even, which means that B must be even. So your tutor has selected B = 2, C = 51 which fulfils the "must be odd" requirement, and offsets the number so...
31 Mar 2018 by OriginalGriff
The simplest way is: as you sample the elements, remove them from the collection.
17 Sep 2018 by Richard MacCutchan
counter = 0 while 1: passwd = ''.join(random.sample(sbc,passlen)) if passwd == 'abc': print('password matched') break print(passwd, "does not match") counter += 1 print(counter, "iterations")
2 Feb 2019 by OriginalGriff
I don't think you are ever going to find exactly what you want, so that means a custom solution - writing the code, basically. And if you aren't a coder, then you will have to find a coder to do it for you - but this is not the place for that, we do not arrange commissions here. I suggest you...
21 Oct 2019 by Member 12696135
OK, Just throwing this out there... EASY PRIME GENERATION IN C#.NET I think this approach will be far more useful to most readers than some of the suggestions above. Forgive me, but after reading this thread I figured that this little trick is sorely missing from the discussion. I don't...
21 Mar 2020 by Patrice T
Quote: i want mathematical equation or function to get number between two number Short answer is "it does not exist". Both requests are mutually exclusive. The closest thing is a "shuffle" algorithm, just like you shuffle a deck of playing cards...
21 Mar 2020 by OriginalGriff
Random numbers are just that: random. And that means that the next number returned by a generator does not rely on previous results at all: it is as likely to generate any number in the sequence each time you try to get a new random number. And...
7 Jan 2021 by CPallini
You are using the octal format specifier %o while you should use the decimal one %d. For example, the (decimal) number 50 becomes by 62 = 6*8+2 in octal representation. By the way, you know, you could write your program in a more compact way:...
3 May 2021 by CPallini
A very approach is by construction: Randomly generate the second (integer) number, say n2. Randomly generate an integer factor, say f. Let the first number, say n1, be equal to second number multiplied by the factor f (namely n1 = n2 * f)
12 May 2021 by OriginalGriff
The solution is simpler: don't use Random like that. Declare a single Random instance at class level (static is fine) and use that for both values: private static Random rand = new Random(); ... int maxprvni = 10; int...
23 May 2021 by Patrice T
Advice: Learn to indent properly your code, it show its structure and it helps reading and understanding. It also helps spotting structures mistakes. Random number = new Random(); int maxValue = 10; int total = 0; int firstNumber =...
23 May 2021 by Richard MacCutchan
You are incrementing secondNumber before you do the division, so the number could already have exceeded firstNumber. Change the loops to straight while: if (firstNumber
15 Jun 2021 by lmoelleb
Learn to debug. It is simple, and the time investment pays of immediately. I understand that it might seem like "I have a lot to learn, so I will put that off and learn it later - for now I just want my program working", but that is a REALLY bad...
15 Jun 2021 by Richard MacCutchan
while (failResult == resultNumber && failResult == wrongResult) A variable cannot be equal to two different values at the same time.
18 Aug 2021 by Richard Deeming
Generate a random number between 65280 (0x00ff00) and 16711680 (0xff0000). Math.random() - JavaScript | MDN[^] function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) +...
24 May 2022 by CHill60
Look at the line random_char = random.choice(letters) + random.choice(numbers) + random.choice(symbols) For every iteration of the loop you are adding three characters to the array. You could change your loop to be something like for char in...
24 May 2022 by Richard MacCutchan
You need to select either letters or numbers or symbols each time, not all three. Here is a sample that will do that automatically: import random letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',...
18 Oct 2022 by Manojkumar-dll
Finally found it var result= "0"; if(Desired condition>0) { Random random = new Random(); double val = (random.NextDouble() * (max - min)...
20 Nov 2022 by OriginalGriff
To add to what Greame says, don't do it like that. Declare a single Random instance at class level:private Random random = new Random(); Or: private static Random random = new Random(); and us that instead. The reason why is simple: when you...
28 Mar 2013 by kastriotlimani
Hi, i am a beginner at coding, and i am making a little game where a character is capturing some dots generated randomly.Now i need each dot to be an image (same image for all), but i cant find out how to do it.This is a piece of what I did:Rectangle[] rects;rects = new...
11 Apr 2013 by dteece1
In JS, I'm trying to make a random compliment generator using Arrays. The goal is that when the program is run, it takes a random part from each array and then displays the string. I'm sure i've used far too many variables here, but I am struggling. The variables at the top of the page...
11 Apr 2013 by CPallini
You don't need the if chains: you have arrays!For instance the choiche in whatList could be coded this way: var rwl = Math.floor((Math.random()*6)); // generate a random number between 0..5 (included) var whatChoice = whatList[rwl]; // use the random number to index the array.
12 May 2013 by Sergey Alexandrovich Kryukov
Unfortunately, this code does not deserve debugging, because this is not how a software developer writes code. A software developer would never repeat identical declaration several times like your 10 Boolean variables. A software developer would declare an array or use some collection. A...
12 May 2013 by Ron Beyer
First, yes, bad programming...However getting to the point, a random number is just that, random. It is not guaranteed to give you any value, only a value within that range. So lets say you run this and it NEVER randomly gives you the value of 2, your code will continue to loop forever until...
3 Jun 2013 by Member 10056564
I made a Bingo game and use a randomly generated set of 75 ball numbers for each new game.The array is public and is aryRnd(75). This works well for me and is reasonably fast.You can then use the array as needed in the project.Dim valueRnd As String = ""Dim ballCnt As Single =...
23 Jul 2013 by BulletVictim
Good day all.Let me start by saying I am missing something obvious and I know, but cant seem to get it.I am working on a randomization application.I need to pull a list of active users(with USERID's) from my database, load them into a Datagridview, Well that works fine, now after that I...
6 Aug 2013 by mbue
At the beginning i==0 therefore the value of check in the first do{}while loop is always false. The function runs in an infinite loop.to avoid this take a look: for(i=0;i
6 Aug 2013 by Sergey Alexandrovich Kryukov
Never ever use loop variable declared outside of the loop!—SA
6 Aug 2013 by Sergey Alexandrovich Kryukov
Never ever use loop variable declared outside of the loop!—SA
8 Aug 2013 by Ahmad Abd-Elghany
hello i want to generate a unique id just like this #OWD-716-46324 how can i achieve it
17 Sep 2013 by DaveyM69
Have you had a look at this[^]?
17 Sep 2013 by Uknownymous
Im planning to make an entrance examination windows application in vb.net,VS2012, and i want to randomly select questions from database(i use ms sql server 2005 express) and not repeating every question. I have a limited idea in using binding navigator... is it possible to randomly select using...
17 Sep 2013 by PIEBALDconsult
Often (with SQL Srver anyway), you can sort the rows by NEWID() to get a fairly random order.But, chances are, you don't want it to be completely random.
24 Sep 2013 by OriginalGriff
First off, move the srand call outside the loop - if you call it each time you go round there is a very good chance that all your "random" numbers will be the same! :laugh:Second,y, if you want 50 numbers between 1 and 25 then you want to loop 50 times, not 25, and use a maximum of 25, not...
11 Oct 2013 by ASP.NET Community
This is simple and effective method for generation of a random password Public Function GeneratePassword(ByVal PwdLength As Integer) As String   
9 Dec 2013 by IAmABadCoder
Hi, I have an enum called Gender and I was wondering how I would cast the enum to a random int between 0 and 1.public enum Gender : int{ Male = 0, Female = 1,}
9 Dec 2013 by ArunRajendra
I am not sure. Just give a try good luck.Random rnd1 = new Random();Gender g = (Gender)rnd1.Next(2);
9 Dec 2013 by BillWoodruff
The Enum you show is equivalent to:public enum Gender{ Male, Female}Here's an example of a method that will return either Gender.Male or Gender.Female at random:Random rand = new Random();private Gender randomGender(){ return (rand.Next(2) == 0) ? Gender.Male :...
26 Dec 2013 by ketan italiya
I want 6 digit random number,which shouldn't be repetative.number must is in between 000000 to 999999I mean it must contain 6 digits.i use this code for that.Random rnd = new Random(); int s = rnd.Next(000000, 999999);ingbal i =new ingbal(); i.Activation_Code =...
29 May 2014 by OriginalGriff
The algorithm remains the same - unlikely to help you brute force attack a password in a reasonable time period, thankfully - all you need is to output them differently: instead of Console.Writeline, you need to pass them back to the "calling process" in some way: either by passing a ListBox...
12 Aug 2014 by Coder93
I need to generate random latitude and longitude which is located in city (one city) for my application written in Java, how can I generate it?
19 Nov 2014 by Member 11246689
we have a table of 50k items and we display it at search page with random sort and 10 items per page , and there is some filtersrandom with/without seed is very slownote that items are 3 category and first category should be display first with random order , then the second category with...
21 Nov 2014 by OriginalGriff
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.Try it yourself, you may find it...
22 Nov 2014 by Ishpreet Kaur
The solution is:$var=rand($min,$max);if($var%3 == 0){echo "number is divisible by 3";}else{echo "number is not divisible by 3 and remainder is: ".($var%3);}
5 Dec 2014 by Member 11287540
I've been modifying the code for the past few day adding different things. I made my dice in a separate file to make sure they looked right then copied them over to my game, but when I try to call the functions in my game nothing happens. I don't even get a canvas. I'm not 100% sure what I"m...
17 Dec 2014 by Tomas Takac
You already declared a variable of Random class so you are on a good way. You basically randomly pick 9 characters from the string of allowed characters and store them in an array. Wne you are done you just create the password string from that array:Dim s As String =...
17 Dec 2014 by Afzaal Ahmad Zeeshan
You need to make a use of the Random class, to generate Random numbers. But, that would give you a Random integer, you can then use those numbers to call different alphabets at those indices. You can read my previous article to create Random strings for URLs, instead of using them in URLs...
5 Jan 2015 by eboolean
How to create Random e-mail adress for users' notifications in ASP.NET ?Like this;61e-2eb3af5-c7da98 -noreply@twitter.com
30 Jan 2015 by Reuben Cabrera
hi everyone. i have this problem. i was making a simple monopoly simulator and i needed a function that would generate random numbers from 1 to 6. i searched the net for the rand() func and yes it was working but the problem in my code that every time I run it, it seems to generate the same...
30 Jan 2015 by Anthony Fountaine
You should seed the rand function once at the beginning of your code.srand(time(NULL));
15 Feb 2015 by Dana Taha
I want generate 4 random name, type are Strings and put this random Strings without repeating to 4 Text Field in Java ?can you help me ? thank you ..
12 Dec 2015 by Are Riff
#include #include #include using std::cout;using std::cin;using std::endl;using std::ostream;// Random value generator functiondouble randomize(const double &minVal, const double &maxVal){ std::random_device rd; std::mt19937...
22 Feb 2016 by Keith Lewis
I'm new to coding, and just working on a little project to learn.I'm trying to produce multiple different versions of sets of attributes that I'll be inserting into a SQLite database.My current code prints the same numbers each time, ie:721213721213... etc.I guess...
11 Mar 2016 by log98
For instance take a board with a form which moves from left to right and vice versa , i want this to be random. Actually, i want the landing of a ship to be random. Sample code that I wrote.I want to work only in the x-axis.public partial class theForm : Form { int xx; ...
14 Jul 2016 by Aamir Yousafi
Dear all, I have been through the forums and Google and have found only complicated setups for random number generators that are more advanced than rand(). My problem with rand() is that I can't seem to change the RAND_MAX, and even when I do by using #undef and #define followed by the integer...
14 Jul 2016 by CPallini
If you can use C++ then have a look at this page: random - C++ Reference[^].
11 Oct 2016 by Tobias Wälde
Hey,just a quick question:I hava a button 'get Random'. If i press the button, the program sets the text of a label to this value.sometimes, if i press the button 2 times, it returns the same number.How can i avoid getting two same values?What I have tried:int newRandom =...
24 Jan 2017 by Patrice T
We do not do your HomeWork.HomeWork is not set to test your skills at begging other people to do your work, it is set to make you think and to help your teacher to check your understanding of the courses you have taken and also the problems you have at applying them. Any failure of you will...
11 May 2017 by Richard MacCutchan
int answer = mathquestion1 - mathquestion2;
17 Jun 2017 by Michael_Davies
Google is your friend, lots of answers and details; Random random = new Random(); int randomvalue = random.Next(a, b + 1); What do you mean by "on a number like (x)"?
17 Jun 2017 by RickZeeland
See this example: [dotnetperls]
17 Jun 2017 by Patrice T
Quote: how can i generate n random number between (a) and (b) that are around a number like (x)? C# have random function, first step is to read the documentation.
16 Jul 2017 by Atlapure Ambrish
You can do something like this before your if condition. Call the below method to get the path and then check if the path exists, if not create the directory. public string GetTemporaryDirectory() { string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); ...
18 Sep 2017 by Member 13380410
Hello guys, i am sitting on a game which i am programming at the time and i am facing the following problem: The game has a predefined exisiting polygon on a GMaps.net API using GoogleMaps as GMapsProvider. Now i need a random valid address which is existing inside the polygon on the map....
18 Sep 2017 by W Balboos, GHB
Address are arbitrary definitions on the landscape. You can, however pick out an arbitrary locations. Do this by using the rand function to generate GPS coordinates with the following two general possibilities. 1) Polygon is rectangular aligned, in phase, with the coordinate system: simply...
9 Oct 2017 by CPallini
Quote: 51 - 99, but the problem says the range is 50-99. Indeed taht's the range. But, unfortunately 50 is even, hence 51 is the first valid entry of the requested range.
19 Dec 2017 by Lilyanaa
Hi, in this code I'm generate random number in specific range, but I want the out put of array must be l101 l101 l102 l104 I mean adding the word "host" to every number that is generate randomly, how can do this please?? I'm sorry about my bad english What I have...