• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ RandInt函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中RandInt函数的典型用法代码示例。如果您正苦于以下问题:C++ RandInt函数的具体用法?C++ RandInt怎么用?C++ RandInt使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了RandInt函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: m_bSuccess

//-----------------------------ctor---------------------------------------
//
//------------------------------------------------------------------------
CController::CController(int cxClient,
                         int cyClient):
                                       m_bSuccess(false),                                  
                                       m_vPadPos(SVector2D(RandFloat()*cxClient, 50)),
                                       m_cxClient(cxClient),
                                       m_cyClient(cyClient)
                                       
{


  //create a starting postion for the landers
  SVector2D vStartPos = SVector2D(WINDOW_WIDTH/2, cyClient-50);

  //create the user controlled lander
  m_pUserLander = new CLander(cxClient, cyClient, PI, vStartPos, m_vPadPos);

  //set up the VB for the landing pad
  for (int i=0; i<NumPadVerts; ++i)
  {
    m_vecPadVB.push_back(Pad[i]);
  }

  //setup the stars
  for (int i=0; i<NumStars; ++i)
  {
    m_vecStarVB.push_back(SPoint(RandInt(0, cxClient), RandInt(100, cyClient)));
  }

}
开发者ID:aepedrive,项目名称:Mooning,代码行数:32,代码来源:CController.cpp


示例2: RandInt

dsr::Entity dsr::Entity::buildEntity(unsigned long int size, int cardinality) {

  dsr::Entity e;


  // If cardinality is -1 do random integers
  if (cardinality == -1) {
    for (unsigned i = 0; i < size; ++i) {
      e.add(RandInt());
    }
  }
  else {
    std::vector<unsigned> ms;
    // Create a block of mentions for each item in the cardinality
    // Evenly spread out the randoms for now
    unsigned block = size / cardinality; // (Assume size > cardinality)
    for (unsigned i = 0; i < cardinality; ++i) {
      auto m = RandInt();
      for (auto b = 0; b < block; ++b) {
        ms.push_back(m);
      }
    }

    std::random_shuffle(ms.begin(), ms.end());
    for(auto &m: ms) {
      e.add(m);
    }
  }

  return e;
}
开发者ID:cegme,项目名称:qdstreaming,代码行数:31,代码来源:Entity.cpp


示例3: RandInt

NEURAL_NETWORK *OPTIMIZER::Genome_Get_Random_But_Not(NEURAL_NETWORK *other) {

	// Return a random genome, but don't choose one that is equal
	// to genome `other'.

	int genomeIndex = RandInt(0,AFPO_POP_SIZE-1);
	int numberOfTries = 0;

	while (	(genomes[genomeIndex]==other) ||
		(genomes[genomeIndex]->fitness == 0.0) ||
		(genomes[genomeIndex]->fitness == other->fitness) ) {

		genomeIndex = RandInt(0,AFPO_POP_SIZE-1);

		numberOfTries++;

		// If no appropriate controller can be found,
		// return a random one.

		if ( numberOfTries >= 10000 )
			return( genomes[genomeIndex] );
	}

	return( genomes[genomeIndex] );
}
开发者ID:jbongard,项目名称:Ludobots,代码行数:25,代码来源:optimizer.cpp


示例4: main

int main()
{
    const unsigned int SAMPLE_NUM = 1000;

    // 定义训练输入矩阵和输出矩阵
    LPerceptronMatrix X(SAMPLE_NUM, 2);
    LPerceptronMatrix Y(SAMPLE_NUM, 1);
    for (unsigned int i = 0; i < SAMPLE_NUM; i++)
    {
        X[i][0] = (float)RandInt(-1000, 1000);
        X[i][1] = (float)RandInt(-1000, 1000);
        Y[i][0] = ((X[i][0] + X[i][1]) >= 0)? LPERCEPTRON_SUN : LPERCEPTRON_MOON;
    }

    LPerceptronProblem problem(X, Y);

    // 训练模型
    LPerceptron perceptron;
    perceptron.TrainModel(problem);

    // 使用测试样本测试
    LPerceptronMatrix testSample(1, 2);
    testSample[0][0] = -50.0f;
    testSample[0][1] = 0.0f;

    printf("Predict: %f\n", perceptron.Predict(testSample));

    system("pause");
    return 0;
}
开发者ID:BurnellLiu,项目名称:LiuProject,代码行数:30,代码来源:main.cpp


