Advertisement
Guest User

Untitled

a guest
Dec 5th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. describe "Caesar" do
  2.  
  3. latin_encrypter = Caesar.new 4
  4. dna_encrypter = Caesar.new 3, 'ACTG'
  5.  
  6. it 'encrypts correctly' do
  7. expect(latin_encrypter.encrypt 'hello').to eq "lipps"
  8. end
  9.  
  10. it 'encrypts correctly using DNA alphabet' do
  11. expect(dna_encrypter.encrypt 'ACCTGA').to eq "GAACTG"
  12. end
  13.  
  14. it 'decrypts correctly' do
  15. expect(latin_encrypter.decrypt 'lipps').to eq 'hello'
  16. end
  17.  
  18. it 'decrypts correctly using DNA alphabet' do
  19. expect(dna_encrypter.decrypt 'GAACTG').to eq 'ACCTGA'
  20. end
  21. end
  22.  
  23. class Caesar
  24. def initialize(shift, alphabet = 'abcdefghijklmnopqrstuvwxyz')
  25. @shift = shift % alphabet.size
  26. @alphabet = alphabet
  27. end
  28.  
  29. def encrypt(string)
  30. string.chars.map { |char| @alphabet[@alphabet.index(char) + @shift - @alphabet.size] }.join
  31. end
  32.  
  33. def decrypt(string)
  34. string.chars.map { |char| @alphabet[@alphabet.index(char) - @shift] }.join
  35. end
  36. end
  37.  
  38. class Caesar
  39. def initialize(shift, alphabet = ('a'..'z').to_a.join)
  40. i = shift % alphabet.size #I like this
  41. @decrypt = alphabet
  42. @encrypt = alphabet[i..-1] + alphabet[0...i]
  43. end
  44.  
  45. def encrypt(string)
  46. string.tr(@decrypt, @encrypt)
  47. end
  48.  
  49. def decrypt(string)
  50. string.tr(@encrypt, @decrypt)
  51. end
  52. end
  53.  
  54. class Caesar
  55. def initialize(shift, alphabet = ('a'..'z').to_a.join)
  56. @shift = shift
  57. @alphabet = alphabet
  58. @indexes = alphabet.chars.map.with_index.to_h
  59. end
  60.  
  61. def encrypt(string)
  62. string.chars.map { |c| @alphabet[(@indexes[c] + @shift) % @alphabet.size] }.join
  63. end
  64.  
  65. def decrypt(string)
  66. string.chars.map { |c| @alphabet[(@indexes[c] - @shift) % @alphabet.size] }.join
  67. end
  68. end
  69.  
  70. class Caesar
  71. def initialize(shift, alphabet = ('a'..'z').to_a.join)
  72. chars = alphabet.chars.to_a
  73. @encrypter = chars.zip(chars.rotate(shift)).to_h
  74. @decrypter = chars.zip(chars.rotate(-shift)).to_h
  75. end
  76.  
  77. def encrypt(string)
  78. @encrypter.values_at(*string.chars).join
  79. end
  80.  
  81. def decrypt(string)
  82. @decrypter.values_at(*string.chars).join
  83. end
  84. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement