注册 登录
编程论坛 C# 论坛

从几个整数数组中随机取出若干整数组成新数组遍历输出

h1436094174 发布于 2017-09-06 21:50, 1934 次点击
我想编个控制台程序:有4个整数数组,从第一个数组中取出2个整数,从第二个数组中取出1个整数,从第三个数组中取出3个整数,从第四个数组中取出4个整数,然后将这些选出的整数放入一个新数组中并遍历输出,依此类推,将所有的组合情况都遍历输出。本人新手,求赐教。
1 回复
#2
wtujoxk2017-09-10 19:16
程序代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace IntRande
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array1 = new[] { 1, 2, 3, 4, 5 };
            int[] array2 = new[] { 6, 7, 8, 9, 10 };
            int[] array3 = new[] { 11, 12, 13, 14, 15 };
            int[] array4 = new[] { 16, 17, 18, 19, 20 };

            List<int> newList = new List<int>();

            foreach (var temp in RandomNoRepeat(2, array1.Length, array1))
            {
                newList.Add(array1[temp]);
                Console.WriteLine("第一种组合:" + array1[temp]);
            }
            foreach (var temp in RandomNoRepeat(1, array2.Length, array2))
            {
                newList.Add(array2[temp]);
                Console.WriteLine("第二种组合:" + array2[temp]);
            }
            foreach (var temp in RandomNoRepeat(3, array3.Length, array3))
            {
                newList.Add(array3[temp]);
                Console.WriteLine("第三种组合:" + array3[temp]);
            }
            foreach (var temp in RandomNoRepeat(4, array4.Length, array4))
            {
                newList.Add(array4[temp]);
                Console.WriteLine("第四种组合:" + array4[temp]);
            }

            foreach (var num in newList)
            {
                Console.WriteLine("新的组合:" + num); //输出
            }

            Console.ReadKey();
        }

        static List<int> RandomNoRepeat(int number, int total,int[] array)
        {
            List<int> result = new List<int>();
            Random ran = new Random();

            while (result.Count < number)
            {
                int num = ran.Next(total); //随机生成一个数
                if (!result.Contains(num)) //取的下标数不能重复
                {
                    result.Add(num);
                }
            }

            return result;
        }
    }
}


[此贴子已经被作者于2017-9-10 19:27编辑过]

1