function [ a, more ] = vector_next_equivalent ( a )

%*****************************************************************************80
%
%% vector_next_equivalent() generates the next equivalent vector.
%
%  Discussion:
%
%    Two vectors are equivalent if one is simply a permuted copy of the 
%    other.  A vector may have no equivalents, or many.
%    This function produces the "next" equivalent vector, so it can
%    produce all the equivalent vectors one at a time.  To do so,
%    start with the vector whose entries are sorted in ascending order.
%
%    For example, here is for vectors of length d = 3, with digits 1, 2 or 3,
%    the possible sequences are:
%
%      #1  1 1 1 --> 1 1 1
%      #2  1 1 2 --> 1 1 2, 1 2 1, 2 1 1
%      #3  1 1 3 --> 1 1 3, 1 3 1, 3 1 1
%      #4  1 2 2 --> 1 2 2, 2 1 2, 2 2 1
%      #5  1 2 3 --> 1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2, 3 2 1
%      #6  1 3 3 --> 1 3 3, 3 1 3, 3 3 1
%      #7  2 2 2 --> 2 2 2
%      #8  2 2 3 --> 2 2 3, 2 3 2, 3 2 2
%      #9  2 3 3 --> 2 3 3, 3 2 3, 3 3 2
%     #10  3 3 3 --> 3 3 3
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    02 November 2022
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer a(d): a vector in the sequence.
%
%  Output:
%
%    integer a(d): the next equivalent vector.  But if the sequence is
%    exhausted, a is returned as [].
%
%    logical MORE: is TRUE if another vector was computed.
%    If MORE is FALSE on return, then ignore the output value A, and
%    stop calling the routine.
%
  more = true;

  n = length ( a );
%
%  Starting at the right, seek the highest index I for which A(I) < A(I+1).
%
  i = n - 1;

  while ( true )

    if ( i <= 0 )
      break
    end

    if ( a(i) < a(i+1) )
      break
    end

    i = i - 1;

  end
%
%  If no I could be found, then we have reach the final permutation,
%  N, N-1, ..., 2, 1.  Time to start over again.
%
  if ( i == 0 )
    a = [];
    more = false;
  else
%
%  Otherwise, let J be the greatest index after I such that A(I) < A(J).
%
    j = n;
    while ( a(j) <= a(i) ) 
      j = j - 1;
    end
%
%  Interchange elements I and J.
%
    t    = a(i);
    a(i) = a(j);
    a(j) = t;
%
%  Reverse the elements from I+1 to N.
%
    a(i+1:n) = a(n:-1:i+1);

  end

  return
end
