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

数目字1到7随机显示,且邻近随机数字不能相同

2013-12-28 
数字1到7随机显示,且邻近随机数字不能相同上面图片仅作参考,格子的多少自己定义的.需求:例如6的邻近数字为

数字1到7随机显示,且邻近随机数字不能相同
数目字1到7随机显示,且邻近随机数字不能相同
上面图片仅作参考,格子的多少自己定义的.
需求:
例如
6的邻近数字为1 和4, (数字"1"和"4"不能为同一个数)
3的邻近数字为1,2,4,5 (数字"1","2","4","5"不能为同一个数) 
也就是说中心的数字(例如"3"),它的"上下左右"四个数字(包括"3")不能为同一个数字,
且这四个数字不能等于它中心那个数字(也就是"3")

求理念,最好能有代码,谢谢.
[解决办法]
思路很简单,就是上下左右,没有超出数组边界的,全部都要比一下,如果有雷同的,立马重新生成新的随机数,递归比较,直到不同为止。

注: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);
            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]))             //向右比较
                )
            {
                return GetTrueNum(ary, i, j, D);
            }
            return temp;
        }
    }//end of class
}//end of namespace

热点排行