Create an array to hold indices of non - empty piles
int non_zero_indices [ n ] , count ; for ( i = 0 , count = 0 ; i < n ; i ++ ) if ( piles [ i ] > 0 ) non_zero_indices [ count ++ ] = i ; ( * moves ) . pile_index = ( rand ( ) % ( count ) ) ; ( * moves ) . stones_removed = 1 + ( rand ( ) % ( piles [ ( * moves ) . pile_index ] ) ) ; piles [ ( * moves ) . pile_index ] = piles [ ( * moves ) . pile_index ] - ( * moves ) . stones_removed ; if ( piles [ ( * moves ) . pile_index ] < 0 ) piles [ ( * moves ) . pile_index ] = 0 ; } return ; }