Skip to content

Instantly share code, notes, and snippets.

@beezee
Created January 11, 2015 06:52
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 beezee/08bcf2d32d6a69c5536b to your computer and use it in GitHub Desktop.
Save beezee/08bcf2d32d6a69c5536b to your computer and use it in GitHub Desktop.
Rail Fence Cipher #rdaily
class RCipher
def take(s, n, stream)
x = 0
val = s
acc = []
while x < n do
val = stream.call(val)
acc.push(val)
x += 1
end
acc
end
def rail_stream(num_rails)
plus = ->(n) { n + 1 }
minus = ->(n) { n - 1 }
op = plus
next_value = ->(n) do
if n <= 1
op = plus
elsif n >= num_rails
op = minus
end
op.call(n)
end
end
def zip_sort(list1, list2)
indices = {}
list1.zip(list2).each do |(l, r)|
indices[l] ||= []
indices[l].push(r)
end
list1.sort.uniq.inject([]) {|a, i| a + indices[i] }
end
def enc_list(n, list)
s = take(0, list.size, rail_stream(n))
zip_sort(s, list)
end
def enc(n, string)
enc_list(n, string.split("")).join("")
end
def dec(n, string)
o = enc_list(n, (1..string.size).to_a)
zip_sort(o, string.split("")).join("")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment