If you didn’t realize you were doing something of grave matter at the time because you were half-asleep or something, than you did not commit a mortal sin. If you were fully awake, sane, sober and realized fully what it is you were doing (I’ve had brief fuzzy moments when my concupiscence had seemed to take over my brain and I’d start doing something of grave matter without ever even having registered that I was committing a sin at all) than you were committing a mortal sin and you should go to confession as soon as possible.
Also, pray for chastity, perhaps especially to the Virgin Mary and all the virgin maryters such as St. Philomena (her story is amazing and inspiring so you should look it up when you get the chance.) I will pray for you as well.
It is, of course, best to avoid all circumstances within reason that cause your hormones to overload. Also you may find it helpful to cut down on grains, vitamind B and or potassium; they are vital nutriants, but overdoing them overloads the sex hormones.
Also, if you are a woman, I would suggest the herb vitex (also known as chaste tree berry) preferably in liquid form (although that is the most expensive form.) If you’re a guy, you shouldn’t take vitex, especially not if you want to have children. Side effects are rare and generally not serious (for women.) This is an herb that people have been taking for thousands of years for various purposes (the most ancient reason being to remain chaste.) There is no guarantee it will work as everybody’s body works differently.
Of course, I understand the fact that having sexual urges is natural and that restraining them may not be the best way to go, but if all else seems to fail, it’s good to have a practical and natural resource to turn to.