Skip to content

Instantly share code, notes, and snippets.

@long-long-float
Created February 1, 2015 07:19
Show Gist options
  • Save long-long-float/d2eacc68e6133551da7d to your computer and use it in GitHub Desktop.
Save long-long-float/d2eacc68e6133551da7d to your computer and use it in GitHub Desktop.
文字列のサイコロ符号化(速度度外視)
# Usage: ruby convert.rb FILE
require 'zlib'
# サイコロの組み合わせ数
N = (2 + 4 + 4 + 2 + 2 + 4) * 3
def num2num_ary(num, base)
num_ary = []
while num != 0
num_ary << num % base
num = num / base
end
num_ary
end
def num_ary2num(ary, base)
num = 0
x = 1
ary.each do |n|
num += x * n
x *= base
end
num
end
def to_dice(data)
num2num_ary(('1' + data.unpack('b*')[0]).to_i(2), N)
end
raw = ARGF.read
compressed = Zlib.deflate raw
# 符号化
puts "size of compressed: #{compressed.size} (raw: #{raw.size})"
diced = to_dice(compressed)
puts "number of required dice: #{diced.size} (raw: #{to_dice(raw).size})"
# 復号化
decoded = Zlib.inflate [num_ary2num(diced, N).to_s(2)[1..-1]].pack('b*')
puts decoded
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment