Created
June 17, 2010 02:43
-
-
Save jdar/441614 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
# options available by superclassing. See defs/examples below. | |
class MDS | |
class << self | |
def shalphadecimal(number) | |
case number | |
when String | |
require 'digest' | |
shalphadecimal( Digest::MD5.new << number ).rjust(20,"0") | |
when (0..(base - 1)) | |
options[:alphabet][number,1] | |
when Integer | |
[ number/base, remainder = number%base ].inject("") do |string, i| | |
string += shalphadecimal(i).to_s | |
end | |
else; raise TypeError | |
end | |
rescue TypeError => e | |
raise e, 'number must be a positive integer' | |
end | |
alias shal shalphadecimal | |
def deconstruct_simple(shal) | |
digits = shal.to_s.split('').map {|d| upcase(d) } | |
padding = digits.length | |
decomposition = [] | |
strings = [] | |
digits.each_with_index do |digit,index| | |
spacing = 12 + digits.length - (padding -= 1) | |
base10 = options[:alphabet].index(digit.to_s) || (puts("skipping #{digit}") || next) | |
power = digits.length-index-1 | |
last = (decomposition << base10*(base**power))[-1] | |
strings << digit.to_s + "(#{base10}* #{base}^#{power})" + " => " + (last).to_s.rjust(spacing, " ") | |
end | |
puts strings | |
sum = decomposition.inject(0) {|i,d|i+=d} | |
end | |
alias to_i deconstruct_simple | |
protected | |
# OPTIONS (override in Thor?) | |
def options; {:alphabet=>'0123456789ACDEFGHJKMNPQRTUVWXYZ'} end | |
def base; options[:alphabet].length end | |
def upcase(character); character.upcase end | |
end | |
end | |
=begin | |
require 'test/unit' | |
class MDSTest < Test::Unit::TestCase | |
def test_single_digit assert_equal "G", MDS.shal(15) end | |
def test_double_digit assert_equal "1G", MDS.shal( 31 + 15) end | |
def test_triple_digit; assert_equal "12G", MDS.shal( 31*31 + 2*31 + 15) end | |
def test_binary; assert_equal "HAXOR", MDS.shal(652190) end | |
def test_negative_i; assert_raise TypeError,MDS.shal(-100) end | |
end | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment