0
Random choice from a list (C#)
Hi everybody, I really need a help in (C#). I want to make a random choice(2 nums) from a list. Ex: my numbers will be (-2,-1,1,2,3) I need to make a random (2nums)unique choice (I mean not same numbers) and I need to multiply them eachother and divide by 2. I will be glad If I can have a solution for this. Thanx in advance for your help :)
9 Respostas
+ 2
Hey.
Have a look here
https://code.sololearn.com/cgXlLePmTAHM/?ref=app
Hope that works out for you. Cheers. C
+ 2
Hi.
You could use random.next(min, max) and since you have to store the first value anyway, you could put the search for the second in a while-loop that runs until the second value is unequal to the first one.
Random rand = new Random();
int value_1 = rand.Next(-2, 3);
int value_2 = value_1;
while(value_2 == value_1){
value_2 = rand.Next(-2, 3);
}
Something similar should do the trick. Haven't been coding C# in a while, so please excuse stupid errors.
Hope that helps. Cheers. C
+ 2
ChrA you r right indexes should be 0,1,2,3,4 because of that u should write rand.Next(0,5) cuz random is not choosing last num and u should fix it now (0,Length) rather than (0,Length-1 :)) but its not a big deal I only try to remind u that Thanx for your answer I already made a function with it and add to my code.....you already save me Thank You âșïžâșïž
+ 2
Thanks for your input. I'll change the code
+ 1
Great! Does it work? Even on several repetition?
You gave five valid results that you wanted from the random generator. If you access an array with five elements at position (index) five there is an undefined output. The useable indexes should be 0, 1, 2, 3, 4.
0
ChrA Thanx for your help,
But I domt want to choose 0 from list.Im not sure its going to work for me well,I think I still need some help :)
0
You are right. Overlooked this requirement.
How about creating an array that contains all your allowed values and generating the index randomly where to access the array of your values.
0
ChrA Yes you are right,thats what Im trying to do but that time Im having some trouble Ä°m not that much good at it ....
0
ChrA Thank you its working perfect ,but I already change a part of it to rand.Next(0,5) :)))