I have to sort an array objects (all of the same class); each object as a type property which always stores 1 of 5 possible integer values (call them 1-5 for the sake of convenience). In this strange use-case, the objects must be randomly ordered within the array with the single condition that no two objects, in sequence, can share the same type value.
ie. If the array were:
$objects = [$t_1, $t_1, $t_2, $t_2]
where $t_1 indicates an object whose type property is 1
Then the following order is fine:
$objects = [$t_1, $t_2, $t_1, $t_2]
But the initial state is not.
I'm currently doing something like this (the verbatim code is too confusingly in situ to post, but this is identical, logically, to what I've currently written):
$unsorted = $array_of_objects
$sorted = [];
while ( count( $unsorted ) ) {
// randomly select a remaining unsorted object
$next_index = array_rand( $unsorted );
$next_obj = $unsorted[ $next_index ];
// as long as the current object's type property doesn't match the type property of the preceding obj, add it to $sorted
if ( !count( $sorted ) or ( $next_obj->type != $sorted[ -1 ]->type ) ) {
array_push( $sorted, $next_obj );
unset( $unsorted[ $next_index ] );
}
}
But I have the intuition that this inefficient, and of course it has problem of running forever if there is no sorting solution.
Looking for advice on how to do this better and/or more robustly.