示例5: RandInt

xor::xor(void)
{
	fitness = 0;
	posX = RandInt(0, dimMapa/dimCasilla)*dimCasilla;
	posY = RandInt(0, dimMapa/dimCasilla)*dimCasilla;
	crearListaObjetos();
}
开发者ID:Pablo1990,项目名称:3DVideogameABPSlayers,代码行数:7,代码来源:xor.cpp


示例6: ChooseSection

//------------------------MutateSM--------------------------------
//
//	chooses a random start and point then scrambles the genes 
//	between them
//----------------------------------------------------------------
void CgaTSP::MutateSM(vector<int> &chromo)
{
	//return dependent upon mutation rate
	if (RandFloat() > m_dMutationRate) return;

	//first we choose a section of the chromosome
	const int MinSpanSize = 3;

	//these will hold the beginning and end points of the span
  int beg, end;

	ChooseSection(beg, end, chromo.size()-1, MinSpanSize);

	int span = end - beg;

	//now we just swap randomly chosen genes with the beg/end
	//range a few times to scramble them
	int NumberOfSwapsRqd = span;

	while(--NumberOfSwapsRqd)
	{
		vector<int>::iterator gene1 = chromo.begin();
		vector<int>::iterator gene2 = chromo.begin();

		//choose two loci within the range
		advance(gene1, beg + RandInt(0, span));
		advance(gene2, beg + RandInt(0, span));

		//exchange them
		swap(*gene1, *gene2);
		
	}//repeat
}
开发者ID:pxli168,项目名称:source,代码行数:38,代码来源:gaTSP.cpp


示例7: tournamentSelection

SGenome geneticselection::tournamentSelection(vector<SGenome> &m_vecPop, double m_totalfitness){
	

	
	
	//Retrieve the size of the population
	int m_vecSize = m_vecPop.size();

	//Randomly select the initial best value
	//REASON: makes selecting every other part of the set easier
	SGenome best = m_vecPop[RandInt(0,m_vecSize-1)];

	//Holder for future individuals in the tournament
	SGenome ind;
	//Run a tournament utilizing 1 to n members of the population
	for (int i = 0; i < CParams::dTournamentNumber - 1; ++i){

		//Randomly select a member of the population
		ind = m_vecPop[RandInt(0, m_vecSize-1)];

		if (ind.dFitness > best.dFitness){
			//The new individual is better than the initial individual
			best = ind;
		}

	}

	//Tournament has run it's course
	//return the best option selected
	return best;
}
开发者ID:World93,项目名称:NeuroNetwork,代码行数:31,代码来源:geneticselection.cpp


示例8: RandInt

/**
*   Função contruída com o objetivo de facilitar o treinamento de uma rede. Utiliza critérios 
* de parada  pré-definidos. O objetivo é paralizar o treinamento a partir do momento em que o 
* erro médio quadrático da rede em relação às amostras para de  diminuir. Recebe um  parâmetro 
* indicando um número mínimo de treinos, a a partir do qual se inicia a verificação da variaçao
* do erro médio quadrático. Recebe também o número de treinamentos a ser executado até que uma
* nova medição  do erro seja feita. Caso a variância (porcentual) das últimas n  medições seja 
* menor ou igual a um determinado valor (entre 0 e 1), paraliza o treinamento.
*   A função recebe ainda um conjunto de amostras (matriz de entradas/matriz de saídas), número 
* de amostras contidas nas matrizes, a dimensão de cada amostra de entrada e de cada amostra de 
* saída e um flag indicando se as amostras devem ser treinadas aleatoriamente ou em ordem.
*/
int BKPNeuralNet::AutoTrain( float**inMatrix, float **outMatrix, int inSize, int outSize, int nSamples, 
              int minTrains, int varVectorSize, float minStdDev, int numTrains, TrainType type, 
              float l_rate, float momentum, int* retExecutedTrains )
{
  // Casos de retorno:
  if( (!inMatrix) || (!outMatrix) || (inSize!=_nLayers[0]) || (_nLayers[_layers-1]!=outSize) )
    return -1;

  // O número de treinamentos inicial tem que ser pelo menos 0:
  if( *retExecutedTrains < 0 )
    *retExecutedTrains = 0;

  int thisSample = -1;    //< Variável auxiliar, indica a amostra a ser treinada.
  // Executando os treinamentos obrigatórios:
  for( int i=0 ; i<minTrains ; i++ )
  {
    if( type == ORDERED_TRAIN )
      thisSample = (++thisSample)%nSamples;
    if( type == RANDOM_TRAIN )
      thisSample = RandInt(0, (nSamples-1));
    Train( inSize, inMatrix[thisSample], outSize, outMatrix[thisSample], l_rate, momentum );
  }

  // Executando os demais treinamentos:
  float* varVector = new float[varVectorSize];  //< Vetor para conter as últimas medições de erro.
  int ptVarVector = 0;              //< Aponta para a primeira posição vazia de varVector.
  float lastVariance = (float)MAX_VALUE;   //< Variâvel que mantém o valor da varirância.
  float StdDev = (float)MAX_VALUE;   //< Variâvel que mantém o valor do desvio-padrão. 
  thisSample = -1;
  int nTrains=minTrains + *retExecutedTrains;  //< Mantém o número de treinamentos executados.
  bool varFlag = false;
  while( StdDev > minStdDev )
  {
    if( type == ORDERED_TRAIN )
      thisSample = (++thisSample)%nSamples;
    if( type == RANDOM_TRAIN )
      thisSample = RandInt(0, (nSamples-1));
    Train( inSize, inMatrix[thisSample], outSize, outMatrix[thisSample], l_rate, momentum );
    if( (nTrains%numTrains) == 0 ) //< A cada numTrains treinamentos, testa o erro:
    {
      float retRMS_Error = 0;
      float mean = 0;
      RMS_error( inMatrix, outMatrix, inSize, outSize, nSamples, &retRMS_Error );
      varFlag = ShiftLeft( varVector, varVectorSize, retRMS_Error, ptVarVector );
      if( varFlag == true )
      {
        lastVariance = Variance( varVector, varVectorSize, &mean );
        StdDev = ((float)sqrt(lastVariance))/mean;
      }
      ptVarVector++;
    }
    nTrains++;
    if( nTrains >= 90000 )   //< O número máximo de treinamentos será 150000.
      StdDev = minStdDev;

  }
  *retExecutedTrains = nTrains;
  return 0;
}
开发者ID:supermalf,项目名称:SoccerFieldDetection,代码行数:71,代码来源:BKPNeuralNet.cpp


示例9: RandInt

void MATRIX::Perturb(double maxVal) {

	int i, j;
		
	i = RandInt(0,length-1);
	j = RandInt(0,width-1);

	Set(i,j,Rand(0.0,maxVal));
}
开发者ID:jbongard,项目名称:cords,代码行数:9,代码来源:matrix.cpp


示例10: CMinesweeper

//-----------------------------------constructor-------------------------
//
//-----------------------------------------------------------------------
CDiscMinesweeper::CDiscMinesweeper():
							 CMinesweeper(),
                             m_dRotation((ROTATION_DIRECTION)RandInt(0,3))
{
	//create a random start position
	
	m_vPosition = SVector2D<int>(RandInt(0,CParams::WindowWidth/CParams::iGridCellDim)*CParams::iGridCellDim, 
					             RandInt(0,CParams::WindowHeight/CParams::iGridCellDim)*CParams::iGridCellDim);
}
开发者ID:kidynamit,项目名称:MLBackProp,代码行数:12,代码来源:CDiscMinesweeper.cpp


示例11: RandColorRGBA

LLGL::ColorRGBAub RandColorRGBA()
{
    return LLGL::ColorRGBAub
    {
        static_cast<std::uint8_t>(RandInt(255)),
        static_cast<std::uint8_t>(RandInt(255)),
        static_cast<std::uint8_t>(RandInt(255)),
        static_cast<std::uint8_t>(RandInt(255))
    };
}
开发者ID:LukasBanana,项目名称:LLGL,代码行数:10,代码来源:Test_Performance.cpp


示例12: RandomSparseMatrix

 void RandomSparseMatrix(SparseMatrix& A,int nnz,Real range)
 {
   A.setZero();
   for(int k=0;k<nnz;k++) {
     int i=RandInt(A.m);
     int j=RandInt(A.n);
     Real x=Rand(-range,range);
     A.insertEntry(i,j,x);
   }
 }
开发者ID:HargisJ,项目名称:KrisLibrary,代码行数:10,代码来源:SelfTest.cpp


示例13: RandInt

void   NEURAL_NETWORK::Connection_Remove(int nodeIndex) {

	int i = RandInt(0,((NODES_PER_SENSOR*numSensors)+numNodes)-1);

	while ( weights->Get(i,nodeIndex) == 0 )

		i = RandInt(0,((NODES_PER_SENSOR*numSensors)+numNodes)-1);

	weights->Set(i,nodeIndex,0);
}
开发者ID:jbongard,项目名称:ISCS,代码行数:10,代码来源:neuralNetwork.cpp


示例14: RandInt

//-------------------------CrossoverPMX---------------------------------
//
// crossover operator based on 'partially matched crossover' as 
// defined in the text
//-------------------------------------------------------------------
void CgaTSP::CrossoverPMX(	const vector<int>	&mum, 
							              const vector<int>	&dad, 
							              vector<int>			&baby1, 
							              vector<int>			&baby2)
{
	baby1 = mum;
	baby2 = dad;
	
	//just return dependent on the crossover rate or if the
	//chromosomes are the same.
	if ( (RandFloat() > m_dCrossoverRate) || (mum == dad)) 
	{
		return;
	}

	//first we choose a section of the chromosome
	int beg = RandInt(0, mum.size()-2);
	
	int end = beg;
	
	//find an end
	while (end <= beg)
	{
		end = RandInt(0, mum.size()-1);
	}

	//now we iterate through the matched pairs of genes from beg
	//to end swapping the places in each child
	vector<int>::iterator posGene1, posGene2;

	for (int pos = beg; pos < end+1; ++pos)
	{
		//these are the genes we want to swap
		int gene1 = mum[pos];
		int gene2 = dad[pos];

		if (gene1 != gene2)
		{
			//find and swap them in baby1
			posGene1 = find(baby1.begin(), baby1.end(), gene1);
			posGene2 = find(baby1.begin(), baby1.end(), gene2);

			swap(*posGene1, *posGene2);

			//and in baby2
			posGene1 = find(baby2.begin(), baby2.end(), gene1);
			posGene2 = find(baby2.begin(), baby2.end(), gene2);
			
			swap(*posGene1, *posGene2);
		}
		
	}//next pair
}	
开发者ID:pxli168,项目名称:source,代码行数:58,代码来源:gaTSP.cpp


示例15: RandInt

//-------------------------------------------Reset()--------------------
//
//	Resets the sweepers position, MinesGathered and rotation
//
//----------------------------------------------------------------------
void CDiscMinesweeper::Reset()
{

	//reset the sweepers positions
	m_vPosition = SVector2D<int>(RandInt(0,CParams::WindowWidth/CParams::iGridCellDim)*CParams::iGridCellDim, 
					             RandInt(0,CParams::WindowHeight/CParams::iGridCellDim)*CParams::iGridCellDim);
	
	CMinesweeper::Reset();

	//and the rotation
	m_dRotation = (ROTATION_DIRECTION)RandInt(0,3);
	//m_dRotation = ROTATION_DIRECTION::SOUTH;
	return;
}
开发者ID:kidynamit,项目名称:MLBackProp,代码行数:19,代码来源:CDiscMinesweeper.cpp


示例16: while

void GameWorld::CreateObstacles()
{
	for (int o=0; o < AICON.NumObstacles; ++o)
	{
		bool bOverlapped = true;
	
		//keep creating tiddlywinks until we find one that doesn't overlap
		//any others.Sometimes this can get into an endless loop because the
		//obstacle has nowhere to fit. We test for this case and exit accordingly

		int NumTrys = 0; int NumAllowableTrys = 2000;

		while (bOverlapped)
		{
			NumTrys++;

			if (NumTrys > NumAllowableTrys) return;

			float scale = 0.1f;
			int radius = RandInt((int)AICON.MinObstacleRadius,  (int)AICON.MaxObstacleRadius);
			radius *= scale;
			const int border                 = 10 * scale;
			const int MinGapBetweenObstacles = 20 * scale;

			noVec3 pos(RandInt(radius+border, m_cxClient-radius-border), 0.0f,  RandInt(radius+border, m_cyClient-radius-30-border));
			WowActor* ob = new WowActor(modelname[0]);
			ob->SetID(g_database.GetNewObjectID());
			ob->SetType(0);
			
			ActorController* pACtrl = new ActorController( ob,
				this, pos, RandFloat() * noMath::TWO_PI, 
				vec3_zero, AICON.VehicleMass, AICON.MaxSteeringForce, AICON.MaxSpeed, AICON.MaxTurnRatePerSecond );
			
			pACtrl->SetBRadius(radius);
			ob->PushStateMachine(*pACtrl);
							

			if (!Overlapped(pACtrl, m_Obstacles, MinGapBetweenObstacles))
			{
				//its not overlapped so we can add it
				m_Obstacles.push_back(pACtrl);

				GameObjectManager::Get()->AddGameObject(ob);
				GetApp()->GetActorRoot()->AddChild(ob->GetNode());

				bOverlapped = false;
			}			
		}
	}
}
开发者ID:DanielNeander,项目名称:my-3d-engine,代码行数:50,代码来源:GameWorld.cpp


