This is a homework question, and you gain nothing by getting a complete solution (other than perhaps an A which you wouldn't deserve!)
Instead I can give you some pointers, which will hopefully get you to the right answer.
The first thing to be aware of is that when doing mathematical calculations you want to be dealing with numbers, so change your first line appropriately
var amount = 30;
(Be aware that if you are letting the user input this number you will want to ensure its numeric and convert it to a number - user input is almost always a string. Use parseInt(<user input>,10)
).
The second thing to do is divide your amount by 12. Floor this number using Math.floor
to get an integer. In this example you will get 24
.
(Another way to think of the above is to investigate the modulo operator %
, which can be used instead)
At this point you can create an array, with 12 elements (one for each camel) each element should have a count of 2 (representing 2 cargo items each). (see ref1)
With this example you will end up with a remainder of 6
and the only thing left to do is distribute the remaining 6
randomly among your camels.
You can achieve this by putting all 12 camels into an array, loop 6
(or, whatever your remainder was) times and pick a random number between 0
and {length of camel array}-1
. Assign that cargo to the selected camel and remove that camel from the camel array. This ensures that no one camel randomly gets assigned more than one extra cargo.
As with programming in general, that last bit should be broken down into individual manageable steps.
- Create an array with 12 elements (where 12 is the number of camels). The elements of this array should be numbers 0-11 representing the index in the array earlier
- Create a loop to repeat the following code once for each remainder
- Inside the loop :
- pick a random number (see ref2) between 0 and the length of the array created in 1.
- use that random number to increment the count in the array created earlier
- remove the element from the array created in 1.
Don't get confused; there are 2 arrays here. One you created much earlier - it has 12 elements and tracks the number of cargos on each camel, the other is temporary, used for tracking which camel has been assigned an "extra" cargo. The former never changes length, whereas the latter gets reduced in size as camels are assigned an extra cargo.
reference material: