function walk ( trial_num, m )

%*****************************************************************************80
%
%% walk() simulates a walk from the corner of (M+1,M+1) to (1,1).
%
%  Discussion:
%
%    A pedestrian begins M blocks east and M blocks north of a destination.
%    At each intersection, there is a stop light which is set randomly,
%    and switches after 1 minute.
%    Until reaching avenue 1 or street 1, the pedestrian always crosses
%    the intersection in accordance with the stop light.
%    Thereafter, the pedestrian must wait at each stop light encountered.
%    What is the average wait for stop lights?
%
%  Example:
%
%      M       Time
%
%      2    0.74936
%      5    1.22906
%     10    1.75866
%     20    2.50673
%     50    3.99415
%    100    5.63352
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    26 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 M, the number of blocks east and north.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'walk():\n' );
  fprintf ( 1, '  A pedestrian begins M blocks east and M blocks north of a destination.\n' );
  fprintf ( 1, '  At each intersection, there is a stop light which is set randomly,\n' );
  fprintf ( 1, '  and switches after 1 minute.\n' );
  fprintf ( 1, '  Until reaching avenue 1 or street 1, the pedestrian always crosses\n' );
  fprintf ( 1, '  the intersection in accordance with the stop light.\n' );
  fprintf ( 1, '  Thereafter, the pedestrian must wait at each stop light encountered.\n' );
  fprintf ( 1, '  What is the average wait for stop lights?\n' );

  total_wait = 0;

  for loop = 1 : trial_num

    j = m + 1;
    k = m + 1;
    wait = 0;

    while ( j > 1 && k > 1 )
      if ( rand < 0.5 )
        j = j - 1;
      else
        k = k - 1;
      end
    end

    if ( j == 1 )
      z = k;
    else
      z = j;
    end

    while ( 1 < z )
      if ( rand ( ) < 0.5 )
        wait = wait + 1;
      end
      z = z - 1;
    end

    total_wait = total_wait + wait;

  end

  total_wait = total_wait / trial_num;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Estimated waiting time = %g\n', total_wait );

  return
end
