This post originated from an RSS feed registered with Ruby Buzz
by Jan Lelis.
Original Post: Storing an array of indices in an integer
Feed Title: rbJ*_*L.net
Feed URL: http://feeds.feedburner.com/rbJL
Feed Description: Hi, I am a fan of Ruby and like to explore it and the world around ;).
So I started this blog, where I am publishing code snippets, tutorials for beginners as well as general thoughts about Ruby, the web or programming in general.
Sometimes you have an array of indices. These might, for example, act as flags, whether some specific options are set or not.
Consider that you have to store such an array. You could do this in some kind of integer list. However, a better way is, to store it in only one single number.This can be achieved by treating each index as an exponent of 2, so you can build a binary representation out of them. Then this binary representation can be displayed as a single decimal number – and vice versa.
An example
Let’s assume that our array is:
[3,6,9]
Now we can treat it as 2 3 + 2 6 + 2 9, which equals 584. In this number, all the information is still present and can be converted back to
[3,6,9]
The following snippet is a ruby implementation of this.
# # # # # # ## 'binary representation': store an array of indices in one decimal number# and vice versaclass Arraydef to_bri# array to integerreturn0ifself==[]# first convert indices to a binary number and then use to_i # to convert it to an integer with base 2ret=[0]*(self.max+1)self.eachdo|ele|ret[self.max-ele]=1endret.join.to_i(2)endendclass Integerdef to_bra# integer to arrayret=[]# convert the decimal integer to binary form with to_s and base 2 and then# check each char to add the current index to the array, if it is setself.to_s(2).reverse.chars.each_with_indexdo|ele,index|ret<<indexifele=='1'endretendend# Example of use## jl = 584.to_bra # => [3, 6, 9]# jl.to_bri # => 584
Please note: There is no type checking or error management.