# 12 sided dice with 5 replicated images

Hello, just imagine a 12 sided dice with 5 replicated images eg. 6 rabbits, 3 sheep, 1 pig, 1 cow, 1 wolf. And now lets make a logic for the throw. I copy here my working logic but I have a question: is it the best option or can it be done in a better way. Especially I am interested what better can be done with the replicated images. I mean if there are 6 rabbits it means that possibility of throwing a rabbit is six time more then a wolf. SO here is my working code:

``````var blueDiceAnimals = [
{ animal: "rabbit"
},
{ animal: "rabbit"
},
{ animal: "rabbit"
},
{ animal: "rabbit"
},
{ animal: "rabbit"
},
{ animal: "rabbit"
},
{
animal: "sheep"
},
{
animal: "sheep"
},  {
animal: "sheep"
},
{
animal: "pig"
},
{
animal: "cow"
},
{
animal: "wolf"
}
];

var diceMachine = {
blueDice: function() {
var newThrowBlue = blueDiceAnimals[Math.floor(Math.random() * blueDiceAnimals.length)];
},
};
``````

You could write it with something like this:

`[[6, "rabbit"], [9, "sheep"], [10, "pig"], [11, "cow"], [12, "wolf"]]`

Then when you generate your random number between 1-12, you iterate through the array until you find a number greater than or equal to the number generated. This would come in handy if you were rolling a hundred-sided die, but for 12 sides, Iâ€™d say your solution is plenty good enough. You might want to at least factor out those object literals into variables though.

1 Like

@chuckadams thank You for your help. Could You be so kind and write me if You find 2 minutes what You mean by - â€śYou might want to at least factor out those object literals into variables though.â€ť Thank You. Hubert

By refactoring, I mean reducing the repetition. Right now, you have a bunch of object literals, like `{ animal: "rabbit" }` repeated several times. What if you wanted to add another property to the object? Youâ€™d have to repeat it six times. Rather than doing that, you can define it in one place, and just use the name. Hereâ€™s what I mean.

``````let rabbit = { animal: "rabbit" };
let sheep = { animal: "sheep" };

let animals = [
rabbit, rabbit, rabbit, rabbit, rabbit, rabbit,
sheep, sheep, sheep // ... and so on ...
]
``````
1 Like