I am rather unhappy with how I implemented this. I'd like some expert advice on how to write this correctly. For example, we might want to avoid the loop inside of a loop? But how?

This is very declarative and should be easy to read but unfortunately it's ugly and probably does not perform well. It's just for an a/b test but still :)