In this paper, we proposed a useful algorithm to optimize the shape of asymmetric resonant cavities (ARCs). At first, we studied the repeatability and accuracy of the ray simulation on one kind of ARCs (half-quadrupole-half-circle shaped cavity), and confirmed the robustness of the directionality under shape errors. Based on these, we proposed a hill-climbing algorithm to optimize the ARCs for unidirectional emission. Different evaluation functions of directionality were tested and we suggested using the function of energy contained in a certain angle for highly collimated and unidirectional emission. By this method, we optimized the ARCs to obtain about 0.46 of the total radiated energy in divergence angle of 40° in the far field. This optimization method is very powerful for the shape engineering of ARCs and could be applied in future studies of ARCs with specific emission properties.