Last active
July 13, 2018 22:01
-
-
Save cwharris/7fa7f64adc0b05af82af17e86169d6ea to your computer and use it in GitHub Desktop.
Permutate
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.Text; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
var randomPassword = | |
Permutate( | |
100, | |
new[] | |
{ | |
new PermutationRule | |
{ | |
AtLeast = 1, | |
Characters = new HashSet<char>("ABCDEFGHIJKLMNOP") | |
}, | |
new PermutationRule | |
{ | |
AtLeast = 1, | |
Characters = new HashSet<char>("1234567890") | |
}, | |
new PermutationRule | |
{ | |
AtLeast = 1, | |
Characters = new HashSet<char>("!@#$%^&*()_+") | |
}, | |
} | |
); | |
Console.WriteLine(randomPassword); | |
} | |
public static string Permutate(int minLength, params PermutationRule[] rules) | |
{ | |
if (rules.Length == 0) | |
{ | |
throw new ArgumentException("rules"); | |
} | |
var random = new Random(); | |
var sb = new StringBuilder(); | |
foreach (var rule in rules) | |
{ | |
for (var i = 0; i < rule.AtLeast; i++) | |
{ | |
sb.Insert( | |
random.Next(0, sb.Length), | |
rule.Characters.ElementAt(random.Next(0, rule.Characters.Count - 1)) | |
); | |
} | |
} | |
for (var i = sb.Length; i < minLength; i++) | |
{ | |
var rule = rules[random.Next(0, rules.Length)]; | |
sb.Append(rule.Characters.ElementAt(random.Next(0, rule.Characters.Count))); | |
} | |
return sb.ToString(); | |
} | |
public class PermutationRule | |
{ | |
public int AtLeast { get; set; } | |
public HashSet<char> Characters { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment