Тёмный
No video :(

Random Numbers in C# - Best Practices, Pitfalls, and Clear Direction 

IAmTimCorey
Подписаться 419 тыс.
Просмотров 83 тыс.
50% 1

Опубликовано:

 

5 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 109   
@AnOpalGhost
@AnOpalGhost Год назад
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!
@Sharingablood
@Sharingablood 3 года назад
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. :)
@tomthelestaff-iamtimcorey7597
@tomthelestaff-iamtimcorey7597 3 года назад
Glad it helped! Thanks for watching.
@jabuci
@jabuci 4 года назад
I was thinking just yesterday how to shuffle a list. And today boom, here is the answer :) Thanks! Very informative video.
@IAmTimCorey
@IAmTimCorey 4 года назад
I am glad it was helpful.
@jamesomambia
@jamesomambia 5 лет назад
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 🙂.
@IAmTimCorey
@IAmTimCorey 5 лет назад
Yeah, picking the right way of doing random can be tricky and confusing.
@RalfsBalodis
@RalfsBalodis 4 года назад
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
@IAmTimCorey
@IAmTimCorey 4 года назад
Thanks! I added it to the description.
@nafisiancastle
@nafisiancastle 2 года назад
Thanks. I'll practice and finish the playlist in sha Allah.
@IAmTimCorey
@IAmTimCorey 2 года назад
Great!
@bokaratom
@bokaratom 2 года назад
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.
@IAmTimCorey
@IAmTimCorey 2 года назад
That's a clever idea.
@celestes8072
@celestes8072 2 года назад
Thanks for this! Really helpful with my project for class.
@IAmTimCorey
@IAmTimCorey 2 года назад
You're very welcome!
@kopilkaiser8991
@kopilkaiser8991 Год назад
Watching and learning from you all day. I just need to rest my brain a little in between with short breaks
@IAmTimCorey
@IAmTimCorey Год назад
Taking time to refresh and let things soak in is a good idea.
@MarcinKralka
@MarcinKralka 3 года назад
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.
@IAmTimCorey
@IAmTimCorey 3 года назад
Thanks for the tip
@Computer-Catt
@Computer-Catt 3 года назад
thanks a lot now i can generate a a list of suggestions
@tomthelestaff-iamtimcorey7597
@tomthelestaff-iamtimcorey7597 3 года назад
Looking forward to hearing them
@frontierflip6762
@frontierflip6762 2 года назад
Note for me only: go to 6:12 to see the code
@tomthelestaff-iamtimcorey7597
@tomthelestaff-iamtimcorey7597 2 года назад
From me only: Thanks for watching!
@unlxck3255
@unlxck3255 2 года назад
7:05 Theres actually a 5 there :D And also thanks for all the videos you make, they are very helpful
@IAmTimCorey
@IAmTimCorey 2 года назад
You are welcome.
@DathoxUdictus
@DathoxUdictus Год назад
ah yes, every developers favorite recreational activity. 16:26
@anamnasirrollno0838
@anamnasirrollno0838 3 года назад
You are amazing person!
@IAmTimCorey
@IAmTimCorey 3 года назад
Thank you
@scottsaccenti
@scottsaccenti 5 лет назад
Wish I'd seen a tutorial like this many years ago.
@IAmTimCorey
@IAmTimCorey 5 лет назад
Bummer it couldn't have been sooner.
@-pcmr-108
@-pcmr-108 4 года назад
I know this is probably attainable elsewhere, but an explanation into seeds and how the system persists their contents would have been cool.
@IAmTimCorey
@IAmTimCorey 4 года назад
Thanks for the suggestion.
@jajaja24ja85
@jajaja24ja85 4 года назад
I love your channel. Awesome Videos.
@IAmTimCorey
@IAmTimCorey 4 года назад
Thank you!
@juanpaulperez
@juanpaulperez 4 года назад
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?
@IAmTimCorey
@IAmTimCorey 4 года назад
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.
@fredpaul9352
@fredpaul9352 3 года назад
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"?
@chrisroberts1773
@chrisroberts1773 3 года назад
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.
@johnrhodelbartolome7509
@johnrhodelbartolome7509 3 года назад
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(); }
@IAmTimCorey
@IAmTimCorey 3 года назад
You would need to generate them, put them in the list, and then sort them but that would seem to negate the need for random.
@user-uz4hs8km9n
@user-uz4hs8km9n 2 года назад
How can i set each random number with all different digits?
@user-mf5gw2yd9g
@user-mf5gw2yd9g Год назад
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?
@AnonymousDeveloper1
@AnonymousDeveloper1 5 лет назад
Did you create step by step introduction course for learing C#? Best practices and so on?
@IAmTimCorey
@IAmTimCorey 5 лет назад
I created this course series for learning C# well: www.iamtimcorey.com/blog/49797/how-to-learn-csharp-well
@briankarcher4418
@briankarcher4418 5 лет назад
Hmm. Been developing in C# longer than I can remember and I never thought to use OrderBy that way.
@IAmTimCorey
@IAmTimCorey 5 лет назад
Glad you learned something new.
@andywalter7426
@andywalter7426 5 лет назад
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.
@IAmTimCorey
@IAmTimCorey 5 лет назад
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.
@drip888
@drip888 2 года назад
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()
@IAmTimCorey
@IAmTimCorey 2 года назад
Glad you figured it out.
@drip888
@drip888 2 года назад
@@IAmTimCorey u are soooo nice. You reply to all of the comments in the videos. 🤗
@eupraxiaz7818
@eupraxiaz7818 4 года назад
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?
@IAmTimCorey
@IAmTimCorey 4 года назад
You would need to write that yourself. Generate each number randomly and, if it repeats, generate it again until it doesn't.
@primekrunkergamer188
@primekrunkergamer188 3 года назад
I noticed u have public string FirstName {get; set;} Is it good practice to have get set even if u don't use it? Thanks in advance
@kevinstani5025
@kevinstani5025 3 года назад
HI. Is there a way to insert into database (sql or mysql) generated random numbers in C#
@IAmTimCorey
@IAmTimCorey 3 года назад
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.
@ww1flyingace263
@ww1flyingace263 Год назад
I hate that the upper limit is not included. It would be much simpler to use random.Next(1, 10) to get random numbers from 1 to 10 inclusive.
@IAmTimCorey
@IAmTimCorey Год назад
It can be confusing.
@antoneriksson208
@antoneriksson208 5 лет назад
In your thumbnail on the left side it says "Practical Git" instead of the usual "Practical C#" is this intended?
@IAmTimCorey
@IAmTimCorey 5 лет назад
lol, nope. I'll have to fix that. Thanks.
@fuzzykitty7549
@fuzzykitty7549 3 года назад
is there a way to reset the seed without having to close the program.
@IAmTimCorey
@IAmTimCorey 3 года назад
Re-instantiate the Random class.
@daizukeyoshida9621
@daizukeyoshida9621 2 года назад
How do you only print one of the list when there is 5 or more list
@hungerxhunger
@hungerxhunger 2 года назад
What if i want a random double from ranges 5-19?
@wiwita63
@wiwita63 Год назад
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.
@saintmaloj
@saintmaloj 5 лет назад
Is it possible to use a hand-made random-class with a static constructor to be sure to get unique values each time you need it?
@IAmTimCorey
@IAmTimCorey 5 лет назад
Yes, you just need to be careful to keep it thread-safe if you access it from different threads.
@attilaguba856
@attilaguba856 2 года назад
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 ?
@IAmTimCorey
@IAmTimCorey 2 года назад
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.
@attilaguba856
@attilaguba856 2 года назад
@@IAmTimCorey so basically I can handle out with an if statement? Like if(number == random.othernumber) { Random number = new Random() } ?
@IAmTimCorey
@IAmTimCorey 2 года назад
Handle it with a loop instead. Random means you could get the same number three times in a row.
@alword
@alword 5 лет назад
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 )
@IAmTimCorey
@IAmTimCorey 5 лет назад
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
@alword
@alword 5 лет назад
IAmTimCorey thank you! Yeah, great docs 😇 read it every time
@netforcetechnologiesllc
@netforcetechnologiesllc 2 года назад
I'm writing a yahtzee game in c#, I have the random dice roller done, but I need to know how to hold dice, I'm using visual studio 2022?
@IAmTimCorey
@IAmTimCorey 2 года назад
Sounds like you need a class for that.
@mryan5522
@mryan5522 3 года назад
hi tim. What if we want to random the number between 1 and 1000 and pick 10 number from it without any same number? is that possible?
@IAmTimCorey
@IAmTimCorey 3 года назад
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.
@majidahahmed2566
@majidahahmed2566 3 года назад
أتمنى لو توجد الترجمة العربية شكرًا لك 👍🏻
@IAmTimCorey
@IAmTimCorey 3 года назад
شكراً، أشعر أنني أقوم بعمل جيد فقط لإخراجهم باللغة الإنجليزية
@__3093
@__3093 3 года назад
lmao
@loptrfawkes2149
@loptrfawkes2149 Год назад
anyone know what he says at 12:05? i can't understand which method he's talking about.
@IAmTimCorey
@IAmTimCorey Год назад
"It is only if you pass it around in asynchronous methods that you may want to consider that"
@loptrfawkes2149
@loptrfawkes2149 Год назад
@@IAmTimCorey Hey, thanks so much. I appreciate it.
@p199a
@p199a 5 лет назад
thank
@IAmTimCorey
@IAmTimCorey 5 лет назад
You are welcome.
@giuliob6029
@giuliob6029 4 года назад
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
@giuliob6029
@giuliob6029 4 года назад
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?
@IAmTimCorey
@IAmTimCorey 4 года назад
Not with this system, no.
@Seathorne74
@Seathorne74 4 года назад
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.
@Rizon1985
@Rizon1985 4 года назад
// 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.
@AestheticMat
@AestheticMat 4 года назад
How are your values in a green color?
@IAmTimCorey
@IAmTimCorey 4 года назад
I changed the default size and color of my text in my command window to be green. I think it shows up better on the screen.
@trevorloughlin1492
@trevorloughlin1492 3 месяца назад
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.
@waqaarahsab
@waqaarahsab 2 года назад
What if I want a single random number between 1 to 10?
@IAmTimCorey
@IAmTimCorey 2 года назад
Check out the video at 6:25 - you will see how to set a range.
@waqaarahsab
@waqaarahsab 2 года назад
​@@IAmTimCorey oh, I forgot thank you
@baltazar0007
@baltazar0007 Год назад
howcould we do like the unityengine can float factor = UnityEngine.Random.Range(0f, 100f); I really have trouble making a good subsitute for it.
@westonforbes
@westonforbes Год назад
Did you not watch the video?
@widevladimir9405
@widevladimir9405 2 года назад
how can i do fart sound in random time? i need this in my game
@IAmTimCorey
@IAmTimCorey 2 года назад
You can use this random generator for the randomness. The rest is up to you.
@jlbman1887
@jlbman1887 4 года назад
This doesn't work I just get build errors
@IAmTimCorey
@IAmTimCorey 4 года назад
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.
@wim1983
@wim1983 5 лет назад
Short answer: Sodium Core
@IAmTimCorey
@IAmTimCorey 5 лет назад
I don't think that is necessary unless you are getting into encryption.
@wim1983
@wim1983 5 лет назад
@@IAmTimCorey A neat class for randomness and encryption.
@phantomboy09
@phantomboy09 3 года назад
anybody eyes also burn at 19:37
@IAmTimCorey
@IAmTimCorey 3 года назад
Why?
@phantomboy09
@phantomboy09 3 года назад
@@IAmTimCorey i had my brightness to high and when it went to white it burn my eyes
Далее
Liskov: The Liskov Substitution Principle
4:23
Просмотров 21 тыс.
How to connect C# to SQL (the easy way)
1:20:40
Просмотров 1,1 млн
Building the world's LARGEST iPhone
32:05
Просмотров 207 тыс.