2

In a two-dimensional array of integers (e.g. int[3,3]), consisting of all 0 values, I'd like to set n random elements of the array to the value 1 as efficiently as possible. The problem that I am running into is that the first elements in the array are more likely to have a value of 1 than other elements later in the array.

Here is my code. In the example below I am attempting to set exactly 3 randomly-selected elements of the 3x3 array to 1.

int sum = 0;

private void MakeMatrix()
{
    for (int i = 0; i < 3; i++)
    {
        for (int k = 0; k < 3; k++)
        {
            int n = _r.Next(2);

            if (n != 1 && sum < 3)
            {
                matrix[i, k] = 1;
                sum++;
            }
            else
            {
                matrix[i, k] = 0;
            }
        }
    }
}
3
  • if u want them to be 1 then why not set directly? Commented Jan 26, 2013 at 15:56
  • out of 9 element, any 6 of them can be zero? Commented Jan 26, 2013 at 15:57
  • Based on the value I do other things. This method is called by event. I need every time when the event is fired to get different set of values where 6 are zeros and 3 are not, or whatever - I need to be able to select exactly 3 element by some unique identifier. Commented Jan 26, 2013 at 16:01

2 Answers 2

4

You might try something like the following. First initialize your matrix to all 0 values, then run the code below. It will set three random values in the matrix to 1.

int count = 0;
while (count < 3)
{
    int x = r.Next(0, 3);
    int y = r.Next(0, 3);

    if (matrix[x, y] != 1)
    {
        matrix[x, y] = 1;
        count++;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0
    static int sum = 0;
    private static readonly int[,] matrix = new int[3,3];
    private static readonly Random _r = new Random();
    private static void MakeMatrix()
    {
        //by default all the element in the matrix will be zero, so setting to zero is not a issue
        // now we need to fill 3 random places with numbers between 1-3 i guess ?

        //an array of int[3] to remember which places are already used for random num
        int[] used = new int[3];
        int pos;
        for (int i = 0; i < 3; i++)
        {
            pos = _r.Next(0, 8);
            var x = Array.IndexOf(used, pos);
            while (x != -1)
            {
                pos = _r.Next(0, 8);
            }
            used[i] = pos;
            matrix[pos/3, pos%3] = _r.Next(1, 3);

        }

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.