function u = lollatz_sequence ( t, nmax )

%*****************************************************************************80
%
%% lollatz_sequence() computes a "Lollatz" sequence from a given starting value.
%
%  Discussion:
%
%    Let T be an entry in the input set.
%
%    If mod(T,3) == 0
%      U = 2*T/3
%    Else if mod(T,3) == 1
%      U = (4*T-1)/3
%    Else if mod(T,3) == 2
%      U = (4*T+1)/3
%
%    Note that this is actually the first transformation function that
%    Lothar Collatz is known to have considered, as recorded in his
%    notebook for 1 July 1932.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    15 June 2022
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer T: the starting value.
%
%    integer NMAX: the maximum length the sequence can go before being terminated.
%
%  Output:
%
%    integer U(N): the permuted values.
%
  for n = 1 : nmax

    if ( n == 1 )

      u = zeros ( 0, 1 );
      u(n) = t;

    else

      if ( mod ( t, 3 ) == 0 )
        t = 2 * t / 3;
      elseif ( mod ( t, 3 ) == 1 )
        t = ( 4 * t - 1 ) / 3;
      elseif ( mod ( t, 3 ) == 2 )
        t = ( 4 * t + 1 ) / 3;
      end

      u(n) = t;

      if ( any ( u(1:n-1) == t ) )
        break
      end

    end

  end

  return
end
