Looking to code some probabilities based on dice rolls, but a mechanic that is slowing me down deals with isolating the value shown by the second highest rolled die (and subsequently third highest, etc.)
So say I've got $n$ fair dice of size $m$, of the $m^n$ possible permutations sorted by size, how often would you expect to see k in the second highest slot, assuming $k = 1,…,m$?
I did some brute force up to $5$ d4s to see if I could infer any trends. This question led me to the formula $k^n - (k-1)^n$ to calculate occurance rates of highest values, and I can retrofit it to give lowest value by $(m-k+1)^n - (m-k)^n$. This has worked for all values I've been able to brute force.
Knowing how to calculate highest and lowest and knowing that total occurance rate for any given number is m^n means that I can derive the middle value when $n=3$, by using $m^n - (m-k+1)^n - (m-k)^n - k^n - (k-1)^n$, so a general form for all $n$ could be linked to that somehow, but I'm unable to derive it offhand.
So ndm is 3d4, there are $64$ possible permutations, only one roll can provide a $1$ as the highest value ${1,1,1}$, but seven rolls can put $2$ as the highest value $\lbrace1,1,2\rbrace,\lbrace1,2,1\rbrace,\lbrace2,1,1\rbrace,\lbrace1,2,2\rbrace,\lbrace2,1,2\rbrace,\lbrace2,2,1\rbrace$ and $\lbrace2,2,2\rbrace$, nineteen rolls put $3$ as the highest value, and thirty-seven rolls put $4$ in the highest slot. In the lowest slot, $4$ mirrors the $1$ for the lowest, with only $\lbrace4,4,4\rbrace$ working, low three mirrors high two with seven rolls, two has nineteen, and one has thirty-seven.
What I'm looking for is some equation that would allow me to calculate the occurrence rates for each non-highest or lowest slot, so with the 3d4 example, one crops up in second place ten times, two shows up twenty two times, as does three, and four is back down to ten.
How would I find the occurrence rates for the second highest in things like 4d4 when one shows up $13$ times, two $67$ times, three $109$ times and four $67$ times? Then beyond that, what would be the general form for the number of times $k$ shows up as the $x$th term of $n$ dice of size $m$?