storkeye
storkeye

Reputation: 307

PHP Create a unique number from 1 to 9 using userid

In order to color code each row of a calendar I'd like to be able to create a unique integer from 1 to 9 using the field userid. I need to use the color in another part of the calendar to display the student assigned to the instructor.

Bear in mind that userID can be any length.

At first I thought of using the least significant digit, but that won't work for user IDs 01, 21, 22 etc.

Then I thought of adding the left to the right, eg userID 22 = 2+2=4, but that won't work either.

Any ideas how I might create a unique 0-9 integer based on the users ID?

Upvotes: 0

Views: 254

Answers (1)

mensi
mensi

Reputation: 9826

Any function mapping [0..N] to [1..9] will have collisions if N is larger than 9 and therefore there does not exist a scheme that maps them uniquely.

What you can do in your case is to just go through the userIDs and assign them the next free number if you have not seen this userID before. This is a simple for-loop + an array.

Pseudocode:

colors = array()
for userid in userids_to_color:
    if userid not in colors:
        colors[count(colors)] = userid

Colors is then a mapping index (=color number) to userid. You can break out of the loop if count(colors) becomes greater than your maximal number of colors.

Upvotes: 4

Related Questions