Under God's direction, Moses' army defeats the Midianites. They kill all the adult males, but take the women and children captive. When Moses learns that they left some live, he angrily says: "Have you saved all the women alive? Kill every male among the little ones, and kill every woman that hath known man by lying with him. But all the women children, that have not known a man by lying with him, keep alive for yourselves." So they went back and did as Moses (and presumably God) instructed, killing everyone except for the virgins. In this way they got 32,000 virgin. Numbers 31:1-54
25:6 And, behold, one of the children of Israel came and brought unto his brethren a Midianitish woman in the sight of Moses, and in the sight of all the congregation of the children of Israel, who were weeping before the door of the tabernacle of the congregation.
25:7 And when Phinehas, the son of Eleazar, the son of Aaron the priest, saw it, he rose up from among the congregation, and took a javelin in his hand;
25:8 And he went after the man of Israel into the tent, and thrust both of them through, the man of Israel, and the woman through her belly. So the plague was stayed from the children of Israel.
25:10 And the LORD spake unto Moses, saying,
25:11 Phinehas, the son of Eleazar, the son of Aaron the priest, hath turned my wrath away from the children of Israel, while he was zealous for my sake among them, that I consumed not the children of Israel in my jealousy.