How are you placing or generating your box positions in the first place?
It would be most straightforward in a 1d array. You can increment the index in a loop until you run into an empty cell, or 0. Subtract 1 from that index and you'll have the position of the last number in a given set, which you can then swap with whatever you started with. The same loop can continue iterating through the entire array to swap every set of numbers it finds.