function suspect = counterfeit_detection_combinatorial ( logn, coin, correct )

%*****************************************************************************80
%
%% counterfeit_detection_combinatorial detects a counterfeit coin.
%
%  Discussion:
%
%    N = 2^(logn) - 1 coins are given.  All but one have the correct weight.
%    Identify the fake coin in logn weighings.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    10 March 2019
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Kurt Bryan, Tanya Leise,
%    Making do with less: an introduction to compressed sensing,
%    SIAM Review,
%    Volume 55, Number 3, September 2013, pages 547-566.
%
%  Parameters:
%
%    Input, integer logn, the number of coins is 2^logn - 1.
%
%    Input, real coin(2^logn-1), the weights of the coins.
%
%    Input, real correct, the correct weight of a single coin.
%
%    Output, integer suspect, the index of the suspected counterfeit coin.
%
  n = 2 ^ logn - 1;
%
%  The PHI matrix encodes the binary representations of 1 through n.
%  For n = 7:
%
%    1 0 1 0 1 0 1
%    0 1 1 0 0 1 1
%    0 0 0 1 1 1 1
%
%  We compute column J of the PHI matrix, and multiply by COIN(J),
%  and add that to W.  W = PHI * COIN.
%
  w = zeros ( logn, 1 );
  phi = zeros ( logn, 1 );
  for j = 1 : n
    for i = 1 : logn
      if ( phi(i) == 0 )
        phi(i) = 1;
        break
      end
      phi(i) = 0;
    end

    w = w + phi(1:logn) * coin(j);
  end
%
%  The suspected coin is found because the incorrect entries in W
%  form the binary representation of the index.
%
  suspect = 0;
  good = correct * 2 ^ ( logn - 1 );
  factor = 1;
  for i = 1 : logn
    if ( w(i) ~= good )
      suspect = suspect + factor;
    end
    factor = factor * 2;
  end

  return
end

