Looks like I was too tired to think when I tried to solve it. It turned out pretty simple. (I won't spoil the code here in the comment.)