How to pick same colors for same userid

97 views Asked by At

I have a library in which a String userid is passed so basis on that String userid, I need to pick either one of these three colors only.

RED
BLUE
PINK

Let's say if String userid is 12345 then for example it can pick RED so next time if same userid 12345 is passed then it should pick same RED colors only. Another example if String userid is 98765, then in this case it can pick BLUE so next time if same user id 98765 is passed, then it should pick same BLUE colors only.

Idea is for same userid, it should pick same colors always. It should not be for same userid it picks one colors first time and then second time it picks some other colors.

What kind of hashing techniques I can use on userid here so that I can pick same colors always for same userid?

public enum Colors {
    RED, BLUE, PINK;        


    private String pickColor(String userid) {


    }
}
2

There are 2 answers

1
Tony the Pony On BEST ANSWER

This will do the trick:

int userColor = userName.hashCode() % numberOfColors;
1
Em Ae On

userName.hashCode() % Colors.values().length() would do the trick. But you might have to change your enum so that

public enum Colors {
    RED (0),
    BLUE (1),
    PINK(2);

/* write method to find enum by value */
}