function kids ( p )

%*****************************************************************************80
%
%% KIDS simulates a family planning problem.
%
%  Discussion:
%
%    This m-file simulates 10,000 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.
%
%  Modified:
%
%    29 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Dueling Idiots and Other Probability Puzzlers,
%    Princeton, 2012,
%    ISBN: 978-0691155005.
%
%  Parameters:
%
%    Input, real P, the probability that a child will be a boy.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'KIDS\n' );
  fprintf ( 1, '  This m-file simulates 10,000 families that have children\n' );
  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 : 10000

    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 ( c > p )
        if ( first == 1 )
          total = total + s;
          s = 0;
        end
      end

    end

  end

  total = total / 10000;

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

  return
end

