Example #1
0
File: main.cpp Project: CCJY/coliru
// generate uniformly distributed, unique, random numbers with the rng
std::vector<int> generate_unique( std::mt19937& rng, std::size_t n, int minv, int maxv )
{
    std::uniform_int_distribution<int> distr( minv, maxv ) ;
    std::set<int> set ;
    while( set.size() < n ) set.insert( distr(rng) ) ;
    return { set.begin(), set.end() } ;
}
Example #2
0
Shape Shape::RotateShape(LBF_DATA angleRange)
{
	Shape dstShape;

	if (m_Shape.size() < 1)
		return dstShape;

	dstShape.resize(m_Shape.size());

	std::random_device randDev;
	std::mt19937 generator(randDev());
	std::uniform_real_distribution<LBF_DATA> distr(0, 1);

	LBF_DATA rotAngle = 2 * angleRange * distr(generator) - angleRange;
	LBF_POINT rotCenter = GetMeanPoint();
	LBF_DATA sinT = std::sin(rotAngle * PI / 180);
	LBF_DATA cosT = std::cos(rotAngle * PI / 180);
	for (int i = 0; i < m_Shape.size(); i++)
	{
		dstShape.m_Shape[i].x = rotCenter.x + cosT*(m_Shape[i].x - rotCenter.x) - sinT*(m_Shape[i].y - rotCenter.y);
		dstShape.m_Shape[i].y = rotCenter.y + sinT*(m_Shape[i].x - rotCenter.x) + cosT*(m_Shape[i].y - rotCenter.y);
	}

	return dstShape;
}
Example #3
0
static CString RandomFromSet(const SCString& sSet,
                             std::default_random_engine& gen) {
    std::uniform_int_distribution<> distr(0, sSet.size() - 1);
    auto it = sSet.cbegin();
    std::advance(it, distr(gen));
    return *it;
}
void SimulateNextBlock(CBlockIndex*& tip, double* hashRates)
{
    double recTime = 1e9;
    CBlockIndex* newTip = new CBlockIndex;
    newTip->pprev = tip;
    newTip->nHeight = tip->nHeight+1;
    for (int i=0; i<NUM_ALGOS; i++)
    {
        if (hashRates[i] == 0) continue;
        CBigNum target;
        unsigned int nBits = GetNextWorkRequired(tip, NULL, i);
        target.SetCompact(nBits);
        double dtarget = target.getuint256().getdouble()/pow(2,256);
        double mean = 1/(hashRates[i]*dtarget);
        boost::exponential_distribution<double> distr(1/mean);
        double received = distr(prng);
        if (received < recTime)
        {
            recTime = received;
            newTip->nVersion = VersionForAlgo(i);
            newTip->nTime = tip->nTime + received;
            newTip->nBits=nBits;
        }
    }
    assert(recTime < 1e9);
    tip = newTip;
    return;
}
////////////////////////////////////////////////////////////////
// reference: https://msdn.microsoft.com/en-us/library/bb982914.aspx
static void test(const double l, const int s)
{
	// uncomment to use a non-deterministic generator
	//    std::random_device gen;
	std::mt19937 gen(1701);

	std::exponential_distribution<> distr(l);

	std::cout << std::endl;
	std::cout << "min() == " << distr.min() << std::endl;
	std::cout << "max() == " << distr.max() << std::endl;
	std::cout << "lambda() == " << std::fixed << std::setw(11) << std::setprecision(10) << distr.lambda() << std::endl;

	// generate the distribution as a histogram  
	std::map<double, int> histogram;
	for (int i = 0; i < s; ++i) {
		++histogram[distr(gen)];
	}

	// print results  
	std::cout << "Distribution for " << s << " samples:" << std::endl;
	int counter = 0;
	for (const auto& elem : histogram) {
		std::cout << std::fixed << std::setw(11) << ++counter << ": "
			<< std::setw(14) << std::setprecision(10) << elem.first << std::endl;
	}
	std::cout << std::endl;
}
int Math::random(int max)
{
	auto seed = static_cast<unsigned long>(std::time(nullptr));
	auto engine = std::default_random_engine(seed);
	std::uniform_int_distribution<> distr(0, max - 1);
	return distr(engine);
}
Example #7
0
int main() {
   MemoryManager heaper(50);
   std::cout << "Heap initialized" << std::endl;
   heaper.showBlockList();

   std::vector<unsigned char *> chunks;

   std::default_random_engine gen(time(0));
   std::uniform_int_distribution<unsigned int> distr(0, 20);
   for (int i=0; i<10; ++i) {
       unsigned int size = distr(gen);
       std::cout << "Requesting memory size " << size << "...";
       unsigned char *p = heaper.malloc(size);

       if (p)
           chunks.push_back(p);
       else
           std::cout << " FAILED";

       std::cout << std::endl;
       heaper.showBlockList();
   }

   while (auto still_allocated = chunks.size()) {
       auto choice = std::uniform_int_distribution<std::vector<unsigned char *>::size_type>(0, still_allocated-1)(gen);
       std::cout << "Freeing " << (void *) chunks[choice] << std::endl;
       heaper.free(chunks[choice]);
       chunks.erase(chunks.begin() + choice);
       heaper.showBlockList();
   }

   return 0;
}
Example #8
0
	virtual void RandomizeParameters()
	{
		std::uniform_real_distribution< float > distr( (float)1e-10, (float)1e10 ); // интервал равномерного распределения радиуса круга
		m_radius = distr( m_generator );

		m_center.RandomizeParameters();
	}
