Help with Ruby -> Java conversion

Joined
Oct 23, 2005
Messages
670
Code:
def hash(s,M)  # Returns integer 0..M-1
	y = 0
	s.each { |c| y = y * 127 + Integer(c) }
	return y % M
end

Need help converting this chunk of code in Ruby to Java.
 
I don't know Ruby, but this seems simple enough. Function is a simple hash function, takes a string and a modulus. Initialize hash to zero, for every character C, hash = hash*127+IntegerValueOf C. Return hash mod M.

The only real question is whatever Integer(C) really returns. I've run the code with some test strings, and it seems to return the decimal value of a string ("0" -> 0, "0xF" -> 15", "0xFF" -> 255). As far as I can figure out, this expects a string with a number, which is weird in itself.

For S = "0x1234567890", M = 63 it returns 45.

And just to be absolutely clear, since this is Ruby, "s" can probably be anything with an "each()" which can iterate over elements of that structure (say for instance, a list), so the function is at least partially defined by what you pass in.
 
This produces the same output as the ruby one for me.
Code:
public class TestMe {
    public static int hash(final String s, final int m) {
        return java.lang.Integer.parseInt(s) % m;
    }
    public static void main(String args[]) {
        System.out.println(hash("12345678", 8));
    }
}
 
Back
Top