void TestReCode5()
{

	cout << " TestReCode5()" << endl;
	GaloisElemVV vv;
	GaloisElemV _x1 = generateRandomNC(8);
	GaloisElemV _x2 = generateRandomNC(8);
	GaloisElemV _x3 = _x1;

	MTRand CodingCoefficient;
	int x = CodingCoefficient.randInt(CodingSpace)+1;//int(tompo);
	GaloisElem a(&gf, x);
	int y = CodingCoefficient.randInt(CodingSpace)+1;//int(tompo);
	GaloisElem b(&gf, y);

	GaloisElemV::iterator it_2 = _x2.begin();
	GaloisElemV::iterator it_3 = _x3.begin();

	for(; it_2 != _x2.end(); )
	{
		(*it_3) *= a;
		*it_2 *= b;
		(*it_3) += *it_2;
		it_2++;
		it_3++;
	}

	vv.push_back(_x1);
	vv.push_back(_x2);
	vv.push_back(_x3);

	cout << gaussElimination(vv) << endl;
}
예제 #2
0
void HPRC4LikeCipher::Init(const uint8 *key, uint32 size)
{
    // align key to 32 bits
    std::vector<uint32> keycopy((size + sizeof(uint32) - 1) / sizeof(uint32));
    DEBUG(ASSERT(keycopy.size() * sizeof(uint32) >= size));
    // the last 3 bytes may be incomplete, null those before copying
    keycopy[keycopy.size() - 1] = 0;
    memcpy(&keycopy[0], key, size);

#if IS_BIG_ENDIAN
    for(uint32 i = 0; i < keycopy.size(); ++i)
        ToLittleEndian(keycopy[i]);
#endif

    MTRand mt;
    mt.seed((uint32*)&keycopy[0], keycopy.size());

    for(uint32 i = 0; i < 256; ++i)
        _sbox[i] = i | (mt.randInt() << 8); // lowest bit is always the exchange index, like in original RC4

    uint32 a = 0, b = 0;

    for(uint32 i = 0; i < std::max<uint32>(256, size); ++i)
    {
        b += key[a] + _sbox[i & 0xFF];
        iswap(_sbox[i & 0xFF], _sbox[b & 0xFF]);
        ++a;
        a %= size;
    }
}
예제 #3
0
bool cChunkGenerator::Start(cWorld * a_World, cIniFile & a_IniFile)
{
	MTRand rnd;
	m_World = a_World;
	m_Seed = a_IniFile.GetValueSetI("Seed", "Seed", rnd.randInt());
	AString GeneratorName = a_IniFile.GetValueSet("Generator", "Generator", "Composable");

	if (NoCaseCompare(GeneratorName, "Noise3D") == 0)
	{
		m_Generator = new cNoise3DGenerator(*this);
	}
	else
	{
		if (NoCaseCompare(GeneratorName, "composable") != 0)
		{
			LOGWARN("[Generator]::Generator value \"%s\" not recognized, using \"Composable\".", GeneratorName.c_str());
		}
		m_Generator = new cComposableGenerator(*this);
	}

	if (m_Generator == NULL)
	{
		LOGERROR("Generator could not start, aborting the server");
		return false;
	}

	m_Generator->Initialize(a_World, a_IniFile);

	return super::Start();
}
예제 #4
0
void world::recordGeneration()
{

    //  choose a random clock from within the population
    MTRand randGen;
    int randNum = randGen.randInt((int)mWorldSettings.mPopulationSize - 1);

    //  for each row in the genome
    for (int x = 0; x < mWorldSettings.mGenomeSize; x++)
    {
        //  for each column in the genome
        for (int y = 0; y < mWorldSettings.mGenomeSize; y++)
        {
            //  get the piece genome data
            clockPiece outputPiece = mPopulation[randNum].getClockPiece(x, y);
            outputPiece.getPieceType();

            //  output genome layout to screen, replacing numeric values with letters which represent the part type
            if (outputPiece.getPieceType() != PTYPE_NULL)
            {
                if (outputPiece.getPieceType() == PTYPE_ESCAPEMENT)
                {
                    cout << "E";
                    gout << "E";
                }
                else if (outputPiece.getPieceType() == PTYPE_GEAR)
                {
                    cout << "G";
                    gout << "G";
                }
                else if (outputPiece.getPieceType() == PTYPE_PENDULUM)
                {
                    cout << "P";
                    gout << "P";
                }
                else if (outputPiece.getPieceType() == PTYPE_MAINSPRING)
                {
                    cout << "M";
                    gout << "M";
                }
                else if (outputPiece.getPieceType() == PTYPE_HAND)
                {
                    cout << "H";
                    gout << "H";
                }
            }
            else
            {
                cout << " ";
                gout << " ";
            }
        }
        cout << endl;
        gout << endl;
    }

	//	output clock data
    mPopulation[randNum].calcSurvivalScore(true);
    gout << endl;
}
예제 #5
0
void Graph::pass_messages(MTRand &mtrand){
	//std::cout<<"WOW I am HERE";
    
	for (std::vector<Person*>::const_iterator p = m_people.begin(); p != m_people.end(); ++p){
        std::list<Person*> friends=((*p)->get_friends());
        std::list<Message*> messages_lst=((*p)->get_messages());
        
        std::list<Message*>::const_iterator it4=messages_lst.back();
        Message* c=messages_lst.back();
        const std::string z=((*c)->get_message());
        int random_num=mtrand.randInt(friends.size());
        // find the random number from the friends list and send the message to that number
        std::list<Person*>::const_iterator it3=friends.begin();
        
        for(int i=0;i<random_num-1;i++){
            it3++;
        }
        
        //Person* p1=it3;
        std::string pers=(*it3)->get_name();
        // we need to add the message into the graph also and that will call message of person.
        // We need to change the owner of the function also
        bool a=add_message(pers,z);
        bool b=((*it3)->remove_message(it4));
        
	}
	
}
예제 #6
0
static cell_t GetURandomInt(IPluginContext *ctx, const cell_t *params)
{
	MTRand *randobj = s_RandHelpers.RandObjForPlugin(ctx);
	/* Note the sign bit must be stripped off because cell_t is signed,
	 * and this guarantees a range of [0,max_int]
	 */
	return randobj->randInt() & 0x7FFFFFFF;
}
예제 #7
0
int RandomBin :: randInt(Stream_type Stream)
{
	MTRand *streamPtr = GetStream(Stream);
	if (streamPtr != NULL) {
		return streamPtr->randInt();
	}
	return 0;
}
예제 #8
0
// ==========================================================================
// To get you started, this function places tiles on the board and
// randomly and outputs the results (in all likelihood *not* a
// solution!) in the required format
void RandomlyPlaceTiles(Board &board, const std::vector<Tile*> &tiles, std::vector<Location> &locations) {

  // MersenneTwister is an excellent library for psuedo-random numbers!
  MTRand mtrand;

  for (int t = 0; t < tiles.size(); t++) {
    // loop generates random locations until we (eventually) find one
    // that is not occupied
    int i,j;
    do {
      // generate a random coordinate within the range 0,0 -> rows-1,cols-1
      i = mtrand.randInt(board.numRows()-1);
      j = mtrand.randInt(board.numColumns()-1);
    } while (board.getTile(i,j) != NULL);

    // rotation is always 0 (for now)
    locations.push_back(Location(i,j,0));
    board.setTile(i,j,tiles[t]);
  }
}
예제 #9
0
void Graph::pass_messages(MTRand &mtrand){
	

	for (std::vector<Person*>::const_iterator p2 = m_people.begin(); p2 != m_people.end(); ++p2){
		std::list<Person*> friends=((*p2)->get_friends());
		std::list<Message*> messages_lst=((*p2)->get_messages());
		
		//std::cout<<"size"<<friends.size()<<std::endl;
		if(messages_lst.size()==0)
		{
			continue;
		}
		//std::cout<<"Person"<<(*p2)->get_name()<<std::endl;
		//for (std::list<Message *>::const_iterator it1 = messages_lst.begin(); it1 != messages_lst.end(); ++it1){
			
					int random_num=mtrand.randInt(friends.size());
					//std::cout<<"random number generated"<<random_num<<std::endl;

					if(random_num==0)
					{
						continue;
					}
					
					else{
						std::list<Person*>::const_iterator it3=friends.begin();
						std::list<Message *>::const_iterator it1 = messages_lst.begin();
							for(int i=0;i<random_num-1;i++){
							it3++;
							}
					
						//Person* p1=*it3;
						std::string pers=(*it3)->get_name();
					//	std::cout<<"person"<<pers<<std::endl;

						const std::string z=((*it1)->get_message());
						//std::cout<<z;
						bool a=add_message(pers,z);
						bool b=((*p2)->remove_message(*it1));
						
					}
					
					// find the random number from the friends list and send the message to that number	
					
					
					
					// we need to add the message into the graph also and that will call message of person.
					// We need to change the owner of the function also
					
					//continue;
		//}			
	}
	
}
void Recode(GaloisElemV& des, GaloisElemV src)
{
	//cout << "Recode(GaloisElemV& in_cache, const GaloisElemV new_come)" << endl;
	MTRand CodingCoefficient;
	int x = CodingCoefficient.randInt(CodingSpace)+1;//int(tompo);
	GaloisElem a(&gf, x);
	int y = CodingCoefficient.randInt(CodingSpace)+1;//int(tompo);
	GaloisElem b(&gf, y);
	
	GaloisElemV::iterator it_des = des.begin();
	GaloisElemV::iterator it_src = src.begin();
	for(;it_des != des.end(); )
	{	
		
		(*it_des)	= a * (*it_des) + b * (*it_src);

		it_des++;
		it_src++;
	}

}
예제 #11
0
//  constructs a random clockpiece
clockPiece::clockPiece()
{
    //  creates an MTRand that can make random numbers
    MTRand randGen;

    //  initialize data
    mPieceType = randGen.randInt(PTYPE_AMT);
    mPieceInterval = 0;
    mPendulumLength = 0;
    mNumTeeth = 0;
    mIsConnected = false;
    mIsPowered = false;
    mIsAttToHand = false;

    //  determine other member variables based on the part type
    if (mPieceType == PTYPE_PENDULUM)
		//	random length of pendulum between 0 and 1 meter
        mPendulumLength = randGen.rand();
    else if (mPieceType == PTYPE_GEAR)
		//	random number of gear teeth (physical minimum is 3)
        mNumTeeth = randGen.randInt(MAX_TEETH - 3) + 3;
}
void Recode(GaloisElemVV& _factors, GaloisElemV factor)
{
	cout << "Recode(GaloisElemVV& in_cache, const GaloisElemV new_come)" << endl;
	MTRand CodingCoefficient;
	int x = CodingCoefficient.randInt(CodingSpace)+1;//int(tompo);
	//int x = 1;
	GaloisElem a(&gf, x);
	int y = CodingCoefficient.randInt(CodingSpace)+1;//int(tompo);
	//int y = 1;
	GaloisElem b(&gf, y);

	for(GaloisElemVV::iterator it_vv = _factors.begin();it_vv != _factors.end(); it_vv++)
	{
		GaloisElemV::iterator it_f = factor.begin();
		GaloisElemV::iterator it_v = it_vv->begin();
		for(; it_v != it_vv->end(); )
		{
			(*it_v) = a * (*it_v) + b * (*it_f);
			it_v++;
			it_f++;
		}
	}
}
예제 #13
0
void SwarmFitterInterface::randomizeTopology(vector< SwarmFly > & swarm, int maxInformed, MTRand & randGen) {

	for (int i = 0; i < (int)swarm.size(); i++) {
		swarm[i].resetInformants();
		showMessage(str(i) + " informs: { ",4,fixedParams); 
		for (int j = 0; j < maxInformed; j++) {
			int randI = randGen.randInt(swarm.size()-1);
			swarm[randI].addInformant(&(swarm[j]));
			showMessage(str(randI) + " ",4,fixedParams); 
		}
		showMessage("}\n",4,fixedParams); 
	}

}
// generate the next word in the sentence
std::pair<std::string, float> WordFrequency::NextWord( const std::vector<std::string> & sentence, bool random) {
  static MTRand mtrand;
  int start_index = std::max(0,int(sentence.size()) - (depth-1));
  WordFrequency* tmp = this;
  // navigate to the right portion of the overall map hierarchy
  for ( unsigned int i = start_index; i < sentence.size(); i++ ) {
    tmp = tmp->GetWord(sentence[i]);
    if ( tmp == NULL) {
      return std::make_pair(std::string(""),0.0);
    }
  }
  assert(tmp!=NULL);
  // calculate statistis about the options
  int max = -1;
  int total = 0;
  std::string answer;
  std::map<std::string,WordFrequency*>::const_iterator j;
  for ( j= tmp->frequency.begin(); j!=tmp->frequency.end(); j++ ) {
    total += j->second->samples;
    if ( max < j->second->samples) {
      max = j->second->samples;
      answer = j->first;
    }
  }
  if (total == 0 )
    return std::make_pair(std::string(""),0.0);
  if (random == false )
    return std::make_pair(answer,max/double(total));
  assert(total > 0);
  int rand = mtrand.randInt(total-1);
  assert(rand >=0 && rand < total);
  int sum =0;
  int prob = 0;
  for ( j=tmp->frequency.begin(); j != tmp->frequency.end(); j++ ) {
    sum+= j->second->samples;
    if ( sum > rand ) {
      answer = j->first;
      prob = j->second->samples;
      break;
    }
  }
  assert(sum>rand);
  assert(sum <= total);
  assert(answer !="");
  return std::make_pair(answer,prob/float(total));
}
예제 #15
0
bool cChunkGenerator::Start(cPluginInterface & a_PluginInterface, cChunkSink & a_ChunkSink, cIniFile & a_IniFile)
{
	m_PluginInterface = &a_PluginInterface;
	m_ChunkSink = &a_ChunkSink;

	// Get the seed; create a new one and log it if not found in the INI file:
	if (a_IniFile.HasValue("Seed", "Seed"))
	{
		m_Seed = a_IniFile.GetValueI("Seed", "Seed");
	}
	else
	{
		MTRand rnd;
		m_Seed = rnd.randInt();
		LOGINFO("Chosen a new random seed for world: %d", m_Seed);
		a_IniFile.SetValueI("Seed", "Seed", m_Seed);
	}
	
	// Get the generator engine based on the INI file settings:
	AString GeneratorName = a_IniFile.GetValueSet("Generator", "Generator", "Composable");
	if (NoCaseCompare(GeneratorName, "Noise3D") == 0)
	{
		m_Generator = new cNoise3DGenerator(*this);
	}
	else
	{
		if (NoCaseCompare(GeneratorName, "composable") != 0)
		{
			LOGWARN("[Generator]::Generator value \"%s\" not recognized, using \"Composable\".", GeneratorName.c_str());
		}
		m_Generator = new cComposableGenerator(*this);
	}

	if (m_Generator == nullptr)
	{
		LOGERROR("Generator could not start, aborting the server");
		return false;
	}

	m_Generator->Initialize(a_IniFile);

	return super::Start();
}
예제 #16
0
// integer from 0 to n-1
int randInt(int max) { 
    //return (int)((float) max*rand()/(RAND_MAX+1.0));
	return twist.randInt(max-1);
}
예제 #17
0
int32 rand32()
{
    return mtRand.randInt();
}
예제 #18
0
uint32 urand(uint32 min, uint32 max)
{
    return mtRand.randInt(max - min) + min;
}
예제 #19
0
int32 irand(int32 min, int32 max)
{
    return int32(mtRand.randInt(max - min)) + min;
}
예제 #20
0
// integer in [0,2^32-1]
uint32_t SoarRandInt()
{
    return gSoarRand.randInt();
}
예제 #21
0
list<ListGraph::Node> GreedyHeuristic::execute() {
    
    typedef ListGraph::EdgeMap<double> LengthMap;
    typedef Dijkstra<SubGraph<ListGraph>, LengthMap> ShortestPath;
    
    list<ListGraph::Node> solution;    
    // First we instantiate an vector with all the terminal nodes
    list<ListGraph::Node> tnode;
    for (ListGraph::NodeIt v(*graph); v!= INVALID; ++v) {
        if ((*terminal)[v]) {
            tnode.push_back(v);
        }
    }

    // Random get an terminal node 
    MTRand rand;
    list<ListGraph::Node>::iterator iter;
    int i = rand.randInt() % tnode.size();
    int currentNode = 0;
    ListGraph::Node node;
    for (iter = tnode.begin(); iter != tnode.end(); iter++) {
        if (currentNode == i) {
            node = *iter;
            tnode.erase(iter);
            break;
        }
        currentNode++;
    }
    solution.push_back(node);
    while (tnode.size() > 0) {
        double min = DBL_MAX;        
        list<ListGraph::Node>::iterator term;
        list<ListGraph::Node>::iterator bestNode;
        Path<ListGraph> p;
        
        // First we instantiate an vector with all the terminal nodes
        list<ListGraph::Node> fulltnode;
        for (ListGraph::NodeIt v(*graph); v!= INVALID; ++v) {
            if ((*terminal)[v]) {
                fulltnode.push_back(v);
            }
        }
        //cout << "Saindo de: " << (*graph).id(node);        
        for (term = tnode.begin(); term != tnode.end(); term++) {
            ListGraph::NodeMap<bool> node_filter(*graph);
            ListGraph::EdgeMap<bool> edge_filter(*graph);
            //cout << " Chegando em: " << (*graph).id(*term) << endl;
            list<ListGraph::Node> nodesToRemove;
            // Create the node_filter
            for (ListGraph::NodeIt v(*graph); v != INVALID; ++v) {
                //cout << "No atual: " << (*graph).id(v) << endl;
                bool belongSubGraph = true;
                if(( (*graph).id(v) != (*graph).id(node)) &&
                    ((*graph).id(v) != (*graph).id(*term))) {
                    list<ListGraph::Node>::iterator iter;

                    // Remove all the nodes that belongs to the solution
                    for (iter = solution.begin(); iter != solution.end(); iter++) {
                        if((*graph).id(v) == (*graph).id(*iter)) {
                            nodesToRemove.push_back(v);
                            belongSubGraph = false;
                            //cout << "\t no " << (*graph).id(*iter) << "removido pertence a solucao" << endl;
                            break;
                        }
                    }

                    // Remove all the other terminal nodes 
                    for (iter = fulltnode.begin(); iter != fulltnode.end(); iter++) {
                        if((*graph).id(v) == (*graph).id(*iter)) {
                            nodesToRemove.push_back(v);
                            belongSubGraph = false;
                            //cout << "\t no " << (*graph).id(*iter) << "removido pertence aos terminais" << endl;
                            break;
                        }
                    }
                }
                node_filter[v] = belongSubGraph;
            }

            // Create the edge_filter
            for (ListGraph::EdgeIt ed((*graph)); ed != INVALID; ++ed) {
                list<ListGraph::Node>::iterator iter;
                bool value = true;
                for (iter = nodesToRemove.begin(); iter != nodesToRemove.end(); iter++) {
                    if ( (*graph).u(ed) == *iter || (*graph).v(ed) == *iter) {
                        value = false;
                    }
                }
                edge_filter[ed] = value;
            }

            // Generate a subgraph with the nodes that arent on the solution
            SubGraph<ListGraph> sg(*graph, node_filter, edge_filter);
            ShortestPath d(sg, *length);            
            d.run(node);
            double current = calculatePathValue(d.path(*term));
            if (current < min) {
                min = current; 
                bestNode = term;
                p = d.path(*term);
            }
            //cout << "VALUE: " << current << " PATH: " << (*graph).id(node)<< " ";
            for (Path<ListGraph>::ArcIt it(p); it != INVALID; ++it) {
                ListGraph::Arc a = it;
                ListGraph::Edge x = a;
                if ((*graph).u(x) == node) {
                    //cout << (*graph).id((*graph).v(x)) << " ";
                } else if ((*graph).v(x) == node) {
                    //cout << (*graph).id((*graph).u(x)) << " ";
                }
            }
            //cout << endl;
        }
        tnode.erase(bestNode);
        
        // Add the shortest path to the solution
        bool first = true;
        //cout << "PATH: " << endl;
        for (Path<ListGraph>::ArcIt it(p); it != INVALID; ++it) {
            ListGraph::Arc a = it;
            ListGraph::Edge x = a;
            //cout << "edge: " << (*graph).id((*graph).u(x)) << "->" << (*graph).id((*graph).v(x)) << endl;
            if ((*graph).u(x) == node) {
                solution.push_back((*graph).v(x));
            } else if ((*graph).v(x) == node) {
                solution.push_back((*graph).u(x));                    
            } else {
                solution.push_back((*graph).v(x));
            }

            //cout << "\t add 1 nodes:" << endl;;
            //cout << "\t\t add " << (*graph).id((*graph).v(x)) << endl;
        }
        
        //cout << "SOLUCAO ATUAL: ";
        list<ListGraph::Node>::iterator s;
        for (s = solution.begin(); s != solution.end(); s++) {
            //cout << (*graph).id(*s) << " ";
        }
        //cout << endl;

		// Get the last element from solution
        term = solution.end();
        term--; node = *term;
	}
	
    return solution;
}
예제 #22
0
/*!
  Uniform sampling of an integer in the range [a, b].
  Precondition: a <= b
 */
