Skip to content

Instantly share code, notes, and snippets.

@nicolaracco
Created March 26, 2012 09:21
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 nicolaracco/44e1a07a55fbb26bb599 to your computer and use it in GitHub Desktop.
Save nicolaracco/44e1a07a55fbb26bb599 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class Anagram
def initialize filename
@cols = []
File.open filename do |file|
file.each do |line|
@cols << line.strip
end
end
end
def all_combinations
combinations = []
each_combination do |combination|
combinations << combination
end
combinations
end
private
def each_combination &block
clear_indexes_cache
# combinations size
@cols.map(&:size).inject(&:*).times do
block.call next_combination
end
end
def clear_indexes_cache
@indexes = Hash.new 0
end
def next_combination
@can_advance = true
@cols.size.times.map { |col| next_letter col }.join
end
def next_letter column
index = @indexes[column]
letter = @cols[column].chars.to_a[index]
advance_index column if can_advance_index column
letter
end
def can_advance_index column
@can_advance && @cols[column].size > (@indexes[column] + 1)
end
def advance_index column
@indexes[column] = @indexes[column] + 1
column.times { |col| @indexes[col] = 0 }
@can_advance = false
end
end
if __FILE__==$0
t = Time.now
a = Anagram.new 'in.txt'
puts a.all_combinations.join "\n"
puts "Time spent: #{Time.now - t}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment