/// <summary> /// Rearranges all the elements in the list previously scrambled with <see cref="Scramble{TSource}(IList{TSource},int)"/> back into their original order. /// </summary> /// <param name="source">The input list of generic types to unscramble.</param> /// <param name="seed">The same number used in <see cref="Scramble{TSource}(IList{TSource},int)"/> call to scramble original list.</param> /// <typeparam name="TSource">The generic type of the list.</typeparam> /// <remarks>This function uses the <see cref="System.Random"/> generator to perform the unscramble using a sequence that is repeatable.</remarks> public static void Unscramble <TSource>(this IList <TSource> source, int seed) { if (source.IsReadOnly) { throw new ArgumentException("Cannot modify items in a read only list"); } System.Random random = new System.Random(seed); List <int> sequence = new List <int>(); int x, y, count = source.Count; TSource currentItem; // Generate original scramble sequence. for (x = 0; x < count; x++) { // Calls random function from System namespace. sequence.Add(random.Next(count)); } // Unmix the data order (traverse same sequence in reverse order). for (x = count - 1; x >= 0; x--) { y = sequence[x]; if (x != y) { // Swaps items currentItem = source[x]; source[x] = source[y]; source[y] = currentItem; } } }
/// <summary> /// Rearranges all the elements in the list into a repeatable pseudo-random order. /// </summary> /// <param name="source">The input list of generic types to scramble.</param> /// <param name="seed">A number used to calculate a starting value for the pseudo-random number sequence.</param> /// <typeparam name="TSource">The generic type of the list.</typeparam> /// <remarks>This function uses the <see cref="System.Random"/> generator to perform the scramble using a sequence that is repeatable.</remarks> public static void Scramble <TSource>(this IList <TSource> source, int seed) { if (source.IsReadOnly) { throw new ArgumentException("Cannot modify items in a read only list"); } System.Random random = new System.Random(seed); int x, y, count = source.Count; TSource currentItem; // Mixes up the data in random order. for (x = 0; x < count; x++) { // Calls random function from System namespace. y = random.Next(count); if (x != y) { // Swaps items currentItem = source[x]; source[x] = source[y]; source[y] = currentItem; } } }