Archive for the ‘Ruby’ Category

Function of the Day ::: Bijective Hexavigesimal Encoding in Ruby

Monday, January 2nd, 2012

Have you ever noticed how column headers are labeled using letters instead of numbers in a spread sheet? After running from A to Z, the sequence picks up with AA to AZ, then AAA to AAZ, and so forth.

This is a Base-26 (i.e. hexavigesimal) encoding, that doesn’t employ any of its symbols to represent zero (i.e. bijective). As such it is only defined for the Counting Numbers (i.e. 1, 2, 3, …)

This is can be implemented in the Ruby programming language with this utility function:

def bijective_hexavigesimal(n)

   #  Copyright 2012 by Peter J. Wasilko and The Institute for End User Computing, Inc.
   #
   #      Website: http://www.ieuc.org
   #
   #      Email:   info@ieuc.org
   #
   #   Converts a Counting Number to Bijective Hexavigesimal form.
   #
   #      Example: bijective_hexavigesimal(27) => "aa"
   #
   #      Tested under Ruby 1.9.3p0
   #
   #   Please use freely for any non-commercial purposes.
   #

   if ((n < 1) || !(n.is_a? Integer)) then
      raise "Bijective Hexavigesimal encoding is only defined for counting numbers"
   end

   alphabet = %w[a b c d e f g h i j k l m n o p q r s t u v w x y z]

   hexavigesimal_digits = []

   while (n > 0) do
      remainder = (n - 1).remainder 26
      hexavigesimal_digits.unshift alphabet[remainder]
      n = ((n + 1) - remainder) / 26
   end

   return hexavigesimal_digits.join.to_s

end