/* Copyright (c) 1997-2004
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
   http://www.math.tu-berlin.de/polymake,  mailto:polymake@math.tu-berlin.de

   This program is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version: http://www.gnu.org/licenses/gpl.txt.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
*/

#ident "$Project: polymake $$Id: rand01.cc,v 1.22 2005/08/09 14:39:37 witte Exp $"

#include <cstdlib>
#include <ctime>
#include <argv_options.h>
#include <Poly.h>
#include <Rational.h>
#include <Matrix.h>
#include <random_generators.h>
#include <ext/hash_set>

namespace {
   enum { seed };
}

namespace polymake { namespace polytope {

void rand01(Poly& p, int d, int n, const argv_option *options)
{
   time_t t;
   const long s=options[seed] ? atol(options[seed]) : (time(&t), t);
   // initialize random rumber generator
   UniformRNG<Bitset> random(d, s);

   p.take("AMBIENT_DIM") << d;
   p.take("N_VERTICES") << n;

   std_ext::hash_set<Bitset> bitvectors(n);

   while (bitvectors.size() < (size_t)n)
      bitvectors.insert(random.get());

   Matrix<Rational> V(n,d+1);
   std_ext::hash_set<Bitset>::iterator bv=bitvectors.begin();
   for (Entire< Rows< Matrix<Rational> > >::iterator v=entire(rows(V)); !v.at_end(); ++v, ++bv)
      *v = 1 | same_element_sparse_vector<int>(*bv,d);
      
   p.take("VERTICES") << "# rand01: seed="  << '\n' << V ;
}

} }

using namespace polymake;

/** @file rand01
 *
 *  Produce a $d$-dimensional $0/1$-polytope with $n$ random vertices.
 *  Uniform distribution.
 *
 *  @synopsis rand01 <file> <d> <n> [ -seed <s> ]
 *
 *  @writing  AMBIENT_DIM, VERTICES, N_VERTICES
 *
 *  @index clients Producing from scratch
 */

int main(int argc, const char *argv[])
{
   argv_option options[]={ { "-seed", true } };
   if (!extract_options(argc,argv,3,options) || argc!=4) {
      cerr << "usage: " << argv[0] << " <file> <dimension> <#vertices> [ -seed <s> ]" << endl;
      return 1;
   }
   try {
      const int d=atoi(argv[2]),   // dimension
	        n=atoi(argv[3]);   // vertices

      // there is a certain restriction on the parameters
      if (d<2 || n<=d || ((n-1)>>(d))>=1) {
	 cerr << argv[0] << ": 2 <= dim < #vertices <= 2^dim" << endl;
	 return 1;
      }

      Poly p(argv[1], ios::out | ios::trunc);
      polytope::rand01(p, d, n, options);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
