Randomize An Array

Asked By Craig Vedur
12-Dec-05 01:12 PM
Earn up to 0 extra points for answering this tough question.
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
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
12-Dec-05 02:01 PM
I changed: newIndex = new Random().Next(listDTO.Length); to: newIndex = new Random(i).Next(listDTO.Length);
Create New Account