namespace HeuristicLab.Problems.ProgramSynthesis.Push.Generators { using System; using System.Linq; using HeuristicLab.Core; using HeuristicLab.Random; public class StringGenerator { public const int DefaultRandomNameLength = 10; private static readonly char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray(); private static readonly char[] lowercaseChars = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); private static readonly char[] uppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); private static readonly char[] digitChars = "1234567890".ToCharArray(); private const char space = ' '; private int index; public string GetNext() { var length = index < chars.Length ? 1 : (int)Math.Log(index, chars.Length) + 1; var result = new char[length]; var tmp = index; index++; for (var i = length; i > 0; i--) { var a = (int)Math.Pow(chars.Length, i - 1); var b = tmp / a; result[length - i] = chars[b]; tmp -= a * b; } return new string(result); } public static string RandomName(IRandom random) { return RandomName(DefaultRandomNameLength, random); } public static string RandomName(int length = DefaultRandomNameLength, IRandom random = null) { random = random ?? new FastRandom(); var name = new char[length]; for (var i = 0; i < length; i++) name[i] = chars[random.Next(chars.Length)]; return new string(name); } public static string RandomString(bool allowLowercase, bool allowUppercase, bool allowSpace, double spaceProbability, int length, IRandom random = null) { if (!allowLowercase && !allowUppercase) return string.Empty; random = random ?? new FastRandom(); var name = new char[length]; var sourceChars = Enumerable.Empty(); if (allowLowercase) sourceChars = sourceChars.Concat(lowercaseChars); if (allowUppercase) sourceChars = sourceChars.Concat(uppercaseChars); var chars = sourceChars.ToList(); for (var i = 0; i < name.Length; i++) { name[i] = allowSpace && spaceProbability >= random.NextDouble() ? space : chars[random.Next(0, chars.Count)]; } return new string(name); } public static char RandomChar(int from, int to, IRandom random = null) { if (from > to) throw new InvalidOperationException(); random = random ?? new FastRandom(); return Convert.ToChar(from == to ? from : random.Next(from, to)); } } }