Google Sheets advanced alternate sorting

For example: I have a random list of 8 students, 4 in Room 101, 4 in Room 102, different gender, 4 different categories.

How can I sort a random list in Google Sheets so it returns each Room with one Female and one Male but it also alternates through categories and it starts over after cycling through the Rooms?

The desired result would look like this:

Student Gender  Cat Room ------------------------- Anna    F       a   101  Paul    M       b   101 Sara    F       c   102 Mark    M       d   102 Ella    F       a   101 Aaron   M       b   101 Gina    F       c   102 Daniel  M       d   102