C# .NET - Randomize An Array - Asked By Craig Vedur on 12-Dec-05 01:12 PM

Hey,

I have an array and I want to randomize it's contents.  I have this algorithm but it seems as though sometimes the array doesn't get shuffled.  Any help?

public static ListDTO[] Shuffle(ListDTO[] listDTO)
{
	int newIndex;
	ListDTO tempListDTO;

	try
	{
		for (int i = 0; i < listDTO.Length; i++)
		{
			newIndex = new Random().Next(listDTO.Length);
			tempListDTO = listDTO[i];
			listDTO[i] = listDTO[newIndex];
			listDTO[newIndex] = tempListDTO;
		}
	}
	catch (Exception ex)
	{
LoggerUtility.GetInstance().ApplicationLogger.Error("Error while shuffling ListDTO objects", ex);
	}

	return listDTO;
}

You could introduce - Asked By Aarthi Saravanakumar on 12-Dec-05 01:57 PM

a level of Randomness..again by checking that if a number's destination index is the same as its source index..go in a loop and generate the next Random# that is not the same Index as the Source..

public static ListDTO[] Shuffle(ListDTO[] listDTO) 
{ 
int newIndex; 
ListDTO tempListDTO; 

try 
{ 
for (int i = 0; i < listDTO.Length; i++) 
{ 
newIndex = new Random().Next(listDTO.Length); 
while(i!=newIndex)
{
newIndex = new Random().Next(listDTO.Length); 
}


tempListDTO = listDTO[i]; 
listDTO[i] = listDTO[newIndex]; 
listDTO[newIndex] = tempListDTO; 
} 
} 
catch (Exception ex) 
{ 
LoggerUtility.GetInstance().ApplicationLogger.Error("Error while shuffling ListDTO objects", ex); 
} 

return listDTO; 
}

I added a seed - Asked By Craig Vedur on 12-Dec-05 02:01 PM

I changed:
newIndex = new Random().Next(listDTO.Length);  to:
newIndex = new Random(i).Next(listDTO.Length);