解决方案 »

  1.   

    LinQ实现的,方法仅供参考,还有其他N多方法实现【代码】:
      

  2.   

    给一个非LINQ的using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<int> source = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                List<int> rndNumber = new List<int>();
                Random rnd = new Random();
                for (int i = 0; i < 9; i++)
                {
                    int r = source[rnd.Next(0, source.Count - 1)];
                    source.Remove(r);
                    rndNumber.Add(r);
                }
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        Console.Write(rndNumber[i * 3 + j] + "\t");
                    }
                    Console.WriteLine();
                }
            }
        }
    }
      

  3.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;namespace 九宫格
    {
        class Program
        {
            static void Main(string[] args)
            {
                Random rd = new Random();
                int[] diffnums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                int[,] iArrary = new int[3, 3];
                int num = 0;
                int z = diffnums.Length;
                for (int x = 0; x < 3; x++)
                {
                    for (int y = 0; y < 3; y++)
                    {
                        int a = rd.Next(0, z);
                        iArrary[x, y] = diffnums[a];
                        diffnums[a] = diffnums[z - 1];
                        z--;
                    }
                }
                for (int x = 0; x < 3; x++)
                {
                    for (int y = 0; y < 3; y++)
                    {
                        Console.Write(iArrary[x, y]+" ");
                    }
                    Console.WriteLine();
                }
                    Console.ReadLine();
            }
        }
    }再给一个
      

  4.   

    产生1-9不重复的随机数,有两个办法
    1.把1-9放到可变长度的结构里,比如List,然后随机产生一个索引,获取到这个数之后,就将它从List里移除,以此来保证不重复
    2.把1-9的数放到定长数组里,每次产生一个数字之后,要先判断是否重复,如果重复,+1,取下一个,如果还重复,继续+1,如果加到9,就变成1,然后继续+1,直到找到一个不重复的数字