Joey Joey - 4 months ago 16
Java Question

Convert JavaScript function to

I need to change this code from JavaScript to Java from this website:

https://jsfiddle.net/3L6L2fmv/?utm_source=website&utm_medium=embed&utm_campaign=3L6L2fmv

This is the call from another function that generates random numbers but has a 1 in 51 chance of the number being zero: (where "hash" is a 64-bit hexadecimal number)

// In 1 of 51 games the game crashes instantly.
if (divisible(hash, 51))
return 0;


And this is the function: (where mod is always 51)

function divisible(hash, mod) {
// So ABCDEFGHIJ should be chunked like AB CDEF GHIJ
var val = 0;

var o = hash.length % 4;
for (var i = o > 0 ? o - 4 : 0; i < hash.length; i += 4) {
val = ((val << 16) + parseInt(hash.substring(i, i+4), 16)) % mod;
}

return val === 0;
}


So basically when ever the JavaScript version returns a zero for a certain hash, I need the Java version to also return a zero for the exact same hash.

Here is my first attempt and pretty much as far as I can get due to my poor knowledge of JavaScript.

public static double divisible(String hash, int mod)
{
int val = 0;
int o = hash.length() % 4;
int i = 0;

if(o > 0) {i = o - 4;}
if(o < 0) {i = 0;}

for ( int a = i; a < hash.length(); a += 4)
{
val = ((val << 16) + Integer.parseInt(hash.substring(i, i+4), 16)) % mod;
}
return val;
}

Answer

Looks like you just confused the variables a bit in your Java code, other than that, it seems fine.

public static double divisible(String hash, int mod) 
{
    int val = 0;        
    int o = hash.length() % 4;      
    int i = 0;

    if(o > 0) {i = o - 4;}
    if(o < 0) {i = 0;}

    for ( int a = i; a < hash.length(); a += 4) 
    {           
       val = ((val << 16) + Integer.parseInt(hash.substring(a, a+4), 16)) % mod;            
    }
    return val;
 }

The values in the substring should be a not i. You probably assumed i = index.

An improvement would be the following. You do not need to create a new variable in Java for loops.

public static double divisible(String hash, int mod) 
{
    int val = 0;        
    int o = hash.length() % 4;      
    int i = 0;

    if(o > 0) {i = o - 4;}
    if(o < 0) {i = 0;}

    for (; i < hash.length(); i += 4) 
    {           
       val = ((val << 16) + Integer.parseInt(hash.substring(i, i+4), 16)) % mod;            
    }
    return val;
 }