Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Created December 5, 2018 18:42
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 jcoglan/417b5cee7081063f5f2cd4c86ed98e1b to your computer and use it in GitHub Desktop.
Save jcoglan/417b5cee7081063f5f2cd4c86ed98e1b to your computer and use it in GitHub Desktop.
class SuperPermutation
CHARS = ('a'..'z').map(&:to_sym)
def initialize(size)
@size = size
@chars = CHARS.take(@size)
@used = {}
@index = Hash.new { |h, k| h[k] = [] }
@chars.permutation.each do |seq|
@used[seq] = false
(0...@size).each { |n| @index[seq.take(n)] << seq }
end
end
def generate
@string = @chars.clone
@count = @used.size - 1
@cursor = 0
@used[@string] = true
build_string until @count == 0
@string
end
def build_string
@cursor += 1
prefix = @string.drop(@cursor)
picked = @index[prefix].find { |seq| not @used[seq] }
return unless picked
@string.concat(picked.drop(prefix.size))
@used[picked] = true
@count -= 1
end
end
(1..6).each do |n|
sp = SuperPermutation.new(n)
seq = sp.generate
p [seq.size, seq]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment