-3

I just want to know does random function generate a random number to access the very first and very last element of my array “a” and how does it do that in fact. As random will generate number between 0 to 1 however if the number is 0.22 does it round it to upper limit or lower limit?

CowBoy
  • 189
  • 4
  • 18
  • 2
    First of all, your question is unclear. Second, if you want to see what a certain .Net BCL class does, just open that in Reflector or get the .Net Framework Reference Sources and step into it. – Federico Berasategui Feb 06 '14 at 17:36
  • 1
    From your update, it appears your question in based on a false premise. `random.Next(n)` will generate an *integer* from 0 to *n*-1. See [Random.Next Method (Int32)](http://msdn.microsoft.com/en-us/library/zd1bc8e5(v=vs.110).aspx) – p.s.w.g Feb 06 '14 at 17:40
  • Does it really access all the elements of my array? As by the definition it will only access from 0 to n-1 element of my array with n elements. Therefore my concern is if it will ever reach the last (nth) element of my array? – CowBoy Feb 06 '14 at 17:43
  • Array indexes are 0-based in C#, so they go from 0 to n-1 for n elements. random.Next(n) goes from 0 to n-1. You can draw the conclusion. – Pierre-Luc Pineault Feb 06 '14 at 17:44
  • @user3266873 It might return any element in your array including the last one. Of course it's random, so it's not guaranteed to hit the last element, but it is guaranteed to be within the bounds of the array. – p.s.w.g Feb 06 '14 at 17:45

1 Answers1

0

Yes - all elements of an array can be picked with equal probability including first and last:

  • Array of n elements have elements 0,1,...n-2,n-1.
  • Random.Next(n) generates int numbers from 0 to n-1.
Alexei Levenkov
  • 96,782
  • 12
  • 124
  • 169