What is the cleanest way to implement ‘frequency capping’ in Prolog?

Let’s say I have this code.

```
item(a).
item(b).
item(c).
item(d).
pairs(First, Second) :- item(First), item(Second).
```

It returns all permutations of a,b,c,d.

How to introduce a constraint so that the result has no letter in the same position more than twice? E.g. after returning *(a,a)* and *(a,b)*. (a,c) should be excluded, proceeding to (b,b), excluding (b,c) and so on.

I think it can be viewed as an optimization task but I hope there is an easier solution where I would keep a running total of value occurrences and fail when it exceeds the limit.

Any help is appreciated.

Thank you