//Fill a vector with random numbers in the range [lower, upper]
void randomFill( std::vector<long int> &V, const long int lower, const long int upper, const unsigned int seed) {

    //use the default random engine and an uniform distribution
    std::default_random_engine eng(seed);
    std::uniform_real_distribution<long double> distr(lower, upper);

    for( auto &elem : V){
        elem = distr(eng);
    }
}
int randomRange(int min, int max)
{
	std::random_device rd; // obtain a random number from hardware
	std::mt19937 gen(rd()); // seed the generator
	std::uniform_int_distribution<int> distr(min, max); // define the range

	int random = distr(gen);

	return random;
}
Example #11
0
vector<char> genRandomString(size_t len)
{
	std::random_device rd;
	std::mt19937 gen(rd());
	std::uniform_int_distribution<unsigned long> distr(0, alphanumlen - 1);
	vector<char> strvec;
	for (size_t i = 0; i < len; ++i)
		strvec.push_back(alphanum[distr(gen)]);
	return strvec;
}
Example #12
0
string random_sequence(size_t length) {
    static const string alphabet = "ACGT";
    uniform_int_distribution<char> distr(0, 3);
    
    string seq(length, '\0');
    for (size_t i = 0; i < length; i++) {
        seq[i] = alphabet[distr(random_sequence_gen)];
    }
    return seq;
}
void sortR(int v[], int l, int r){
    if(r <= l) return;
    uniform_int_distribution<> distr(l, r-1);
    int temp = distr(eng);
    swap(v[temp], v[r]);
    //printf("%d %d %d\n", temp, l, r);
    int mid = partitionR(v, l, r);
    sortR(v, l, mid - 1);
    sortR(v, mid + 1, r);
}
Example #14
0
void Engine::InitializeEnemyShip()
{
	const int range_from = 0;
	const int range_to = WINDOW_SIZE.x;
	std::random_device rand_dev;
	std::mt19937 generator(rand_dev());
	std::uniform_int_distribution<int> distr(range_from, range_to);

	EnemyShip* enemy = new EnemyShip();
	enemy->SetPosition(sf::Vector2f(distr(generator), -30.f));

	enemyShips.push_back(enemy);
}
int main(int argc, char* argv[]) {
    int n;
    double a, b;
    size_t seed;
    std::tie(n, a, b, seed) = get_options(argc, argv);

    std::mt19937 engine(seed);
    std::uniform_real_distribution<double> distr(a, b);
    for (int i = 0; i < n; ++i)
        std::cout << distr(engine) << std::endl;

    return 0;
}
std::vector<double> generateYs (const std::vector<double>& xs, double a, double b, double variance)
{
	std::random_device generator;
	std::normal_distribution<> distr (0, variance);

	std::vector<double> result;
	result.reserve (xs.size ());

	for (auto x : xs)
		result.push_back (a + b * x + (variance ? distr (generator) : 0.0));

	return result;
}
std::vector<double> generateXs (double from, double to, size_t samples)
{
	std::random_device generator;
	std::uniform_real_distribution<> distr (from, to);

	std::vector<double> result;
	result.reserve (samples);

	for (size_t i = 0; i < samples; ++i)
		result.push_back (distr (generator));

	return result;
}
  void RandomIntProducer::execute()
  {
    //std::random_device                  rand_dev;
    std::mt19937                        generator(0); //TODO(johl): currently using 0 as seed (instead of rand_dev) for reproducable results. This should be adjustable.
    std::uniform_int_distribution<int>  distr(m_min, m_max);

    for (unsigned i = 0; i < m_num; ++i)
    {
      int value = distr(generator);
      TEETIME_TRACE() << "random value produced: " << value;
      AbstractProducerStage<int>::getOutputPort().send(std::move(value));
    }

    AbstractProducerStage<int>::terminate();
  }
Example #19
0
Server::Server(uint16 port, const char *worldId) {
	save = std::unique_ptr<Save>(new Save(worldId));
	boost::filesystem::path path(save->getPath());
	if (!boost::filesystem::exists(path)) {
		boost::filesystem::create_directories(path);
		std::random_device rng;
		boost::random::uniform_int_distribution<uint64> distr;
		uint64 seed = distr(rng);
		save->initialize(worldId, seed);
		save->store();
	}

	ServerChunkManager *cm = new ServerChunkManager(save->getWorldGenerator(), save->getChunkArchive());
	chunkManager = std::unique_ptr<ServerChunkManager>(cm);
	world = std::unique_ptr<World>(new World(chunkManager.get()));

	LOG_INFO(logger) << "Creating server";

	gameServer = std::unique_ptr<GameServer>(new GameServer(this));
	chunkServer = std::unique_ptr<ChunkServer>(new ChunkServer(this));

	if (enet_initialize() != 0)
		LOG_FATAL(logger) << "An error occurred while initializing ENet.";

	ENetAddress address;
	address.host = ENET_HOST_ANY;
	address.port = port;
	host = enet_host_create(&address, MAX_CLIENTS, NUM_CHANNELS, 0, 0);
	if (!host)
		LOG_FATAL(logger) << "An error occurred while trying to create an ENet server host.";
}
Example #20
0
	RoughConductor(const Properties &props) : BSDF(props) {
		ref<FileResolver> fResolver = Thread::getThread()->getFileResolver();

		m_specularReflectance = new ConstantSpectrumTexture(
			props.getSpectrum("specularReflectance", Spectrum(1.0f)));

		std::string materialName = props.getString("material", "Cu");

		Spectrum intEta, intK;
		if (boost::to_lower_copy(materialName) == "none") {
			intEta = Spectrum(0.0f);
			intK = Spectrum(1.0f);
		} else {
			intEta.fromContinuousSpectrum(InterpolatedSpectrum(
				fResolver->resolve("data/ior/" + materialName + ".eta.spd")));
			intK.fromContinuousSpectrum(InterpolatedSpectrum(
				fResolver->resolve("data/ior/" + materialName + ".k.spd")));
		}

		Float extEta = lookupIOR(props, "extEta", "air");

		m_eta = props.getSpectrum("eta", intEta) / extEta;
		m_k   = props.getSpectrum("k", intK) / extEta;

		MicrofacetDistribution distr(props);
		m_type = distr.getType();
		m_sampleVisible = distr.getSampleVisible();

		m_alphaU = new ConstantFloatTexture(distr.getAlphaU());
		if (distr.getAlphaU() == distr.getAlphaV())
			m_alphaV = m_alphaU;
		else
			m_alphaV = new ConstantFloatTexture(distr.getAlphaV());
	}
