如何为循环的每次迭代运行一个函数?

时间:2018-10-11 10:01:51

标签: c# arrays loops iteration genetic-algorithm

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AI_practice
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter target string...");
            string targetString = Console.ReadLine();
            int targetStringLength = targetString.Length;
            Console.WriteLine("Enter Population size...");
            int popSize = Convert.ToInt16(Console.ReadLine());
            string[] pool = new string[popSize];         

            int i = 0;
            do
            {
                string populationPool = RandomStringGenerator(targetStringLength);
                Console.WriteLine(pool[i] = populationPool);
                i++;                              
            }
            while (i < popSize);

            Console.ReadKey();
        }

        static string RandomStringGenerator(int targetStringLength)
        {
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var stringChars = new char[targetStringLength];
            var random = new Random();

            for (int i = 0; i < stringChars.Length; i++)
            {
                stringChars[i] = chars[random.Next(chars.Length)];
            } 

            var finalString = new String(stringChars);
            return finalString;        
        }
    }
}

我的代码旨在运行该函数并将结果输入到数组中。它旨在产生大量随机创建的字符串,但是此代码的输出是多次输出的同一字符串。如何确保输出的所有字符串都是随机生成的?

0 个答案:

没有答案