1
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;        
        }
    }
}

My code is meant to run the function and input the result into the array. It is meant to produce a population of randomly created strings, but the output of this code is the same string outputted numerous times. How can I ensure that the strings being outputted are all randomly generated?

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
Rahil Vig
  • 11
  • 1
  • 5
    Don’t create the `Random` each time, use a single one. – Sami Kuhmonen Oct 11 '18 at 10:03
  • 3
    @SamiKuhmonen has the right answer. As a note to the actual question title: "How do I run a function for each iteration of the loop in C#" some basic debugging would have shown that you were in fact running the function for each iteration of the loop. If you don't know how to do basic debugging then now is a great time to learn. There is lots of information on it out there just a short google away! – Chris Oct 11 '18 at 10:04

0 Answers0