move-to-front_transform.sf 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/ruby
  2. # Author: Trizen
  3. # Date: 13 June 2023
  4. # https://github.com/trizen
  5. # The Move to Front transform (MTF).
  6. # Reference:
  7. # COMP526 Unit 7-6 2020-03-24 Compression - Move-to-front transform
  8. # https://youtube.com/watch?v=Q2pinaj3i9Y
  9. func mtf_encode (bytes, alphabet = @(^256)) {
  10. var C = []
  11. for c in bytes {
  12. C << alphabet.first_index(c)
  13. alphabet.prepend(alphabet.delete_index(C.tail))
  14. }
  15. return C
  16. }
  17. func mtf_decode (encoded, alphabet = @(^256)) {
  18. var S = []
  19. for p in encoded {
  20. S << alphabet[p]
  21. alphabet.prepend(alphabet.delete_index(p))
  22. }
  23. return S
  24. }
  25. var str = "INEFICIENCIES"
  26. var encoded = mtf_encode(str.bytes, @(ord('A') .. ord('Z')))
  27. var decoded = mtf_decode(encoded, @(ord('A') .. ord('Z')))
  28. say "Encoded: #{encoded}" #=> Encoded: 8 13 6 7 3 6 1 3 4 3 3 3 18
  29. say "Decoded: #{decoded.join_bytes}" #=> Decoded: INEFICIENCIES
  30. assert_eq(decoded.pack('C*'), str)
  31. do {
  32. var str = File(__FILE__).read(:raw)
  33. var encoded = mtf_encode(str.bytes)
  34. var decoded = mtf_decode(encoded)
  35. assert_eq(str, decoded.pack('C*'))
  36. }