Since the question was asked in the context of the Hebrew Bible I will point to the two books that address it: Ecclesiastes and Job. The answers given, however, are not likely to satisfy you. Human beings do not have the capacity to understand the will of God. There are things far greater than us in the world, and incomparably more so, is the greatness of the God who created it all.
The pious may accept this “answer” but what about the rest of us? Before dismissing it we need to ask a few more questions. Why should we assume that there is a rational answer? Why must the world conform to some human standard of goodness and justice? To put it somewhat differently, why assume that God must be part of an answer? Perhaps the problem is not with the answer but with the question.
To ask “why?” may be a demand for an answer, an explanation or justification, but it might, instead, have at its source wonder, awe, and astonishment. The latter sense is contemplative. It does not attempt to uncover something behind the given, it marvels at the given, that there is a given, that there is anything at all.
But such lofty contemplation may not be a satisfactory attitude for those who have been touched by suffering, by those who must fend for themselves, for those who live in the world. The message of Ecclesiastes is simple, yet profound:
There is nothing better for a man than that he should eat and drink, and make his soul enjoy pleasure for his labour. This also I saw, that it is from the hand of God. (2:24)
I know that there is nothing better for them, than to rejoice, and to get pleasure so long as they live. (3:12)
So I commended mirth, that a man hath no better thing under the sun, than to eat, and to drink, and to be merry, and that this should accompany him in his labour all the days of his life which God hath given him under the sun. (8:15)
Go thy way, eat thy bread with joy, And drink thy wine with a merry heart; For God hath already accepted thy works. (9:7)
In secular terms, things will happen as they will, enjoy what you can, for all is vanity. In the end, in death, according to Ecclesiastes, the fate of all - righteous and unrighteous, good and bad, just and unjust, is the same.