Skip to content

Instantly share code, notes, and snippets.

@robhol
Last active May 31, 2017 06:25
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 robhol/9801df55b5ec846a863b7a2f9ec4bbf2 to your computer and use it in GitHub Desktop.
Save robhol/9801df55b5ec846a863b7a2f9ec4bbf2 to your computer and use it in GitHub Desktop.
GenerateKeys("0123456789ABCDEF", 2).Dump();
IEnumerable<string> GenerateKeys(IEnumerable<char> charset, int length)
{
var charsetArray = charset.ToArray();
var output = new int[length];
if (length < 1) throw new ArgumentOutOfRangeException(nameof(length));
while(true)
{
yield return string.Concat(output.Select(x => charsetArray[x]));
//increment and "carry"
for(int i = length - 1; i >= 0; i--)
{
output[i] = (output[i] + 1) % charsetArray.Length;
if (output[i] != 0) //simple addition, didn't need to carry over to the next digit
break;
if (i == 0) //"carrying" at the last digit, we're done
yield break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment