Created
December 18, 2013 02:45
-
-
Save jemc/8016513 to your computer and use it in GitHub Desktop.
Generating all possible strings of characters with a given character set and length
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
class BruteForce | |
extend Enumerable | |
def initialize(size, alphabet) | |
@alphabet = alphabet | |
if size.respond_to?(:min) and size.respond_to?(:max) | |
@start_size = size.min | |
@end_size = size.max | |
else | |
@start_size = @end_size = size | |
end | |
end | |
def each &block | |
recursive = Proc.new do |ary| | |
if ary.size >= @start_size | |
block.call ary # yield to caller | |
end | |
if ary.size < @end_size | |
@alphabet.each do |z| | |
recursive.call(ary + [z]) # Recurse deeper | |
end | |
end | |
end | |
recursive.call [] | |
end | |
end | |
alphabet = ('A'..'Z').to_a + ('0'..'9').to_a + ['_'] | |
BruteForce.new(1..4, alphabet).each { |list| puts list.join } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment