Generate an array with pairs of numbers

I have this code:

Random num = new Random();
            int check = CheckIfOdd(num.Next(1, 1000000));
            int counter = 1;

            while (check <= 0)
            {
                if (check % 2 == 0)
                {
                    check = CheckIfOdd(num.Next(1, 1000000)); ;
                }
                counter++;
            }
            int[] nArray = new int[check];
            int arLength = 0;
            //generate arrays with pairs of numbers, and one number which does not pair.
            for (int i = 0; i < check; i++)
            {
                arLength = nArray.Length;

                if (arLength == i + 1) 
                {
                    nArray[i] = i + 1;
                }
                else
                {
                    nArray[i] = i;
                    nArray[i + 1] = i;
                }
                i++;
            }

which really works, but not as we would like.

It should generate an array with 1-1 million elements, and the number inside can be from 1 to 1 billion.

it must make two pairs of each number, at random locations in the array (which it is not now), and then it must contain 1 number that does not have a pair ...

I'm just looking for a better way to do this, since it is not in random places, and it is not generating numbers correctly between 1 - 1 billion.

Edit I was asked the following: (by oerkelens)

var total = new Random().Next(500000) * 2 + 1;
            var nArray = new int[total];
            for (var i = 1; i < total; i += 2)
            {
                nArray[i] = i;
                nArray[i - 1] = i;
            }
            nArray[total - 1] = total;

This is better, not so much code, but it doesn't put values ​​in random order.

2 , , . , , 1-y

Random r = new Random();
int[] output = Enumerable.Range(0, 11).Select(x => x / 2).OrderBy(x => r.Next()).ToArray();

Enigmativity

0
1

:

int[] output = Enumerable.Range(0, 11).Select(x => x / 2).ToArray();

:

{ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5 }

.

, :

Random r = new Random();
int[] output = Enumerable.Range(0, 11).Select(x => x / 2).OrderBy(x => r.Next()).ToArray();

, , :

{ 0, 4, 1, 2, 2, 4, 5, 3, 3, 1, 0 }

, :

Random r = new Random();
int pairs = 5; //elements = 2 * pairs + 1;
int max = 100;
int[] output =
    Enumerable
        .Range(0, pairs)
        .Select(x => r.Next(1, max + 1))
        .SelectMany(x => new [] { x, x })
        .StartWith(r.Next(1, max + 1))
        .OrderBy(x => r.Next())
        .ToArray();

, 3, 4 , .


"System.Interactive":

int[] output =
    new [] { r.Next(1, max + 1) }
        .Concat(
            Enumerable
                .Range(0, pairs)
                .Select(x => r.Next(1, max + 1))
                .SelectMany(x => new [] { x, x }))
        .OrderBy(x => r.Next())
        .ToArray();
+3

All Articles