Skip to content

Instantly share code, notes, and snippets.

@mocoso
Created August 9, 2014 10:18
Show Gist options
  • Save mocoso/ae8188cd2b254e893bdc to your computer and use it in GitHub Desktop.
Save mocoso/ae8188cd2b254e893bdc to your computer and use it in GitHub Desktop.
An implementation of the Burrows–Wheeler transform that satisfies https://github.com/zetter/burrows-wheeler-transform
class BWT
def encode(string)
rotations("#{string}$").sort.map{ |s| s.slice(-1, 1) }.join
end
def decode(encoded_string)
encoded_string.chars.inject([]) do |strings|
encoded_string.chars.zip(strings).map(&:join).sort
end.detect { |s| s.slice(-1, 1) == '$' }[0..-2]
end
private
def rotations(string)
(1..string.length).map { |i| string.chars.rotate(i).join }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment