Reputation: 4096
What I am trying to achieve is some thing like this, Say we have a list of one thousand boxes and a list of 25 colors, now we want to assign colors to boxes such that the color is from given list, and every time i ask the box for color the same color will be choosen. The same color can be used by multiple boxes but the color of a same box will always be same no matter how many time I execute the algorithm.
I think I can have a list of 25 colors and an algorithm to create a unique number (within range of 25) based on name or id of the box.
Can any one help me what algorithm should work for me ?
update The requirement has changed slightly, and now I need five unique colors from that range, and the colors has to be same always. Say we are arranging boxes in groups of five, each box should get unique color within the range of 25 colors. And algorithm should give same colors for same group always.
Upvotes: 1
Views: 1091
Reputation: 691695
box.getId().hashCode() % 25
will get you a number between 0 and 24 (inclusive).
Note that since you didn't specify any rule for the distribution of the colors among boxes, the following algorithm also satisfies your requirements:
return 0;
If you want a good distribution, then iterate through your boxes, and fill a Map<String, Integer>
where the key is the box id and the value is the color:
Map<String, Integer> colorsByBoxId = new HashMap<String, Integer>();
int i = 0;
for (Box box : boxes) {
int colorIndex = i % 25;
i++;
colorsByBoxId.put(box.getId(), colorIndex);
}
And then use this map each time you want to get the color of a box.
Or simply do the same, and add a color
field to the Box class.
Upvotes: 4