随机二维非重复数组c#

时间:2014-11-03 01:37:16

标签: c# arrays random

我用随机数在c#中制作了一个二维数组,但我希望这些数字不会重复 例如,给出输入4(x),4(y),15(maxElem)的成功输出将是:

14 | 8 | 1 | 7

3 | 13 | 2 | 4

2 | 6 | 12 | 8

10 | 9 | 4 |

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TwoDimensionArray
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 4;
            int y = 4;
            int[,] z = new int[x, y];

            Random r = new Random();
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    z[i, j] = r.Next(1, 15);
                }
            }
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    if (i == 3 && j == 3)
                    {
                        Console.Write("  ");
                        break;
                    }
                    else
                    {
                         if (z[i, j] > 9)
                            Console.Write(z[i, j] + " ");
                         else
                            Console.Write(z[i, j] + "  ");
                    }
                }
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

生成一个包含有效数字的数组,然后use a shuffle algorithm随机化数组中的顺序,最后通过检索来自混洗数组的值来填充二维数组。

答案 1 :(得分:0)

尝试这样做:

int x = 4;
int y = 4;
int[,] z = new int[x, y];

Random r = new Random();

var values =
    Enumerable
        .Range(1, x * y)
        .OrderBy(n => r.Next())
        .ToArray();

for (int i = 0; i < x; i++)
{
    for (int j = 0; j < y; j++)
    {
        z[i, j] = values[i * 4 + j];
    }
}