function kids ( trial_num, p )

%*****************************************************************************80
%
%% kids() simulates a family planning problem.
%
%  Discussion:
%
%    Simulate families that have children
%    until a child is born that is the same sex as the first
%    child, where p is the probability of a boy.
%
%  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.
%
%    real P, the probability that a child will be a boy.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'kids():\n' );
  fprintf ( 1, '  Simulate %d families that have children\n', trial_num );
  fprintf ( 1, '  until a child is born that is the same sex as the first\n' );
  fprintf ( 1, '  child, where p is the probability of a boy.\n' );

  total = 0;
  s = 0;

  for family = 1 : trial_num

    c = rand ( );
    s = s + 1;

    if ( c < p )
      first = 0;
    else
      first = 1;
    end

    while ( s > 0 )

      c = rand ( );
      s = s + 1;

      if ( c < p )
        if ( first == 0 )
          total = total + s;
          s = 0;
        end
      end

      if ( p < c )
        if ( first == 1 )
          total = total + s;
          s = 0;
        end
      end

    end

  end

  total = total / trial_num;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Average number of children in each family = %g\n',total );

  return
end

