0

I have an Array Of Integers that Contains several Colors; 0xFF000000. I have attempted to create a function that returns the Color from the Array based on the parameter of the function. The parameters will be numbers to the power of two; 2,4,8,16,32. How can I figure calculate which index from the array to get the color from based on the Parameter?

Function:

 public static int getNumberColor(int number) {
    int index = number % colors.length;
    try {
        return colors[index - 1];
    } catch (Exception e) {

    }
    return colors[0];
}

What is the best way of doing this?

  • Maybe I'm missing something, but how should the parameter (`number`) be mapped onto the array indices? If it's just linearly in the order given (number 2, 4, 8, 16, 32 leads to index 0, 1, 2, 3, 4) then the solution is just a simple `log2(number)-1`. If `0` is a valid input too, then you can leave the `-1` subtraction out. – MH. Mar 10 '15 at 09:47
  • Could you Provide an Example of how to use Log2? –  Mar 10 '15 at 09:48
  • 1
    `log2(number)-1` was just semi-code to indicate the formula (not an actual method). For implementation examples, refer to i.e.: http://stackoverflow.com/questions/3305059/how-do-you-calculate-log-base-2-in-java-for-integers – MH. Mar 10 '15 at 09:50

0 Answers0