Example #21
0
	Float pdf(const BSDFSamplingRecord &bRec, EMeasure measure) const {
		if (measure != ESolidAngle ||
			Frame::cosTheta(bRec.wi) < 0 ||
			Frame::cosTheta(bRec.wo) < 0 ||
			((bRec.component != -1 && bRec.component != 0) ||
			!(bRec.typeMask & EGlossyReflection)))
			return 0.0f;

		/* Calculate the reflection half-vector */
		Vector H = normalize(bRec.wo+bRec.wi);

		/* Construct the microfacet distribution matching the
		   roughness values at the current surface position. */
		MicrofacetDistribution distr(
			m_type,
			m_alphaU->eval(bRec.its).average(),
			m_alphaV->eval(bRec.its).average(),
			m_sampleVisible
		);

		if (m_sampleVisible)
			return distr.eval(H) * distr.smithG1(bRec.wi, H)
				/ (4.0f * Frame::cosTheta(bRec.wi));
		else
			return distr.pdf(bRec.wi, H) / (4 * absDot(bRec.wo, H));
	}
Example #22
0
int main()
{
    // Шаги по заданию 2.
    // 1. Создание вектора.
    std::vector<int> v1(100);

    // 2. Заполение вектора псевдослучайными значениями.
    std::default_random_engine gen;
    std::uniform_int_distribution<int> distr(1, 1000);
    std::generate(v1.begin(), v1.end(), std::bind(distr, gen));

    // 3. Вывод вектора.
    std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " "));

    // 4. Сортировка вектора.
    std::sort(v1.begin(), v1.end());

    // 5. Копирование простых числе из одного вектора в другой.
    std::vector<int> v2;
    prime::copyPrimeNumbers(v1, v2);

    // 6. Удаление простых числе из вектора.
    prime::removePrimeNumbers(v1);

    return 0;
}
Example #23
0
 void test()
 {
    util::uniform_random_real<double, std::random_device> distr(-10.0, 10.0);
    std::array<double, 4> seg1;
    std::array<double, 4> seg2;
    for (size_t k = 0; k < 2500; ++k)
    {
       for (size_t i = 0; i < seg1.size(); ++i)
       {
          seg1[i] = distr();
          seg2[i] = distr();
       }
       auto cgal_res = CGAL::intersection(CGAL::Segment_2<CGAL::Exact_predicates_exact_constructions_kernel>
                                              (CGAL::Point_2<CGAL::Exact_predicates_exact_constructions_kernel>(seg1[0], seg1[1]),
                                              CGAL::Point_2<CGAL::Exact_predicates_exact_constructions_kernel>(seg1[2], seg1[3])),
                                          CGAL::Segment_2<CGAL::Exact_predicates_exact_constructions_kernel>
                                              (CGAL::Point_2<CGAL::Exact_predicates_exact_constructions_kernel>(seg2[0], seg2[1]),
                                              CGAL::Point_2<CGAL::Exact_predicates_exact_constructions_kernel>(seg2[2], seg2[3])));
       auto res = cg::intersection(cg::segment_2(cg::point_2(seg1[0], seg1[1]), cg::point_2(seg1[2], seg1[3])),
                                   cg::segment_2(cg::point_2(seg2[0], seg2[1]), cg::point_2(seg2[2], seg2[3])),
                                   -300);
       visitor_t visitor;
       if (const CGAL::Point_2<CGAL::Exact_predicates_exact_constructions_kernel> *ipoint =
           CGAL::object_cast<CGAL::Point_2<CGAL::Exact_predicates_exact_constructions_kernel>>(&cgal_res))
       {
          visitor.numbers.push_back(CGAL::to_double((*ipoint).x()));
          visitor.numbers.push_back(CGAL::to_double((*ipoint).y()));
          res.apply_visitor(visitor);
       }
       else
       {
          if (const CGAL::Segment_2<CGAL::Exact_predicates_exact_constructions_kernel> *iseg =
              CGAL::object_cast<CGAL::Segment_2<CGAL::Exact_predicates_exact_constructions_kernel>>(&cgal_res))
          {
             visitor.numbers.push_back(CGAL::to_double((*iseg)[0].x()));
             visitor.numbers.push_back(CGAL::to_double((*iseg)[0].y()));
             visitor.numbers.push_back(CGAL::to_double((*iseg)[1].x()));
             visitor.numbers.push_back(CGAL::to_double((*iseg)[1].y()));
             res.apply_visitor(visitor);
          }
          else
          {
             res.apply_visitor(visitor);
          }
       }
    }
 }
Example #24
0
void RandomHits( std::vector < int > & hits){
  hits.clear(); // O vector é limpo para previnir que não armazene mais de 20 elementos
  int RandomNum;
  std::random_device r;
  std::default_random_engine eng(r());
  std::uniform_real_distribution<double> distr(1, 80); // Gerando números dentro da faixa de hits possíveis do Keno

  for(int i = 0; i < 20;){
    RandomNum = distr(eng);
    if(std::binary_search(hits.begin(), hits.end(), RandomNum)){
      continue;
    }else{
      hits.push_back(RandomNum);
      i++;
    }
  }
}
Example #25
0
/**
 * Disribute measurements
 * @param measurements a vector containing all measurements
 */
void gridpack::state_estimation::SEFactory::setMeasurements(
    std::vector<gridpack::state_estimation::Measurement> measurements)
{
  int me = p_network->communicator().rank();
  int size = measurements.size();
  std::vector<int> bus_keys;
  std::vector<int> branch_ids;
  std::vector<std::pair<int,int> > branch_keys;
  std::vector<gridpack::state_estimation::Measurement> bus_meas;
  std::vector<gridpack::state_estimation::Measurement> branch_meas;
  int i, idx1, idx2;
  std::pair<int,int> key;
  for (i=0; i<size; i++) {
    std::string meas_type = measurements[i].p_type;
    if (meas_type == "VM" || meas_type == "PI" ||
        meas_type == "PJ" || meas_type == "QI" ||
        meas_type == "QJ" || meas_type == "VA") {
      bus_meas.push_back(measurements[i]);
      bus_keys.push_back(measurements[i].p_busid);
    } else if (meas_type == "PIJ" || meas_type == "PJI" ||
        meas_type == "QIJ" || meas_type == "QJI" ||
        meas_type == "IIJ" || meas_type == "IJI") {
      branch_meas.push_back(measurements[i]);
      idx1 = measurements[i].p_fbusid;
      idx2 = measurements[i].p_tbusid;
      key = std::pair<int,int>(idx1,idx2);
      branch_keys.push_back(key);
    }
  }
  gridpack::hash_distr::HashDistribution<SENetwork,Measurement,Measurement>
    distr(p_network);
  distr.distributeBusValues(bus_keys,bus_meas);
  int nsize = bus_keys.size();
  for (i=0; i<nsize; i++) {
    p_network->getBus(bus_keys[i])->addMeasurement(bus_meas[i]);
  }
  bus_keys.clear();
  bus_meas.clear();
  distr.distributeBranchValues(branch_keys,branch_ids,branch_meas);
  branch_keys.clear();
  nsize = branch_ids.size();
  for (i=0; i<nsize; i++) {
    p_network->getBranch(branch_ids[i])->addMeasurement(branch_meas[i]);
  }
  branch_ids.clear();
  branch_meas.clear();
  nsize = p_network->numBuses();
  // Sort measurements on each bus and branch so that they are in a consistent
  // order on all components
  for (i=0; i<nsize; i++) {
    p_network->getBus(i)->sortMeasurements();
  }
  nsize = p_network->numBranches();
  for (i=0; i<nsize; i++) {
    p_network->getBranch(i)->sortMeasurements();
  }
}
Example #26
0
void rnd_fill(std::vector<T> &V, const T lower, const T upper, const T seed)
{
    // use the default random engine and an uniform distribution
    std::mt19937 eng(static_cast<unsigned int>(seed));
    std::uniform_real_distribution<double> distr{double(lower), double(upper)};

    for (auto &elem : V) {
        elem = static_cast<T>(distr(eng));
    }
}
Example #27
0
TEST(orientation, uniform_line)
{
   boost::random::mt19937 gen;
   boost::random::uniform_real_distribution<> distr(-(1LL << 53), (1LL << 53));

   std::vector<cg::point_2> pts = uniform_points(1000);
   for (size_t l = 0, ln = 1; ln < pts.size(); l = ln++)
   {
      cg::point_2 a = pts[l];
      cg::point_2 b = pts[ln];

      for (size_t k = 0; k != 1000; ++k)
      {
         double t = distr(gen);
         cg::point_2 c = a + t * (b - a);

         EXPECT_EQ(cg::orientation(a, b, c), *cg::orientation_r()(a, b, c));
      }
   }
}
Example #28
0
	virtual void RandomizeParameters()
	{
		m_coords.Clear();

		std::uniform_int_distribution< int > distr( 1, 100 );
		int segment_count = distr( m_generator );
		Point p;

		p.RandomizeParameters();
		this->AddPoint( p );

		for( int i = 0; i < segment_count; ++i )
		{
			p.RandomizeParameters();

			while( p.m_x == ( *m_coords.End() ).m_x && p.m_y == ( *m_coords.End() ).m_y )
				p.RandomizeParameters();

			this->AddPoint( p );
		}
	}
