Click here to Skip to main content
15,887,485 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 Title

Random 

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.
7 May 2023 by ToughDev
How to allow only numeric input in TextBox
16 Sep 2013 by ellasaro
So I have this weird problem,I wrote a program in Visual Studio 2010.At first I configured it so the binary would have an icon, lets call it icon A. Then I changed the configuration again and changed the icon to icon B. The problem is that if I copy/move my binary to my desktop the...
17 Sep 2013 by DaveyM69
Have you had a look at this[^]?
28 Jan 2013 by Member 9790449
I am a beginner and I want to have a code with a random number generator, but my code does not follow what I would like it to follow.... PLEASE HELP! . This is what have so far... please help with any corrections, improvements, etc. #include ;#include //drand...
27 Jan 2013 by uddhavh
You can use rand function in c++ i = rand();
29 Jan 2013 by Stefan_Lang
You appear to be confused about a number of things, most related to program flow and programming logic:1. You intialize a number of char variables and never change them, but then, later, you test their value. Apparently what you intended to do is compare the user input against the values you...
2 Sep 2021 by Peter Occil
Algorithms to turn biased "coin flips" into biased "coin flips", and how to code them.
20 Feb 2023 by gggustafson
In this first part, we look at the random arrangement of numbers on a player's Bingo card.
27 Feb 2023 by gggustafson
Print_Cards to produce PDF file containing specified number of unique Bingo cards
6 Jan 2022 by innapivov
Please help to write the C code Here is a version of a problem called the random walk. Assume that you`re very tired and dog leaves his lamppost on summer evenings and staggers randomly either two steps in the direction toward home or one step...
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...
6 Jan 2022 by KarstenK
Start with some Learn C tutorial. It wont be to hard if you can already code in some other language, but you need to respect the rules of C like a bunch of braces and declarations. Best is to write some functions and use struct. For some random...
2 Nov 2015 by Member 12108243
Alright so this is an in game command and it works perfect but I just can't figure out how to make decimal pc = num * rand / 100 because rand doesn't really define one number. internal class GambleCommand : Command { public GambleCommand() :...
2 Nov 2015 by George Jonsson
Maybe try decimal.Parse or decimal.TryParse, if you want to continue on the road of string conversions.decimal pc = num * decimal.Parse(rand) / 100;
2 Nov 2015 by Member 12108243
Alright I fixed it so I had to change it todecimal pc = decimal.Parse(rand) / num * 100;
2 Nov 2015 by Patrice T
First, you should try with integerint rand;...rand = rnd.Next(num, 0);And change the formulaint pc = rand * 100 / NUM;Should be better !
29 May 2014 by Member 10847268
Hello guys! I have this piece of code that I am willing to be converted to a windows forms application in c#!using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ComponentModel;using System.Data;using System.IO;namespace Bruteforce{ ...
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...
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...
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...
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...
14 Apr 2018 by dolfijn3000
so i'm working with perlin noise in c#. after experimenting with it i wanted to make a seammless perlin noise map. i want a map where the above edge of the map can continue in the bottom edge. is there someone that can help me with this ? What I have tried: searching the internet the only...
14 Apr 2018 by OriginalGriff
Quote: the answer was writtin in python i don't know python. Then you will either have to learn Python, or keep looking: we are not a "code conversion service".
29 Jul 2016 by Igor Krein
A library of simple extension methods that could be useful for data generation tasks
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
27 May 2018 by Member 13843522
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). Below is my code -- can anyone help me find out where I went wrong with syntax, seed, etc...? What I have...
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....
27 May 2018 by Richard MacCutchan
Create a function that does the rolling, and allow it to accept a parameter which tells it whether to seed the randomiser or not: int DiceRoll(bool seed = false) { if (seed) { // seed the randomiser srand((int)time(0)); } int roll = 1+rand()%6; // get a random...
27 May 2018 by CPallini
Try #include /// need this for srand() -- for random numbers #include /// need this for time() -- time #include /// need this for cout> using namespace std; /// need this for cout> int main() { srand(time(0)); cout
6 Jul 2021 by Happy kaul
0 I want to remove the single string and want to keep string with minimum length 3 and above i tried to access string with this if(result.string >= 3) but it is giving array length so i tried to access string but i cant. so please anybody who...
5 Jul 2021 by Greg Utas
I don't know Javascript but have a sense of what your code is doing. You're finding all combinations except for the empty string, which is a good start. But I see nothing in your code that filters out combinations of less than 3 letters. It looks...
6 Jul 2021 by Estys
Replace your return result; withreturn result.filter(x => x.length >= 3); Because the way you generate the combinations, you can't filter short combinations earlier. Cheers
19 Jan 2021 by Member 13987161
i'am trying to generate a random password using python random library where i've defined a number of alphabets(upper, lower & digit) in a variable and also defined the password length size should be 3(EXAMPLE), now using if statement i tried to check whether the random generated password would...
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")
16 Jul 2017 by RealFlare
Is it possible to create a folder in Temp with path.getrandomfilename? Thanks for trying to help me out if you do! :D What I have tried: Research, but nothing works. Maybe use this code: dim path as String = "D:\Mahesh" IF Not Directory.Exists(path) then Directory.CreateDirectory(path) End IF...
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()); ...
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
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 =...
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
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
3 Dec 2013 by Sal Razzaq
How to fairly pick items from a list
19 Feb 2024 by Alexey Shtykov
The thing that could generate pseudo random numbers faster than standard library does
15 Sep 2015 by Shvetsov Evgeniy
How to generate a random sequence of chars with the specified parameters (e.g., length, char sets, char count per set, etc.)
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   
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...
19 Dec 2017 by OriginalGriff
Quote: No, I want array must have "host101"... Your array can't hold values like "host101" - it can only hold integers. In order to get it to hold strings, you need to change it to an array that holds char pointers: char* a[50]; And then use malloc[^] to allocate space for each string inside...
19 Dec 2017 by Rick York
Assuming you have a random room number generated, you can make the string like this : char buffer[16]; sprintf( buffer, "host%d", roomNumber ); To generate the random room number I would use this : int GetRandomValue( int minval, int maxval ) { int span = maxval - minval; int rval...
24 Jan 2017 by Member 12324523
I need to generate images randomly on button click using c# private Image DrawText(String text, Font font, Color textColor, Color backColor){ //first, create a dummy bitmap just to get a graphics object Image img = new Bitmap(1, 1); Graphics drawing =...
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...
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...
16 Oct 2022 by Richard MacCutchan
See Random Class (System) | Microsoft Learn[^].
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)...
18 Oct 2022 by Manojkumar-dll
I want to generate random float numbers ranging 0.0 to 1.5 and to store it inside a variable the values should store inside the variable under certain condition like in What have you tried? section apology for my poor explanation i tried my...
13 Jun 2021 by Member 15170612
I am trying to create an application in which I will be offered three answer options (radiobuttons) one will be correct (assigned from the result) but the other two should be randomly generated and different from the correct. It occurred to me to...
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) { ...
17 Jun 2017 by Member 13264936
hi. how can i generate n random number between (a) and (b) that are around a number like (x)? What I have tried: hi. how can i generate n random number between (a) and (b) that are around a number like (x)?
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.
24 May 2022 by Manbir Singh 2022
I'm writing a code for Random Password generator where user should have an ability to select the length of password from pre-defined range (15,25) and code will generate random password using letters, numbers and symbols. If a user enters a...
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 OriginalGriff
The way I do it is simple - just use a GUID: uuid — UUID objects according to RFC 4122 — Python 3.10.4 documentation[^] Create it as a Hex string and you get something like this: 11069f3e-bc2b-469c-ab00-2297d1c7e07f Use that as a password and...
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',...
21 Oct 2019 by HitsugayaHisagi
Would like to ask, how do I generate 2 random numbers and then check if it is a prime? I would like to generate both and check them all in one click. I tried to write the code in C# but there are some invalid arguments. Here is my code.protected void btnstart_Click(object sender, EventArgs...
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 ...
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 =...
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,...
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...
8 Feb 2021 by Mohammad Shaheen
i want mathematical equation or function to get number between two number .. for example the two number is 5 and 10 .. when i send 5 will make process and returned number for example 7 this result will not be repeated .. and when i send 8 . will...
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...
8 Feb 2021 by Member 15067916
I searched and searched the internet and did not like the solutions I was seeing. Yes, I saw the Fisher-Yates Shuffle but its like greek to me. I wanted a simpler, easy to follow solution that was more how it would happen in the real world (ie....
14 May 2014 by agent_kruger
How to get random unique numbers between any 2 numbers in c# without storing and checking the previous output?Please see the below link for an example:-https://adf.ly/msz2d[^]Thanks in advance
13 May 2014 by CPallini
Short answer: you cannot.If you can, use a GUID for that.
13 May 2014 by Prasad Avunoori
static void Main(string[] args) { var r = new Random(); Console.WriteLine(r.Next(50)); Console.ReadLine(); }
13 May 2014 by phil.o
Technically, there is a Next method on the Random class which allows you to specify bounds for your random number.Here: Random.Next Method (Int32, Int32)[^]Beware!- The first parameter (minValue) is inclusive, whereas the second (maxValue) is exclusive.It means that, if you want a...
13 May 2014 by Murali0195
Hi...How+generate+random+num...
14 May 2014 by Emre Ataseven
Guid creates random values but you can't set a range for them and they won't be numeric.Not an efficient way, also causes extra memory consumption but it may be useful if your range is relatively narrow.Create a list of int that starts with your small number till your big number....
14 May 2014 by balajidileepkumar
namespace ConsoleEnum{ public class host { [STAThread] static void Main(string[] args) { List getrandom1 = Enumerable.Range(0, 100).ToList(); for (int i =0;i
14 May 2014 by johannesnestler
Hi Agen_Spock,It seems you are not getting it (concluded from your variouse comments)...If you don't store which numbers (of any set you wish your random numbers to come from e.g. 1-50) are already used, you can not know if the number is unique - Can you agree on that?So your whole...
14 May 2014 by Philippe Mori
As other as mentionned, it is essentially impossible to achieve that. Either, you have to use a know sequence that happen to be unique (in that case you still need to know where you are).It would be possible to do it wihout storing previous values if you use a seed for the random generator...
14 May 2014 by Member 10272815
Depending on your definition of random, this could work. To make it more random instead of using a fixed group size it could be randomly evalutated each pass through the loop. int[] GenerateRandom(int minimum, int maximum, int count) { int[] ret = new...
28 Nov 2021 by Grelm
Hello, I'm making a number guessing game in C# for homework. When I run it, if the guess is lower or higher than the random number, it just loops "Guess higher" or guess lower". Any help would be appreciated. using System; namespace...
28 Nov 2021 by Grelm
Figured it out! static void Problem3() { Random random = new Random(); int numNums = 2; int GuessCount = 1; int current = 0; Console.WriteLine("Enter amount of numbers to guess...
15 Jun 2021 by Member 15170612
Hi, I have a question. How do I convert an IF-statement to a WHILE loop without doing an infinite loop? Every time I tried it, I overloaded the computer and had to turn it off.And when I use the IF condition, it doesn't solve my problem at all,...
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.
28 Dec 2019 by Member 14549747
I'm working on a java project where I have a method that returns a hash function as a pair of integers a , b that exist in {1 , 2 , ... , 10000} and are picked randomly . To pick the random numbers I have an "rnd" variable . My problem is that I have learned that prime numbers are better for ...
28 Dec 2019 by OriginalGriff
You don't use random values to generate a hash - the idea of a hash is that it is a smaller, simpler, easier-to-manipulate version of the original input. And that requires that the same input always gives the same hash value, which use of random numbers does not allow. Think about it: if a hash...
12 May 2021 by Member 15170612
Hello, I would like to ask if there is any simple way to multiply the random generated number by the current millisecond? In my WPF Application I generate two random numbers in quick succession and it happens to me that in most cases they are...
12 May 2021 by OriginalGriff
Repost: Deleted. Please do not repost your question; use the Improve question widget to add information or reformat it, but posting it repeatedly just duplicates work, wastes time, and annoys people. I'll delete this one.
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...
12 May 2021 by Abeer Joshi
Yeah that helped me too, thanks everyone :)
20 May 2021 by Member 15170612
Hello, how can I set my WPF Application with random generator number for division without residue? I try to create a math game in which the user chooses the math operation he wants to calculate, then he chooses what level he wants. Addition,...
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)