By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,990 Members | 2,279 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,990 IT Pros & Developers. It's quick & easy.

Inner workings or orderby Rnd.next

P: 4
I am trying to understand the internal logic of how Orderby actually re-orders when using Orderby with random.Next.

For Example in the following how is the random number actually used to do the reordering?

Expand|Select|Wrap|Line Numbers
  1.  
  2. Dim deck = Enumerable.Range(1, 52)
  3.  
  4. deck = deck.OrderBy(Function(n) rng.Next)
  5.  
  6.  
I would appreciate an easy not too technical explanation.
Jul 26 '12 #1
Share this Question
Share on Google+
3 Replies


Frinavale
Expert Mod 5K+
P: 9,731
I have no idea what you are doing with the random number.
The Enummerable.OrderBy() method is used to sort the elements in the enumeration. Using a random number is kind of defeating the purpose because it would be randomizing instead of sorting. See the link for more details.



-Frinny
Jul 27 '12 #2

P: 4
this was part of the code in a Dan Mabbutt article concerning random numbers. the entire code block was
Expand|Select|Wrap|Line Numbers
  1. Dim rng As New Random
  2. 'Create the deck.
  3. Dim deck = Enumerable.Range(1, 52)
  4. 'Shuffle the deck.
  5. deck = deck.OrderBy(Function(n) rng.Next)
  6. 'Deal four hands of five cards.
  7. Dim hands(3) As List(Of Integer)
  8. For i = 0 To 3
  9.     hands(i) = deck.Skip(i * 5).Take(5).ToList()
  10. Next
  11.  
I understand the effect of the code; however, when stepping through it, the OrderBy Rng.Next cycles through each of the members of deck. I am wondering about the mechanics of exactly how it is randomizing the members of deck. When it examines the first member is it selecting a subsequent member at random and replacing the member it is addressing? Is it then simply placing the replaced member at the position from which it took the replacement?

I am interested in the details of the process that is being performed.

Dan's article is at http://visualbasic.about.com/od/usin...ndintarray.htm
Jul 27 '12 #3

Frinavale
Expert Mod 5K+
P: 9,731
Well, if your list was originally sorted (in order) and you sort it again based on a random number, then your sorted list will not be sorted any more.

-Frinny
Jul 27 '12 #4

Post your reply

Sign in to post your reply or Sign up for a free account.