Any thoughts on how to improve this? The permutation part at the beginning and the `reduce` might be a little hard to follow.