首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

求一3*3数组,下上左右全部是不同的随机数字(1到7)

2012-11-26 
求一3*3数组,上下左右全部是不同的随机数字(1到7)任一个数,周围的数字也都不能相同。任一个数,与周围的数字

求一3*3数组,上下左右全部是不同的随机数字(1到7)

任一个数,周围的数字也都不能相同。
任一个数,与周围的数字不能相同。

思路很简单,就是上下左右,没有超出数组边界的,全部都要比一下,周围的数字,也都要比较一下,如果有雷同的,立马重新生成新的随机数,递归比较,直到不同为止。


注:int 数组在初始化时,默认值均为0。

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            int D = 3;     //维度,可自定义            int[,] ary = new int[D, D];            for (int i = 0; i < D; i++)            {                for (int j = 0; j < D; j++)                {                    ary[i, j] = GetTrueNum(ary, i, j, D);                    Console.Write("{0}\t", ary[i, j]);                }                Console.WriteLine();            }            Console.Read();        }//end of main        private static int GetTrueNum(int[,] ary, int i, int j, int D)        {            int temp = new Random().Next(1, 8);            HashSet<int> hs = new HashSet<int>();            hs.Add(i - 1 >= 0 ? ary[i - 1, j] : -1);            hs.Add(i + 1 < D ? (ary[i + 1, j] == 0 ? -2 : ary[i + 1, j]) : -2);            hs.Add(j - 1 >= 0 ? ary[i, j - 1] : -3);            hs.Add(j + 1 < D ? (ary[i, j + 1] == 0 ? -4 : ary[i, j + 1]) : -4);            int hsCount = hs.Count;            if (                ((i - 1 >= 0) && (temp == ary[i - 1, j])) ||            //与上比较                ((i + 1 < D) && (temp == ary[i + 1, j])) ||             //向下比较                ((j - 1 >= 0) && (temp == ary[i, j - 1])) ||            //向左比较                ((j + 1 < D) && (temp == ary[i, j + 1])) ||             //向右比较                hsCount != 4        //上下左右的数值有相同的                )            {                return GetTrueNum(ary, i, j, D);            }            return temp;        }    }//end of class}//end of namespace

热点排行