Skip to content

Instantly share code, notes, and snippets.

@Najaf
Created May 2, 2017 16:32
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 Najaf/9384eb42c738465fdacbf0547c94373b to your computer and use it in GitHub Desktop.
Save Najaf/9384eb42c738465fdacbf0547c94373b to your computer and use it in GitHub Desktop.
Rough implementation of Burrows-Wheeler
# Rough implementation of BW transform
# As described at the wikipedia page: https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform
EOF_CHAR = '|'
def bwt(string)
string_with_eof = string + EOF_CHAR
rotations = []
0.upto(string_with_eof.length - 1) do |i|
rotations << string_with_eof.chars.rotate(i).join
end
rotations.sort.reduce('') do |memo, rotation|
memo += rotation.chars.last
memo
end
end
def inverse_bwt(string)
rotations = []
string.length.times { rotations << [] }
string.length.times do
rotations.each_with_index do |rotation, index|
rotations[index].unshift(string[index])
end
rotations.sort_by! do |rotation|
rotation.join
end
end
inverse_array = rotations.select do |rotation|
rotation.last == EOF_CHAR
end
inverse = inverse_array.first.join
inverse.chomp(EOF_CHAR)
end
string = "^BANANA"
puts inverse_bwt(bwt(string)).inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment