picturebox image randomisation C#

cheesebunz picture cheesebunz · May 17, 2010 · Viewed 11k times · Source

i am working on a puzzle slider program and trying to randomize images inside of pictureboxes. I did some research on the internet can't find any examples i could work on. These are my code:

        Random r = new Random();

        PictureBox[] picBox = new PictureBox[9];
        picBox[0] = new PictureBox();
        picBox[1] = new PictureBox();
        picBox[2] = new PictureBox();
        picBox[3] = new PictureBox();
        picBox[4] = new PictureBox();
        picBox[5] = new PictureBox();
        picBox[6] = new PictureBox();
        picBox[7] = new PictureBox();
        picBox[8] = new PictureBox();

i have bitmap array too:

        Bitmap[] pictures = new Bitmap[9];
        pictures[0] = new Bitmap(@"1.1Bright.jpg");
        pictures[1] = new Bitmap(@"1.2Bright.jpg");
        pictures[2] = new Bitmap(@"1.3Bright.jpg");
        pictures[3] = new Bitmap(@"2.1Bright.jpg");
        pictures[4] = new Bitmap(@"2.2Bright.jpg");
        pictures[5] = new Bitmap(@"2.3Bright.jpg");
        pictures[6] = new Bitmap(@"3.1Bright.jpg");
        pictures[7] = new Bitmap(@"3.2Bright.jpg");
        pictures[8] = new Bitmap(@"3.3Dark.jpg");

i tried a few ways but i don't know how to set random pictures[] into the picBox[]:

        for(int i=0; i<=8;i++)
        {
            picBox[i].Image= pictures[r.Next(0,9)];
        }

the problem here is that some pictureboxes e.g picBox[1] and picBox[6] are repeated pictures. How do i make them non repeats? Examples are greatly appreciated thanks.

Answer

Mitch Wheat picture Mitch Wheat · May 17, 2010

Simply fill the array and use a shuffle algorithm.

Perhaps implement as an extension method:

namespace ExtensionMethods
{
    public static class Extensions
    {
        static Random rng = new Random();

        public static void shuffle<T>(this T[] array)
        {
            // i is the number of items remaining to be shuffled.
            for (int i = array.Length; i > 1; i--)
            {
                // Pick a random element to swap with the i-th element.
                int j = rng.Next(i);  // 0 <= j <= i-1 (0-based array)
                // Swap array elements.
                T tmp = array[j];
                array[j] = array[i - 1];
                array[i - 1] = tmp;
            }
        }

    }
}

Calling sample:

using ExtensionMethods;

namespace ConsoleApplication
{

    static class Program
    {
        static void Main()
        {
            int[] array = new int[] {1,2,3,4,5,6,7,8,9};

            array.Shuffle();
        }
    }
}