Skip to content

Instantly share code, notes, and snippets.

@cwharris
Last active July 13, 2018 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwharris/7fa7f64adc0b05af82af17e86169d6ea to your computer and use it in GitHub Desktop.
Save cwharris/7fa7f64adc0b05af82af17e86169d6ea to your computer and use it in GitHub Desktop.
Permutate
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