function car ( trial_num, n )

%*****************************************************************************80
%
%% car() estimates probability I am my nearest neighbor's nearest neighbor.
%
%  Discussion:
%
%    Park N cars in a line, and compute each car's nearest neighbor.
%
%    Estimate the probability that a given car is the nearest neighbor
%    of its nearest neighbor.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    23 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Digital Dice: Computational Solutions to Practical Probability Problems,
%    Princeton, 2008,
%    ISBN: 978-0-691-15821-1.
%
%  Input:
%
%    integer trial_num: the number of trials.
%
%    integer N, the number of cars.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'car():\n' );
  fprintf ( 1, '  Park %d cars in a line, and compute each car''s nearest neighbor\n', n );
  fprintf ( 1, '  Estimate the probability that a given car is the nearest neighbor\n' );
  fprintf ( 1, '  of its nearest neighbor.\n' );

  total_mn = 0;

  for loop = 1 : trial_num

    for k = 1 : n
      pos(k) = rand ( );
    end
%
%  Sort.
%
    check = 1;
    while ( check == 1 )
      check = 0;
      i = 1;
      while ( i < n )
        if ( pos(i) < pos(i+1) )
          temp = pos(i+1);
          pos(i+1) = pos(i);
          pos(i) = temp;
          check = 1;
        end
        i = i + 1;
      end
    end
%
%  Find nearest neighbor.
%
    nn(1) = 2;
    nn(n) = n - 1;
    for j = 2 : n - 1
      if ( pos(j) - pos(j-1) < pos(j+1) - pos(j) )
        nn(j) = j - 1;
      else
        nn(j) = j + 1;
      end
    end

    mn = 0;
    if ( nn(2) == 1 )
      mn = mn + 1;
    end

    j = 2;
    while ( j < n )
      if ( nn(j) == j + 1 && nn(j+1) == j )
        mn = mn + 1;
        j = j + 2;
      else
        j = j + 1;
      end
    end
    total_mn = total_mn + mn;
  end

  total_mn = 2 * total_mn / n / trial_num;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Estimated probability = %g\n', total_mn );
  fprintf ( 1, '  Theoretical probability is %g\n', 2/3 );

  return
end
