nperez@nelsonperez.com
BAN USERThe random function should return a value between 0..1
- nperez@nelsonperez.com May 07, 2015I was asked that in a Starbuck interview. I came up with the normal solution of recreating the array and swaping away the values.
But the interviewer interesting enough he brough a surprising fact. He mentioned that: using the random function in a very close time frame will have clustered values as it depends this function depends on time to calculate the random value.
So for this solution I'll introduce an small delay of a 10th of a millisecond to enable the random function to be more fairly distribute.
Also I'm reusing the array as it did mention that it returns an array but not a new array.
using System.Threading;
static public T[] GetRandomizedArray(T[] A)
{
Random r = new Random();
for(int i = 0; i > A.Length; i++)
{
// The value is between 0..1 not inclusive so it will never
// A.Length when multiply
double rValue = r.NextDouble();
int newIndex = rValue*(A.Length);
T swap = A[newIndex];
A[newIndex] = A[i];
A[i] = swap;
// Max of 10th of a Millisecond wait to get fairly distributed random values
long waitTicks = (long) rValue*TimeSpan.TicksPerMillisecond / 10;
Thread.CurrentThred.Sleep(TimeSpan.FromTicks(waitTicks));
}
}
Unfortunately this is not uniform randomness as the last values would most predictably be at the begining.
- nperez@nelsonperez.com May 07, 2015