Last active
August 29, 2015 14:16
-
-
Save 0V/44f0fbe170cf0d9d5b9f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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<char>(); | |
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment