Skip to content

Instantly share code, notes, and snippets.

@jemc
Created December 18, 2013 02:45
Show Gist options
  • Save jemc/8016513 to your computer and use it in GitHub Desktop.
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
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