Example #29
0
File: Room.cpp Project: xantoz/spel
void Room::update()
{
    static unsigned cntr = 0;

    // std::cerr << "Updating room " << getName() << std::endl;

    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::default_random_engine engine(seed);
    std::uniform_real_distribution<double> distr(0.0, 1.0);
    std::uniform_int_distribution<int> lvl(1,3);
	
    if (distr(engine) > 0.1)
        return;

    if (distr(engine) < encounters.dragon)
        this->addActor(new Dragon("dragon" + std::to_string(++cntr), lvl(engine)));
    
    if (distr(engine) < encounters.thief)
        this->addActor(new Thief("thief" + std::to_string(++cntr), lvl(engine)));
    
    if (distr(engine) < encounters.golem)
        this->addActor(new Golem("golem" + std::to_string(++cntr), lvl(engine)));
	
	if (distr(engine) < encounters.troll)
        this->addActor(new Troll("troll" + std::to_string(++cntr), lvl(engine)));
    
    
}
Example #30
0
void multipleFactoryTest(size_t times)
{
	std::random_device rd;
	std::mt19937 gen(rd());
	std::uniform_int_distribution<unsigned long> distr(5, 20);

	ofstream logfile("log.txt", ios::app);

	Logger::printPromptlyToStdOut();
	for (size_t i = 50; i < 50 + times; ++i)
	{
		Logger::log("Test with ID #" + to_string(i) + " is started.");

		testFactory(genRandomString(i), seconds(distr(gen)), seconds(distr(gen)), i);

		Logger::print(logfile);
		Logger::clear();
		cout << endl;
	}

	Logger::save("log.txt");
}