using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Util { public class RandomWordMatch { private readonly string baseChars = "1234567890"; private readonly string defaultMatchWord = "114514"; private bool _ProgressDisplay = true; public bool ProgressDisplay { get { return _ProgressDisplay; } set { _ProgressDisplay = value; } } public RandomWordMatch() { } public RandomWordMatch(string baseChars, string defaultMatchWord = "114514") { if (string.IsNullOrWhiteSpace(baseChars)) throw new ArgumentNullException("baseChars"); else if (string.IsNullOrWhiteSpace(defaultMatchWord)) throw new ArgumentNullException("defaultMatchWord"); this.baseChars = baseChars; this.defaultMatchWord = defaultMatchWord; } public void Start(string matchWord = null, int limit = int.MaxValue) { if (string.IsNullOrWhiteSpace(matchWord)) matchWord = defaultMatchWord; var wordQueue = new Queue(); foreach (var c in GetRandomString(matchWord.Count())) wordQueue.Enqueue(c); int count = 0; while (count < limit) { if (wordQueue.SequenceEqual(matchWord)) { foreach (var c in wordQueue) Console.Write(c); Console.WriteLine( "\n\n HIT!!! \n {0}回目で「{1}」!!!", (count + matchWord.Count()), matchWord); break; } count++; if (ProgressDisplay) { Console.Write(wordQueue.Dequeue()); } else { wordQueue.Dequeue(); } wordQueue.Enqueue(GetRandomString(1)[0]); } } private string GetRandomString(int length) { var sb = new StringBuilder(length); for (int i = 0; i < length; i++) sb.Append(baseChars[GetRandomNumber()]); return sb.ToString(); } private int GetRandomNumber() { var bs = new byte[4]; var rng = new RNGCryptoServiceProvider(); rng.GetBytes(bs); var num = BitConverter.ToInt32(bs, 0); return Math.Abs(num % baseChars.Length); } } } public class Test { public static void Main() { // var r = new Util.RandomWordMatch(); var r = new Util.RandomWordMatch("145"); r.Start(); } }