int p3d_random_integer(int a, int b)
{
  assert(a <= b);
  return(mersenne_twister_rng.randInt(b - a) + a);
}
예제 #23
0
void world::mateClocks()
{
    //  create a random number generator
    MTRand randGen;
    const int CLOCKS_TO_COMPETE = 3;
    const int SRC_1 = 0;
    const int SRC_2 = 1;
    const int LEAST_ACC = 2;

    //  store indexes and accuracies of relevant clocks
    int clockIndexes[CLOCKS_TO_COMPETE];
    double clockScores[CLOCKS_TO_COMPETE];

    //  temp variables for swapping while sorting
    int tempIndex;
    double tempScore;

    //  stores selected clocks, initialized to a value out of array
    int selectedClocks[CLOCKS_TO_COMPETE - 1] = {-1,-1};
    int randClock = 0;

    //  run through each generation
    for (int x = 0; x < mWorldSettings.mNumGenerations; x++)
    {
        //  a generation is defined by x matings in a population of x clocks
        for (int y = 0; y < mWorldSettings.mPopulationSize; y++)
        {
            for (int i = 0; i < CLOCKS_TO_COMPETE; i++)
            {
                do
                {
                    randClock = randGen.randInt(mPopulation.size() - 1);
                }
                while (selectedClocks[0] == randClock || selectedClocks[1] == randClock);

                if (i != CLOCKS_TO_COMPETE)
                    selectedClocks[i] = randClock;

                // 	randomly choose a clock index from the population
                clockIndexes[i] = randClock;
                // 	retrieve the score of the clock
                clockScores[i] =  mPopulation[clockIndexes[i]].calcSurvivalScore();
            }

            //  sort clocks by survival score
            for (int j = 0; j < CLOCKS_TO_COMPETE; j++)
            {
                for (int k = j; k < CLOCKS_TO_COMPETE; k++)
                {
                    // 	ensure that the index goes from greatest to least accurate
                    if (clockScores[j] < clockScores[k])
                    {
                        //  if it doesn't, swap the accuracy and index reference
                        tempScore = clockScores[k];
                        clockScores[k] = clockScores[j];
                        clockScores[j] = tempScore;

                        tempIndex = clockIndexes[k];
                        clockIndexes[k] = clockIndexes[j];
                        clockIndexes[j] = tempIndex;
                    }
                }
            }

            //  rewrite third (least accurate) clock using source data from two other ones (the parents)
            bioClock childClock (mPopulation[clockIndexes[SRC_1]], mPopulation[clockIndexes[SRC_2]]);
            mPopulation[clockIndexes[LEAST_ACC]] = childClock;
        }
        recordGeneration();
        cout << endl << "This is generation " << x + 1 << endl;
        outputGenAverages();
    }
}
예제 #24
0
파일: stdlib.cpp 프로젝트: berkus/metta
extern "C" int rand()
{
    return library_randomness.randInt();
}
예제 #25
0
int cProbabDistrib::Random(MTRand & a_Rand) const
{
	int v = a_Rand.randInt(m_Sum);
	return MapValue(v);
}
예제 #26
0
// integer in [0,n] for n < 2^32
uint32_t SoarRandInt(const uint32_t& max)
{
    return gSoarRand.randInt(max);
}