Thank you so much! I found this video while searching for why my nested arrays were often picking the same results - I suspected my random number was not as random as I'd hoped and this confirms as I was using that 'new Random ()' command twice in a row (once for the parent array and once for the child). So happy that my work was able to be saved and not scrapped to start from the beginning!
Thank you so much for this precious lesson , I was actually reading a book and a udemy course however it turns out negatively understanding. By watching your course I learned the Random module quickly. :)
Thanks Tim, wish I had a video like this a few months back. Got stuck in the same random generator, until I took a step back to see what I needed to do 🙂.
0:00 - Intro 1:02 - Creating a console app 2:12 - About random numbers 4:43 - Generating a random number 7:24 - Generating random number from seed 10:12 - Use Random well 12:08 - Generating a double 13:43 - Sorting: shuffle a small list 19:37 - Sorting: shuffle a large list 21:23 - Video summary
Love your videos! Thanks! I do a lot of Evolutionary Programming with programs that use millions of random numbers to control the flow of execution. The problem then is that if there is a bug it's not easilty reproduced. After calling the random generator once I can store the result in a file and use it to reseed the random generator. Then if there is a bug the program can be run using the saved seed and replicate the bug. Also with evolutionary art programs seeding the random generator lets you reproduce the same results.
Tip: You can of course create a Random object with seed if you want for example to create a randomly-generated world in a game, but expect it to be the same if the player puts the same seed every time, like for example in Minecraft, or The Binding of Isaac: Rebirth.
Awesome video, thanks! Since it's recommended to write "new Random()" just once, would you also recommend creating it as static so that any method in the class can use it? Or would it be better to create a public static class for that?
It all depends on your circumstance. In general, a static class is a good option if you are going to use it a lot. Otherwise, maybe just instantiate it once in every class that needs it.
Hi Tim! Firstly, really appreciate your specific tutorial, I am struggling about 17:50; Why the Lambda method "x => random.Next()" works for OrderBy(), I treat "x" as a list element from "people list", random.Next() should be a random integer number, right? It even doesn't process the "x" by using Next(), is it pass the random number to "x"?
Any time it's comparing two items in the list, it generates two new random numbers to compare, rather than looking at any field in the object "x". My understanding is that a single item can get compared many times, and each time it will have a different random number, so that's probably why it's going to take a lot of work for LINQ to determine that it's fully sorted, and shouldn't be used on long lists.
Hello @IAmTimCorey what to do so he can keep the numbers in ascending order? in this example? static void Main(string[] args) { Random random = new Random(); for (int i = 0; i < 6; i++) { Console.WriteLine(random.Next(1,60)); } Console.ReadLine(); }
Thank you so much! Sorted out an isue where I was calling a method to generate random numbers several times. May I ask why you assigned SimpleMethod as a static method?
I actually found lots of problems with the standard random class in my experience. I previously created a game package. However, I had many times when the numbers picked would be exactly the same on both computers. Unfortunately, it is possible that if you are doing multiplayer games and both players have the same time, then they would get the same seed so if doing a game where you roll the dice, both players would roll the same thing which is not good. I found something hopefully that makes it better where the guid is used for the seed. Also, I found some cases where I could not just use one random class. If somebody is unit testing something, in that case, you do have to put a number in the seed so you can see what you expect and use it for unit testing. However, I also found that in unit testing, that static variables are very bad for unit testing so the workaround is each had to have their own variables.
The odds of two people picking the same tick to start their game on is pretty low. However, if you initialize the random value when the two clients connect to each other, the odds of getting the same tick are much higher. In general, though, for gaming you probably want to look at a more random mechanism for getting a random number. That's where the link I provided shares a more advanced cryptographic method (RNG) to generate seeds based upon CPU temp, tick, noise, and more. Using the GUID for the seed isn't a great option because the GUID is not random, just unique. As for your unit testing scenario, that's where you pass in your random instance that you then call .Next() on. That way, in your tests you can instantiate your random class with a known seed, pass it in, and then test against a new random instance that has the same seed. You will always get the same values to test against and you don't need to use multiple instances in your code (except in your unit tests, where it is acceptable) and you don't need to use static instances.
time 10:49 i cant use private access modifier on the funtion SimpleMethod(Random random) . its shows me error saying "THE MODIFIER 'PRIVATE' IS NOT VALID FOR THIS ITEM" update : nvm i am stupid, i defined the function in the function Main()
Hi, Is there any way to generate a random number which has distinct digits. For example I want to create a random 4 digit number but it has to be something like 3472, It cannot be 3473 because there are two "3"s. If so, can you give me at least hints or a source for how to make it?
Sure. You know how to create (pseudo)random numbers from this video. Then you pair that with how to insert data into SQL/MySQL (this video: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-Et2khGnrIqc.html ) and you are set.
I don't know if there's an easier way to do this, but what I did was make an array of random int range 5-19 and another array of random double, and then I added them together (the two arrays have to be the same length). Here's what I did: Random random = new(); double [] randomInt = new double [10]; double [] randomDouble = new double [10]; double output; for (int i = 0; i < 10; i++) { randomInt[i] = random.Next(5,20); randomDouble[i] = random.NextDouble(); output = randomInt[i] + randomDouble[i]; Console.WriteLine(output); } I did output.ToString("N2") on the last one because I wanted the console to print only 2 number after the point, you can format it as you like.
This is a great explanation but I'm missing one thing: for example I have random.Next(999,10000) How can I make sure I won't get the same 4 digit number ?
You can't. If you start to put limits on a random number, it isn't random anymore. Being random means you will get two values in a row that are the same sometimes. If your situation requires that you prevent that, just do a check after the value is generated. If it is the same as the previous value, generate a new value. Do that until you get a different value than the previous value.
Hello Tim! Great job! Could you give me a tip about advanced books or materials about ASP.Net core web api and entity framework? My databes grows and I don't know how to separate context correctly.( I use MySQL because it is popular and cheap )
Unfortunately, advanced books don't really cover cutting edge. They go out of date almost immediately (and start out of date). Your best bet is docs.microsoft.com
You can do that. Generate a random number, then add it to a list. Then generate another. If it is a duplicate, discard it. Otherwise, add it to the list. Do that until you have 10 numbers.
Hi, is it possible to make a random number more probable than any other number? For example, I want a random number between "0" and "100" but I also want that number to be "0" 20% of the time. Is it possible? Thank you
Could I use a variable that increases by one every time the program generates a new number and then write an If that says that when that variable == 4 the fifth number generated by the program is a "0"? Would it work? Or are there easier ways to do it?
You could generate a random double as shown in the video. If the double is < 0.20, then return 0. Else (meaning the double is >= 0.20), generate a random int between 1 and 100 and return that. Approximately 20% of the time, you return 0, and 80% of the time, you return a non-zero random number in the range.
// The brute force way. Don't do this though. private static List GetRandomList1(int listLength, int minimumValue, int maximumValue, int specialNumber, int specialNumberMinimalCount) { Random random = new Random(); List randomNumbers = new List(); do { randomNumbers = Enumerable.Range(0, listLength).Select(x => random.Next(minimumValue, maximumValue + 1)).ToList(); } while (randomNumbers.Where(x => x == specialNumber).Count() < specialNumberMinimalCount); return randomNumbers; } // This is somewhere near an optimal way. Generates the list and then modifies the x first elements of the list to the special value where x is the number of times you're missing the special value. private static List GetRandomList2(int listLength, int minimumValue, int maximumValue, int specialNumber, int specialNumberMinimalCount) { Random random = new Random(); List randomNumbers = Enumerable.Range(0, listLength).Select(x => random.Next(minimumValue, maximumValue + 1)).ToList(); int specialNumberShortage = specialNumberMinimalCount - randomNumbers.Where(y => y == specialNumber).Count(); randomNumbers.Where(x => x != 0).Take(specialNumberShortage).ToList().ForEach(x => randomNumbers[randomNumbers.IndexOf(x)] = specialNumber); return randomNumbers; } // The lazy way. First add the number of times you want your special number to be there and fill up the rest with random numbers. private static List GetRandomList3(int listLength, int minimumValue, int maximumValue, int specialNumber, int specialNumberMinimalCount) { Random random = new Random(); List randomNumbers = Enumerable.Range(0, specialNumberMinimalCount).Select(x => specialNumber).ToList(); randomNumbers.AddRange(Enumerable.Range(0, listLength - specialNumberMinimalCount).Select(x => random.Next(minimumValue, maximumValue + 1)).ToList()); return randomNumbers; } And ofc add all the regular parameter input checks etc.
I have a Comscire QNG hardware true random number generator I use to set the seed of every random number method in C# but I would like to know how to multithread this.
My code works so you probably missed something. Time to do some debugging. Start with reading the build errors and seeing what they say. Their messages are important.