# statistics – How to count near duplicates in a mixed pool using AnyDice?

The programs given in my answer to your previous question can be fairly easily modified to also count “near misses”. Taking advantage of the fact that the input arrays are sorted (in descending order by AnyDice, in ascending order by Python), we can replace the equality comparisons with checks that the difference of adjacent elements is at most 1.

For example, in AnyDice:

``````function: near dupes in A:s B:s C:s {
DICE: (sort {A, B, C})
DUPES: 0
loop X over {1..#DICE} {
PREV_MATCH: X > 1 & (X-1)@DICE <= X@DICE + 1
NEXT_MATCH: X < #DICE & (X+1)@DICE >= X@DICE - 1
if PREV_MATCH | NEXT_MATCH { DUPES: DUPES + 1 }
}
result: DUPES
}

output (near dupes in 1d12 2d10 1d8)
``````

or, if you need a solution less likely to time out for large dice pools, in Python using the dice rolling framework from this answer:

``````from collections import defaultdict
summary = defaultdict(float)

for d12, p12 in dice_roll(12, count=3):
for d10, p10 in dice_roll(10, count=2):
for d8, p8 in dice_roll(8, count=1):
prob = p12 * p10 * p8
roll = sorted(d12 + d10 + d8)
dupes = sum(
(i > 0 and roll(i-1) >= roll(i) - 1)
or (i < len(roll)-1 and roll(i+1) <= roll(i) + 1)
for i in range(len(roll))
)
summary(dupes) += prob

for dupes, prob in sorted(summary.items()):
print("%d duplicates: %.2f%%" % (dupes, 100 * prob))
``````