I'm trying to come up with a solution where I need to roll a number of dice (all of the same size) and come to a specified number. Provided I have all the validation in place to make sure the numbers are valid and could theoretically arrive at the desired result, does anyone have a good algorithm for solving this? Note it should appear random, not just a straight divide.

Some examples

> 
> roll 3 d6 and get 14 -> so it could output 5,3,6 or 6,6,2
> 
> 
> roll 4 d20 and get 66 -> so it could output 16,14,19,17
> 
> 
> 

I need a generic function that can accept a dice of any size, any amount to be rolled and the desired result.

My initial attempt is below, though this doesn't produce the desired output (you can ignore the `mod` for now, this was to also allow modifiers). This example is also missing the validation that the desired output is achievable,but that's not part of the question.

```
let desired = 19
let mod = 0
let dm = desired - mod
let n = 5;// number of dice
let d = 6 // dice sides
let nums = []

for(i =0; i< n; i++) {
    nums.push(Math.round(Math.random() * Math.round(d)) + 1)
}

let sum = nums.reduce((acc,val) => acc + val)

nums = nums.map(a => Math.round((a/sum) * dm))

let diff = dm - (nums.reduce((acc,val) => acc + val))
function recursive(diff) {
    let ran = nums[Math.random() * Math.round(nums.length -1)]
    if(nums[ran] + diff > d || nums[ran] + diff < 1) {
        recursive(diff)
    } else {
        nums[ran] += diff
    }
}
while(diff != 0) {
    recursive(diff)
    diff += diff < 0 ? 1 : -1;
}

alert(nums)

```