当前位置:编程学习 > C#/ASP.NET >>

求教:哈希算法

C#源代码:

构建一个N全部为数字0的序列。然后使用哈希算法,将M(M<N)个非0数字随机并均匀地填充到这个总长为N的数字序列之中,替换掉原有位置上的0。

--------------------编程问答-------------------- 这个问题比较专业
友情帮顶,期待高手 --------------------编程问答--------------------

static void GetRandomList(int M, int N)
        {
            if (M > N || N <= 0) throw new ArgumentOutOfRangeException("M和N都必须大于零,且N不小于M");
            List<int> listN = Enumerable.Repeat<int>(0, N).ToList();
            List<int> listM = new List<int>(M);
            for (int i = 0; i < M; i++)
                listM.Add(i);
            //随机排序后,替换零
            listM.Sort((i,j) => i.GetHashCode() + j.GetHashCode());            
            for(int i=0; i<N; i++)
            {
                listN[i] = listM[i % M];
                Console.Write(listN[i] + " ");
            }
        }
/*
6 0 7 5 8 1 4 2 9 3 6 0 7 5 8 1 4 2 9 3 请按任意键继续. . .
*/

--------------------编程问答-------------------- 上面当N比较大时,由于是循环填充M序列,可以明显是有规律的,可以改成这样

static void GetRandomList(int M, int N)
        {
            if (M > N || N <= 0) throw new ArgumentOutOfRangeException("M和N都必须大于零,且N不小于M");
            List<int> listN = Enumerable.Repeat<int>(0, N).ToList();
            List<int> listM = new List<int>(M);
            for (int i = 0; i < M; i++)
                listM.Add(i);
            //随机排序后,替换零
              listM.Sort((i,j) => i.GetHashCode() + j.GetHashCode());            
            for(int i=0; i<N; i++)
            {
                listN[i] = listM[Math.Abs(Guid.NewGuid().GetHashCode()) % M];
                Console.Write(listN[i] + " ");
            }
        }

/* GetRandomList(10, 50);
0 7 0 5 8 0 4 9 0 8 8 4 1 1 0 6 0 4 3 5 7 3 4 0 2 9 6 2 2 1 2 3 4 7 4 3 1 5 1 1
9 2 4 7 6 6 1 5 0 8 请按任意键继续. . .
*/
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,