本文整理汇总了C++中RandInt函数的典型用法代码示例。如果您正苦于以下问题:C++ RandInt函数的具体用法?C++ RandInt怎么用?C++ RandInt使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了RandInt函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)));
}
}
示例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;
}
示例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] );
}
示例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;
}
示例5: RandInt
xor::xor(void)
{
fitness = 0;
posX = RandInt(0, dimMapa/dimCasilla)*dimCasilla;
posY = RandInt(0, dimMapa/dimCasilla)*dimCasilla;
crearListaObjetos();
}
示例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
}
示例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;
}
示例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;
}
示例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));
}
示例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);
}
示例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))
};
}
示例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);
}
}
示例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);
}
示例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
}
示例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;
}