3.随机排序一维数组 int[]

            #region 3、随机排序一维数组 int[]

            #region 方法1

            int[] oldnum = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int[] newnum = new int[oldnum.Length];
            Random ran = new Random();
            List<int> intlist = new List<int>();

            for (int i = 0; i < oldnum.Length; i++)
            {
                int random = ran.Next(oldnum.Length - 1);
                while (intlist.Contains(random))
                {
                    random = ran.Next(oldnum.Length);
                }
                intlist.Add(random);
            }


            for (int j = 0; j < intlist.Count; j++)
            {
                int a = intlist[j];
                newnum[j] = oldnum[a];
            }

            for (int k = 0; k < newnum.Length; k++)
            {
                Console.WriteLine(newnum[k].ToString() + ";");
            }
            #endregion

            #region 方法2 以前写的,小纪念下

            //3、随机排序一维数组  int[] 。

            int[] intArr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            int[] intArr2 = new int[10];

            Console.WriteLine("排序前");
            for (int i = 0; i < intArr.Length; i++)
            {
                Console.Write(intArr[i] + ";");
            }
            List<int> newlist = new List<int>();
            for (int i = 0; i < intArr.Length; i++)
            {
                Random rans = new Random();
                int random = rans.Next(0, 10);
                if (newlist.Count == 10)
                {
                    break;
                }
                if (!newlist.Contains(random))
                {
                    newlist.Add(random);
                }
                else
                {
                    i--;

                }

            }
            Console.WriteLine();
            Console.WriteLine("排序后");
            for (int j = 0; j < intArr.Length; j++)
            {
                intArr2[j] = intArr[newlist[j]];

                //Console.Write(intArr[newlist[j]] + ";");
            }

            intArr = intArr2;
            for (int k = 0; k < intArr.Length; k++)
            {
                Console.Write(intArr[k] + "");
            }
            #endregion

            #endregion

 

 

 

posted @ 2013-09-04 17:38  LifeForCodes  阅读(260)  评论(0编辑  收藏  举报