function spider ( trial_num )

%*****************************************************************************80
%
%% spider() simulates a spider's random walk on a 2D web.
%
%  Discussion:
%
%    A web consists of locations 1 through 9.
%    The web is connected, and each location is connected to some of the others.
%    A spider begins at location 1, and a fly is trapped at location 2.
%    By choosing random moves on the web, how long does it take
%    the spider to find the fly?
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    29 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Dueling Idiots and Other Probability Puzzlers,
%    Princeton, 2012,
%    ISBN: 978-0691155005.
%
%  Input:
%
%    integer trial_num: the number of trials.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'spider():\n' );
  fprintf ( 1, '  A web consists of locations 1 through 9.\n' );
  fprintf ( 1, '  The web is connected, and each location is connected to some of the others.\n' );
  fprintf ( 1, '  A spider begins at location 1, and a fly is trapped at location 2.\n' );
  fprintf ( 1, '  By choosing random moves on the web, how long does it take\n' );
  fprintf ( 1, '  the spider to find the fly?\n' );

  t1 = [3;0;3;1;2;2;3;4;2];
  t2 = [4;0;2;1;3;5;1;1;2];
  t3 = [7;0;5;0;6;7;6;3;8];
  t4 = [8;0;8;0;0;0;8;7;0];
  t5 = [0;0;0;0;0;0;0;9;0];

  web = [ t1 t2 t3 t4 t5 ];

  d = zeros(1,250);

  for walks = 1 : trial_num

    position = 1;
    steps = 0;
    while ( position ~= 2 )
      choices = web(position,1);
      choice = floor ( choices * rand ( ) ) + 2;
      position = web(position,choice);
      steps = steps + 1;
    end
    d(steps) = d(steps) + 1;
  end 

  average = 0;
  for i = 1 : 50
    average = average + i * d(i);
  end

  average = average / trial_num;
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Average number of steps to reach the fly = %g\n', average );
%
%  Graphics.
%
  clf ( );
  bar ( d );
  title ( 'Distribution of Walk Durations on the Web' );
  xlabel ( 'number of steps' );
  ylabel ( 'number of walks' );
  filename = 'spider.png';
  print ( '-dpng', filename );
  fprintf ( '  Graphics saved as "%s"\n', filename );

  return
end

