vendredi 18 décembre 2020

c# - write 10 random lines from a file (without duplicates) into each of 15 files

so I have been trying to make a function that

  1. iterates through each file in a folder of 26 files,
  2. takes 10 random lines from a file of 20 lines,
  3. checks if the currently chosen line is already in the current file, if it is then try choosing again,
  4. writes the 10 random lines into each file.

This is what I have got so far. But I don't know why it's always out of bounds. I have tried putting the lines from file into another array via loop but this doesn't help either. Does anyone see what's wrong?

string[] lines = File.ReadAllLines(@"randomLines.txt");
assignLines(lines);
static void assignLines(string[] listOfLines)
        { 
            Random rnd = new Random();

            foreach (var file in Directory.EnumerateFiles(@"files", @"*.txt"))
            {
                string[] assignedLines = new string[] { };
                int j = 1;
                int i = 0;
                StreamWriter wr = new StreamWriter(file);
                while (i < 5)
                //for (int i = 0; i < File.ReadAllLines(file).Length + 1; i++)
                {

                    int chosen = rnd.Next(0, listOfLines.Length - 1);

                    if (assignedLines.Contains(listOfLines[chosen]))
                    {
                        continue;
                    }
                    else
                    {
                        assignedLines[i] = listOfLines[chosen];
                        wr.WriteLine(j + ". " + listOfLines[chosen] + ".");
                        j++;
                        i++;
                    }
                }
                wr.Close();
            }
        }



Aucun commentaire:

Enregistrer un commentaire