Mathematically / logically determine unit alignment for close combat
get the number of unit on the face being charged, see how many of the charging units front of base length fit in it then * that by the number of units being changed are open on that side.

if you have uneven formations you would need to keep the current shape of a unit in an object, then find all the lengths along the charged side and use some sort of packing algo to put the charging units along them