I don't think you will find an easy way to do this with a single formula, there is a table in sheet 2 used to provide the correct combinations.

sample3(1).xlsx