It would require a funky group-sort algorithm. Something that groups your items into 3’s ( a 3, a 2 and a 1, or three 1’s ), and then randomizes those groups.
If you want to automate the layout, you might try a masonry solution instead. The JS there often has features that attempt a “best fit” for the layout space.
Try macy.js-