示例17: if

unsigned long int dsr::Entity::rand() {
  // TODO need a new method if it is in the large state
  if (state == EntityState::NORMAL) {
    auto r = mentions[RandInt() % mentions.size()];
    return r;
  }
  else if (state == EntityState::COMPRESSED) {
    unsigned long int b = RandInt() % stringmap.bucket_count();
    return stringmap.begin(b)->first;
  }
  else {
    throw "Unimplemented Random function"; //TODO
  }
}
开发者ID:cegme,项目名称:qdstreaming,代码行数:14,代码来源:Entity.cpp


示例18: RandInt

void EnumKare::Crossover(const vector<int> &mum,
	const vector<int> &dad,
	vector<int> &baby1,
	vector<int> &baby2)
{
	//由随机概率决定是否杂交,若两亲本相同也不杂交
	//不杂交则直接复制亲本
	if (RandFloat() > m_dCrossoverRate || mum == dad)
	{
		baby1 = dad;
		baby2 = mum;
		return;
	}
	int cp = RandInt(0, m_iChromoLength - 1);
	int i;
	for ( i = 0; i < cp; i++)
	{
		baby1.push_back(mum[i]);
		baby2.push_back(dad[i]);
	}
	for ( i = cp; i < mum.size(); i++)
	{
		baby1.push_back(dad[i]);
		baby2.push_back(mum[i]);
	}
}
开发者ID:knightjun,项目名称:GA_EightNum,代码行数:26,代码来源:EnumKare.cpp


示例19: RandInt

//----------------------------Crossover--------------------------------
//	Takes 2 parent vectors, selects a midpoint and then swaps the ends
//	of each genome creating 2 new genomes which are stored in baby1 and
//	baby2.
//---------------------------------------------------------------------
void Cga::Crossover( const vector<int> &mum,
						const vector<int> &dad,
						vector<int>		  &baby1,
						vector<int>		  &baby2)
{
	//just return parents as offspring dependent on the rate
	//or if parents are the same
	if ( (RandFloat() > m_dCrossoverRate) || (mum == dad)) 
	{
		baby1 = mum;
		baby2 = dad;

		return;
	}
	
	//determine a crossover point
	int cp = RandInt(0, m_iChromoLength - 1);

	//swap the bits
	for (int i=0; i<cp; ++i)
	{
		baby1.push_back(mum[i]);
		baby2.push_back(dad[i]);
	}

	for (i=cp; i<mum.size(); ++i)
	{
		baby1.push_back(dad[i]);
		baby2.push_back(mum[i]);
	}
}
开发者ID:rennhak,项目名称:Keyposes,代码行数:36,代码来源:Cga.cpp


示例20: TurnRoach

/*
   Turn a roach.
*/
void
TurnRoach(Roach *roach)
{
    if (roach->index != (roach->rp - roachPix)) return;

    if (roach->turnLeft) {
	roach->index += (RandInt(30) / 10) + 1;
	if (roach->index >= ROACH_HEADINGS)
	    roach->index -= ROACH_HEADINGS;
    }
    else {
	roach->index -= (RandInt(30) / 10) + 1;
	if (roach->index < 0)
	    roach->index += ROACH_HEADINGS;
    }
}
开发者ID:EPiCS,项目名称:reconos_v2,代码行数:19,代码来源:nxroach.c



注:本文中的RandInt函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ Random函数代码示例发布时间:2022-05-30
下一篇:
C++ RandFloat函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap