Pages

Gin Rummy Indian Rummy Nine Men's Morris and more Air Attack

Sunday 25 February 2018

A simple shuffle implementation

There are two phases in the algorithm, first we shuffle from the beginning of the array and after that from the end of the array.

First we are going to start from the beginning of the array iterating over all the element. In each iteration we are going to get a random index from current index to the index to the last element.
After getting the random index we are going to swap current element with the element at the random selected index.

In the second phase we are going to do the same thing, but this time we start from the end of the array.

The shuffle implementation is given below,

using System;
using System.Collections.Generic;

class MainClass {
       
    public static void shuffle(List<int> values) {
        Random random = new Random();


        // shuffle by swapping elements from beginning of the list
        for (int i = 0; i < values.Count - 2; ++i) {

            // get a random position from i to end of the list
            int index = random.Next (i, values.Count);

            // swap i th element with the element at position retrieved above, index
            int temp = values [i];
            values [i] = values [index];
            values [index] = temp;
        }

        // shuffle by swapping elements from end of the list
        for (int i = values.Count - 1; i > 2; --i) {
            // get a random position from 0 to i-1 from the list
            int index = random.Next (0, i-1);

            // swap i th element with the element at position retrieved above, index
            int temp = values [i];
            values [i] = values [index];
            values [index] = temp;
        }
    }
   
    public static void Main (string[] args) {
        List<int> values = new List<int>();
        for (int i=0; i<50; ++i) {
            values.Add(i);
        }

        shuffle(values);
        for (int i=0; i<values.Count; ++i) {
            Console.Write(values[i] + ", ");
        }

    }
}