C# How can i randomly assign numbers to an array?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: C# How can i randomly assign numbers to an array?

  1. #1
    Join Date
    Feb 2013
    Posts
    2

    C# How can i randomly assign numbers to an array?

    Hello! I am new to c# so this may be a basic question, i am also new to this forum so hello all!

    I am in progress of planning a "deal or no deal" game with c#.

    I currently have this code:

    int[] array;
    array = new int [3];

    array[0] = 1;
    array[1] = 7;
    array[2] = 9;

    Random random = new Random();
    int number = random.Next(array.Length);
    System.Console.WriteLine(array[number]);
    Console.ReadKey();


    This just randomly prints out a value 1, 7 or 9 if the array value is 0, 1 will always be printed out to the screen.

    I want it so when the game starts up the numbers would be randomly assigned so when the game starts up one game the 0 value in the array could be 1 7 or 9.

    Obviously with deal or no deal there will be 20+ value boxes there for i would need to randomly assign 20+ assigned numbers to random boxs

    Sorry if i havent been clear, if you need clarification please leave a comment

  2. #2
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,005

    Re: C# How can i randomly assign numbers to an array?

    Shuffling is surprisingly easy to screw up! See this post for the details: http://www.codinghorror.com/blog/200...f-naivete.html

    The best advice is to just use the Fisher-Yates shuffling algorithm (which is very easy to implement) after you declare the possible values in the array (i.e. after your array[2] declaration); read about it here: http://www.dotnetperls.com/fisher-yates-shuffle

    Also, you can simplify your array declaration:
    Code:
    int[] array;
    array = new int [3];
    
    array[0] = 1;
    array[1] = 7;
    array[2] = 9;
    Can be written more compactly as:

    Code:
    int[] array = new int[] { 1, 7, 9 };
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  3. #3
    Join Date
    Feb 2013
    Posts
    2

    Re: C# How can i randomly assign numbers to an array?

    Thanks! Ive just ad a look into that im still not 100% sure on how i am going to do it.

    My plan is to create a windows form with 20 buttons, when the user clicks the button the amount - 200 (for example) would be removed. And then the user clicks the next button and another amount would be removed etc..

    The problem is i don't want Box 1 to always hold 200, is that possible with the algorithm ?

    If you dont mind can you give me an example? As i mentioned i am still learning

    Thanks for your help so far!

  4. #4
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,005

    Re: C# How can i randomly assign numbers to an array?

    Sure. Suppose we've playing the game with 5 briefcases containing 1, 10, 100, 500, 1000, 2000.

    Code:
    //Declare some class level variables to keep track of the cases state
    int[] money;
    bool[] opened;
    
    //I like to have exactly one RNG at a time
    static Random rng = new Random();
    
    public void setupGame()
    {
        //
        money = new int[] { 1, 10, 100, 500, 1000, 2000 };  //Set up the money values
        opened = new bool[money.Length]; //Default init is false; no cases have been opened
    
        //Shuffle the money values
        Shuffle<int>(money);
    
        //Now the ordering of integers in money is random, that is, money[0] has equal probability of being 1, 10, 100, etc...
    }
    
    //Helper Fisher-Yates shuffle: adapted from the DotNetPearls link
    public static void Shuffle<T>(T[] array)
    {
        for (int i = array.Length; i > 1; i--)
        {
            // Pick random element to swap.
            int j = rng.Next(i); // 0 <= j <= i-1
    
            // Swap
            T tmp = array[j];
            array[j] = array[i - 1];
            array[i - 1] = tmp;
        }
    }
    
    //Open a specific case (i.e. via user input; your button clicked methods can call this)
    public void openCase(int caseIndex)
    {
        opened[caseIndex] = true;
    }
    
    //Maybe some sort of helper functions; like calculating the expected value of winnings based on remaining cases
    public double expectedValue()
    {
        double result = 0;
        int casesUnopened = 0;
        for(int i = 0; i < opened.Length; i++) 
        {
            //For all closed cases
            if( !opened[i] )
            {
                result = money[i]; //Accumulate the amount of money remaining
                casesUnopened++;
            }
        }
    
        //And the probability of each case being the final case left, if you keep going is 1/casesUnopened, so normalize
        result /= casesUnopened;
    
        return result;
    }
    Clear enough? I'll leave the forms coding to you (e.g., coding up the event handlers for when buttons are clicked, etc.)

    A minor aside: One thing that might not be clear to a novice programmer is the use of generics in the shuffle method. This is a little confusing, but generics are so important to the language that I thought you should wrestle with them now. The shuffle method is defined so that you can shuffle arrays of arbitrary type (i.e. you can use that same method to shuffle an integer array (int[]) as you could a double() array). The "T" in the angle brackets says "this method accepts arbitrary types, and I'll refer to the type as T"). When you call the method, you have to tell the method which type you mean (which is why we specify Shuffle<int> when we call it in setupGame). If, instead, players could earn fractional amounts of money (e.g. 3.14), we could change the datatype of money to double and change the call to the shuffle method to shuffle<double> without ever actually making any changes to the shuffle method itself.

    N.B.: Didn't actually compile my code, but it should be (mostly) free of syntax errors, I hope. If you get really stuck and can't debug, push back.

    Hope that helps!
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center