How to create random files and folders?

During this week of one hour of code, this post refers to a quick and easy way to create random files and folders. Nothing complicated as it was the case in some previous posts. This one came out of a real at-work problem in Bing: in order to validate some scenarios, we wanted a cheap and quick way to create thousands of files and folders, subfolders too, in a semi-random fashion. A simple task. The 50 lines of code down below did the trick. I think the two key interesting points of this code for the novice developer are the following:
a) A way to achieve something with probability N is to simply do something like this: Rand(0, 100) < N. I've seen junior developers trying complicated things - this should do the trick. These are the spots in the code where we do it.
b) State control. Notice that that we use a simple depth variable to determine when we can come down a folder, or to keep creating subfolders. Just by increasing and decreasing this variable controls where we are at, and hence allows us to keep going deeper or not.

Hope you enjoy, and keep on coding. Merry Christmas!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace CreateRandomFilesAndFolders {
 class Program {
  static void Main(string[] args) {
   if (args.Length != 2) {
    Console.WriteLine("Usage: CreateRandomFilesAndFolders <name prefix> <how many?>");
    return;
   }
   string namePrefix = args[0];
   int howMany = Int32.Parse(args[1]);
   Random rd = new Random();
   int depth = 0;
   int MAXDEPTH = 5;
   Console.Write("Processing...");
   for (int index = 1; index <= howMany; index++) {
    //File or folder? 75% chance of a file, 25% chance of a folder
    string resourceName = namePrefix + index.ToString();
    if (rd.Next(0, 100) < 75) {
     string[] extensions = {
      ".txt", ".doc", ".blah", ".mp3", ".mp4", ".tuamae", ".ppt", ".bmp", ".gif", ".jpeg"
     };
     string extension = extensions[rd.Next(0, extensions.Length)];
     resourceName += extension;
     File.Create(resourceName);
    } else if (depth < MAXDEPTH) {
     Directory.CreateDirectory(resourceName);
     Directory.SetCurrentDirectory(resourceName);
     depth++;
    }
    if (depth > 0 && rd.Next(0, 100) < 25) //25% chance to come down
    {
     Directory.SetCurrentDirectory("..\\");
     depth--;
    }
   }
   Console.WriteLine("Done!");
  }
 }
}

Comments

Popular posts from this blog

Changing the root of a binary tree

Prompt Engineering and LeetCode

ProjectEuler Problem 719 (some hints, but no spoilers)