void InitializeBoard(Grid<string> &board) { //assign each location a letter for (int i = 0; i < board.numRows(); i++) { for (int j = 0; j < board.numCols(); j++) { int RandNum = RandomInteger(0,5); //change if big board board(i,j) = StandardCubes[i * board.numCols() + j][RandNum]; //pick a random letter from each of the 16 cubes } } //swap letters randomly so that each letter is swapped at least once for (int i = 0; i < board.numRows(); i++) { for (int j = 0; j < board.numCols(); j++) { int RandRow = RandomInteger(0, board.numRows() - 1); int RandCol = RandomInteger(0, board.numCols() - 1); string s1 = board(i,j); string s2 = board(RandRow, RandCol); board(i,j) = s2; board(RandRow, RandCol) = s1; } } //update graphics for (int i = 0; i < board.numRows(); i++) { for (int j = 0; j < board.numCols(); j++) { LabelCube(i, j, board(i,j)[0]); } } }
int InfAdmixture::moveQrow(int a) { int r1=RandomInteger(0,Q[a].size()-1),r2=r1; while(r2==r1) r2=RandomInteger(0,Q[a].size()-1); double x=rnd();// the proportion of r1+r2 to move to r2 // double oldloglik=state->admixtureApproxSetLogLikelihood(r1,&Q,&P)+state->admixtureApproxSetLogLikelihood(r2,&Q,&P); double oldloglik=state->admixtureApproxIndLogLikelihood(a,&Q,&P); // double oldloglik=state->admixtureLogLikelihood(&Q,&P,&QcolSums); double oldpriorQ=priorForQ(a); double oq1=Q[a][r1],oq2=Q[a][r2]; if(atest){ Q[a][r1]=oq2; Q[a][r2]=oq1; }else{ Q[a][r1]=(oq1+oq2) * x; Q[a][r2]=(oq1+oq2) * (1.0-x); } //double newloglik=state->admixtureLogLikelihood(&Q,&P,&QcolSums); //double newloglik=state->admixtureApproxIndLogLikelihood(a,&Q,&P); double newloglik=state->admixtureApproxIndLogLikelihood(a,&Q,&P); // double newloglik=state->admixtureApproxSetLogLikelihood(r1,&Q,&P)+state->admixtureApproxSetLogLikelihood(r2,&Q,&P); // cout<<"p="<<logstateprob<<" + "<<priorForQ(a)<<" - "<<oldloglik<<" - "<<oldpriorQ<<endl; if(log(rnd())>newloglik + priorForQ(a) - oldloglik - oldpriorQ) { //rejected // cout<<"rejected"<<endl; Q[a][r1]=oq1; Q[a][r2]=oq2; return(0); } // else accept // cout<<"accepted!"<<endl; logstateprob += newloglik-oldloglik;// update our running total of the likelihood return(1); }
/* * Function: PrintRandomSentances * Usage: PrintRandomSentances (int & Markov, Map<Vector<char> > & MarkovData) * -------------------------------------------------------------------------------- * Takes in the Markov Data given in the map and generates random sentances. */ void PrintRandomSentances(int & MarkovNum, Map<Vector<char> > & MarkovData) { string seed; GetMostFrequentSeed(seed, MarkovData); cout << "I'm gonna Write some f*****g sentances"; if (MarkovNum == 0) { for (int i = 0; i < NUM_CHARS; i++) { int rand = RandomInteger(32, 125); char totRand = rand; cout << totRand; } } else { for (int i = 0; i < NUM_CHARS; i++) { Vector<char> next = MarkovData[seed]; int rand = RandomInteger(0, next.size() - 1); cout << next[rand]; seed = seed.substr(1) + next[rand]; } } }
void PlacingShips(class_p clas,ship_p ship,ship_p cell[][NUM_COLS],int ship_num) { coord CELL; int length,pass,col,row,i,k,j,direction; for(i=0;i<=ship_num-1;i++) { length=clas[ship[i].clas].length; do { col=RandomInteger(0,NUM_COLS); row=RandomInteger(0,NUM_ROWS); direction=RandomInteger(1,2); // 1 for vert,2 for horiz pass=1; if (direction==1) { for (k=0;k<=length-1;k++) { CELL.col=col; CELL.row=row+k; if ( IsInside(CELL) && cell[CELL.row][CELL.col]==NULL ) {;} else {pass=0;} } } if (direction==2) { for (k=0;k<=length-1;k++) { CELL.col=col+k; CELL.row=row; if ( IsInside(CELL) && cell[CELL.row][CELL.col]==NULL ) {;} else {pass=0;} } } } while (pass==0); if (direction==1) { for (j=0;j<=length-1;j++) { cell[row+j][col]=&ship[i]; ( ( ship[i].contain )[j] ).row=row+j; ( ( ship[i].contain )[j] ).col=col; } } if (direction==2) { for (j=0;j<=length-1;j++) { cell[row][col+j]=&ship[i]; ( ( ship[i].contain )[j] ).row=row; ( ( ship[i].contain )[j] ).col=col+j; } } } }
/* * Function: ShuffleDice * -------------------------- * Randomly shuffles the dice in the boggleBoard by swapping the contents of 2 random locations in boggleBoard. * Ensures the same dice does not always appear in the same location. */ void ShuffleDice(Grid<char> &boggleBoard) { int row = 0, col = 0; while (true) { int randomRow = RandomInteger(0, boggleBoard.numRows() - 1); int randomCol = RandomInteger(0, boggleBoard.numCols() - 1); char dice = boggleBoard.getAt(row, col); boggleBoard.setAt(row, col, boggleBoard.getAt(randomRow, randomCol)); boggleBoard.setAt(randomRow, randomCol, dice); if (!AdjacentPoint(boggleBoard.numRows(), boggleBoard.numCols(), row, col)) break; } }
/* * Function: RunSortTrial * ---------------------- * Runs the sorting time trial for the specified pqueue size. * Reports results to cout. */ void RunSortTrial(int size) { int *array = new int[size]; for (int i = 0; i < size; i++) // put random data into array array[i] = RandomInteger(1, size); cout << "Time to pqsort random sequence of " << size << " elements: " << flush; double start = GetCurrentTime(); PQSort(array, size); cout << GetCurrentTime() - start << " msecs" << endl; cout << "Time to pqsort sorted sequence of " << size << " elements: " << flush; for (int j = 0; j < size; j++) // put data in array already sorted array[j] = j; start = GetCurrentTime(); PQSort(array, size); cout << GetCurrentTime() - start << " msecs" << endl; cout << "Time to pqsort reverse-sorted sequence of " << size << " elements: " << flush; for (int k = 0; k < size; k++) // put data in array already reverse sorted array[k] = size - k; start = GetCurrentTime(); PQSort(array, size); cout << GetCurrentTime() - start << " msecs" << endl; delete [] array; }
//Replace errors from evaluating set by non prototypes from training set void opf_SwapErrorsbyNonPrototypes(Subgraph **sgtrain, Subgraph **sgeval){ int i, j, counter, nonprototypes = 0, nerrors = 0; for (i = 0; i < (*sgtrain)->nnodes; i++){ if((*sgtrain)->node[i].pred != NIL){ // non prototype nonprototypes++; } } for (i = 0; i < (*sgeval)->nnodes; i++) if((*sgeval)->node[i].label != (*sgeval)->node[i].truelabel) nerrors++; for (i = 0; i < (*sgeval)->nnodes && nonprototypes >0 && nerrors > 0; i++){ if((*sgeval)->node[i].label != (*sgeval)->node[i].truelabel){ counter = nonprototypes; while(counter > 0){ j = RandomInteger(0,(*sgtrain)->nnodes-1); if ((*sgtrain)->node[j].pred!=NIL) { SwapSNode(&((*sgtrain)->node[j]), &((*sgeval)->node[i])); (*sgtrain)->node[j].pred = NIL; nonprototypes--; nerrors--; counter = 0; } else counter--; } } } }
Vector<int> RandomArray(int size, int min, int max){ Vector<int> arr(size); for(int i = 0; i < size; i++){ arr.add(RandomInteger(min,max)); } return arr; }
string BuildMarkovString(int k, Map< Map<int> > &p, string &max_p_pattern) { string new_text = max_p_pattern; string current_view = max_p_pattern; Randomize(); int r_index; string key; for (int i = 0; i < nCHARS; i++) { int total = p[current_view]["TOTAL"]; r_index = RandomInteger(1, p[current_view]["TOTAL"]); Map<int>::Iterator itr = p[current_view].iterator(); while (itr.hasNext()) { key = itr.next(); if ( key == "TOTAL" ) key = itr.next(); if (r_index <= p[current_view][key]) { new_text += key; current_view += key; current_view.replace(0, 1, ""); break; } else { r_index -= p[current_view][key]; } } } return new_text; }
// Crossover Method void GeneticAlgorithm::Crossover(const vector<int> &vMother, const vector<int> &vFather, vector<int> &vOffspringAlpha, vector<int> &vOffspringBeta) { // Just return parents as offspring, dependent on the rate or if the parents are the same if ((RandomFloat() > mCrossoverRate) || (vMother == vFather)) { // Set the alpha offspring vOffspringAlpha = vMother; // Set the beta offspring vOffspringBeta = vFather; // Return return; } // Determine the crossover point int iCrossoverPoint = RandomInteger(0, (mChromosomeLength - 1)); // Swap the bits for (int iGenome = 0; iGenome < iCrossoverPoint; ++iGenome) { // Add an alpha offspring vOffspringAlpha.push_back(vMother[iGenome]); // Add a beta offspring vOffspringBeta.push_back(vFather[iGenome]); } for (int iMotherGenome = iCrossoverPoint; iMotherGenome < (int) vMother.size(); ++iMotherGenome) { // Add another alpha offspring vOffspringAlpha.push_back(vFather[iMotherGenome]); // Add another beta offspring vOffspringBeta.push_back(vMother[iMotherGenome]); } }
string RandomString(Vector<char> &chars, int size){ string output = ""; for(int i = 0; i < size; i++){ output+= chars[RandomInteger(0,chars.size()-1)]; } return output; }
void RunStringSort(){ //building a list of valid characters for random strings. alphabetical + spaces. Vector<char> chars; for(int i = 65; i < 91; i++){ chars.add((char)i); } for(int i = 97; i < 123; i++){ chars.add((char)i); } chars.add(' '); // populating a vector with some random strings Vector<string> teststrings; for(int i = 0; i < 40; i++){ teststrings.add(RandomString(chars,RandomInteger(3,10))); } // running the vector through the sort algorithm. cout << "Testing our CombSort on a vector of strings..." << endl << endl; cout << "Here is the unsorted vector of strings:" << endl << endl; PrintVectorString(teststrings); CombSort(teststrings,StringCmp); cout << "Here is the sorted version." << endl << endl; PrintVectorString(teststrings); }
/* * Function: InitializeRandomBoard * ---------------------------------- * Randomly initializes boggleBoard and picks a random side of the dice to face up by randomly selecting * a char from the const dice configuration. Then, calls on ShuffleDice to randomize the positions of the dice. */ void InitializeRandomBoard (Grid<char> &boggleBoard) { PlayNamedSound("dice rattle.wav"); int diceCount = 0, row = 0, col = 0; char randomChar; while (true) { if (boggleBoard.numRows() == 4) { //distinguishes between the 5x5 and 4x4 dice configs randomChar = StandardCubes[diceCount].at(RandomInteger(0, 5)); } else { randomChar = BigBoggleCubes[diceCount].at(RandomInteger(0, 5)); } boggleBoard.setAt(row, col, randomChar); diceCount++; if (!AdjacentPoint(boggleBoard.numRows(), boggleBoard.numCols(), row, col)) break; } ShuffleDice(boggleBoard); }
void Initialize(float *Array) { register int i; _Pragma("loopbound min 1000 max 1000"); for (i=0; i < MAX; i++) Array [i] = i + RandomInteger ()/8095.0f; }
FILE * GetFile(void) { int num; string fname; num=RandomInteger(1,5); fname=Concat("ShipData",IntegerToString(num)); return fopen(fname,"r"); }
void PQueueSortTest(void) { int i; pqueueADT pq; int array[SORT_SIZE]; printf("\n----------- Testing use of pqueue to sort -----------\n"); pq = NewPQueue(); printf("Enqueuing %d numbers into pqueue in increasing order.", SORT_SIZE); for (i = 0; i < SORT_SIZE; i++) array[i] = i; HeapSort(pq, array, SORT_SIZE); printf("\nUsing dequeue to pull out numbers in sorted order. Are they sorted? %s\n", ArrayIsSorted(array, SORT_SIZE) ? "TRUE" : "FALSE"); printf("PQueue should be empty. Is it empty? %s\n", IsEmpty(pq) ? "TRUE" : "FALSE"); printf("\nEnqueuing %d numbers into pqueue in decreasing order.", SORT_SIZE); for (i = 0; i < SORT_SIZE; i++) array[i] = SORT_SIZE - i; HeapSort(pq, array, SORT_SIZE); printf("\nUsing dequeue to pull out numbers in sorted order. Are they sorted? %s\n", ArrayIsSorted(array, SORT_SIZE) ? "TRUE" : "FALSE"); printf("PQueue should be empty. Is it empty? %s\n", IsEmpty(pq) ? "TRUE" : "FALSE"); printf("\nEnqueuing %d random values into the pqueue.\n", SORT_SIZE); for (i = 0; i < SORT_SIZE; i++) array[i] = RandomInteger(1, 1000); HeapSort(pq, array, SORT_SIZE); printf("Using dequeue to pull out numbers in sorted order. Are they sorted? %s\n", ArrayIsSorted(array, SORT_SIZE) ? "TRUE" : "FALSE"); printf("PQueue should be empty. Is it empty? %s\n", IsEmpty(pq) ? "TRUE" : "FALSE"); printf("\nEnqueuing %d random possibly negative values into the pqueue.\n", SORT_SIZE); for (i = 0; i < SORT_SIZE; i++) array[i] = RandomInteger(-1000, 1000); HeapSort(pq, array, SORT_SIZE); printf("Using dequeue to pull out numbers in sorted order. Are they sorted? %s\n", ArrayIsSorted(array, SORT_SIZE) ? "TRUE" : "FALSE"); printf("PQueue should be empty. Is it empty? %s\n", IsEmpty(pq) ? "TRUE" : "FALSE"); FreePQueue(pq); printf("Hit return to continue: "); { string s = GetLine(); FreeBlock(s); } }
/* * Function: RunEnqueueDequeueTrial * -------------------------------- * Runs the enqueue & dequeue time trials for the specified * pqueue size. Reports results to cout. * Note that we just randomly choose numbers to insert. * The amount of time it takes to do one enqueue/dequeue is * too small to be accurately measured, so we do many iterations in * a loop and time that. */ void RunEnqueueDequeueTrial(int size) { PQueue pq; for (int i = 0; i < size; i++) pq.enqueue(RandomInteger(1,size)); cout << "Time to enqueue into " << size << "-element pqueue: " << flush; double start = GetCurrentTime(); for (int j = 0; j < NumRepetitions; j++) pq.enqueue(RandomInteger(1, 2*size)); cout << 1000*(GetCurrentTime() - start)/NumRepetitions << " usecs" << endl; cout << "Time to dequeue from " << size << "-element pqueue: " << flush; start = GetCurrentTime(); for (int k = 0; k < NumRepetitions; k++) pq.dequeueMax(); cout << 1000*(GetCurrentTime() - start)/NumRepetitions << " usecs" << endl; }
void Initialize(double Array[]) /* * Intializes the given array with random integers. */ { register int i; for (i=0; i < MAX; i++) Array [i] = i + RandomInteger ()/8095.0; }
// Intializes the given array with random integers. int Initialize(matrix Array) { register int OuterIndex, InnerIndex; for (OuterIndex = 0; OuterIndex < MAXSIZE; OuterIndex++) //100 + 1 for (InnerIndex = 0; InnerIndex < MAXSIZE; InnerIndex++) //100 + 1 Array[OuterIndex][InnerIndex] = RandomInteger(); return 0; }
Grid<char> makeRandomBoard(string standCubes[]) { Grid<char> newGame(4,4); for (int i = 0; i < 16; i++){ int randIdx = RandomInteger(0,i); string temp = standCubes[i]; standCubes[i] = standCubes[randIdx]; standCubes[randIdx] = temp; } for (int i =0; i < 16; i++) { int randIdx = RandomInteger(0,5); string s = standCubes[i]; char ch = s[randIdx]; int row = i/4; int col = i%4; newGame.setAt(row, col, ch); } return newGame; }
void PlacingCreatures(worldADT world,creatureADT *creatureP,speciesADT *speciesP,int numcreature) { int i; pointT pt; for (i=0;i<=numcreature-1;i++) { while(TRUE) { pt.x=RandomInteger(0,WorldWidth(world)-1); pt.y=RandomInteger(0,WorldHeight(world)-1); if ( GetContents(world,pt) == NULL ) { creatureP[i]=NewCreature(speciesP[i],world,pt,RandomInteger(0,3)); SetContents(world,pt,creatureP[i]); break; } } } }
void Initialize(matrix Array) /* * Intializes the given array with random integers. */ { int OuterIndex, InnerIndex; for (OuterIndex = 0; OuterIndex < UPPERLIMIT; OuterIndex++) for (InnerIndex = 0; InnerIndex < UPPERLIMIT; InnerIndex++) Array[OuterIndex][InnerIndex] = RandomInteger(); }
string randomPattern(string pattern){ int i, size; char *randPat; size = 0; size = StringLength(pattern)+1; randPat = NewArray(size, char); for(i=0; i<size; i++){ randPat[i] = pattern[RandomInteger(0,size - 2)]; } randPat[i] = '\0'; return randPat; }
/* * Function: RunMemoryTrial * ------------------------ * Fills a pqueue to specified size and reports memory usage. Then does * a bunch of enqueue-dequeue operations to jumble things up and reports * on the memory usage again. Reports results to cout. */ void RunMemoryTrial(int size) { PQueue pq; cout << endl << "Running memory trial on " << size << "-element pqueue" << endl; for (int i = 0; i < size; i++) pq.enqueue(RandomInteger(1, size)); cout << "After consecutive enqueues, " << size << "-element pqueue is using " << pq.bytesUsed()/1000 << " KB of memory" << endl; int num = size; for (int j = 0; j < NumRepetitions; j++) { /* do a bunch of enqueue/dequeue ops */ if (RandomChance(.5)) { pq.enqueue(RandomInteger(0, size)); num++; } else { pq.dequeueMax(); num--; } } cout << "After more enqueue/dequeue, " << num << "-element pqueue is using " << pq.bytesUsed()/1000 << " KB of memory" << endl; }
int InfAdmixture::moveProw(int a) { int r1=RandomInteger(0,P[a].size()-1),r2=r1; while(r2==r1) r2=RandomInteger(0,P[a].size()-1); double x=rnd();// the proportion of r1 to move to r2 double oldloglik=logstateprob; double oldpriorP=priorForP(a); double op1=P[a][r1],op2=P[a][r2]; P[a][r1]=(op1+op2) * x; P[a][r2]=(op1+op2) * (1.0-x); logstateprob=state->admixtureLogLikelihood(&Q,&P,&QcolSums); if(log(rnd())>logstateprob + priorForP(a) - oldloglik - oldpriorP) { //rejected P[a][r1]=op1; P[a][r2]=op2; logstateprob=oldloglik; return(0); } // else accept return(1); }
int main(void) { int secret; /* Declare variables */ Randomize(); while(1){ secret = RandomInteger(1,100); playHiLo(secret); } return 0; }
void gera_vetor(int v[]){ int j, i, k; for (i = 0; i< TAM; i++){ j = RandomInteger (10, 100); for (k = 0; k < i; k++) if ( v[k] == j ) break; if(k == i) v[i] = j; else i--; } }
int main() { pointT tri[nPOINTS]; // Get three different points from the user via mouse, connect pts as arrive cout << "Click your mouse in three different areas of the canvas." << endl; cout << "The points will be connected to form a triangle and then" << endl; cout << "the triangle will mysteriously begin to fill." << endl; cout << endl; cout << "ALERT! Click your mouse in the window to stop the fill process." << endl; InitGraphics(); GetTrianglePoints(tri); // randomly choose one of the points, i.e. pick an index from 'tri' Randomize(); int vertex; vertex = RandomInteger(0, nPOINTS-1); pointT cp = tri[vertex]; while ( ! MouseButtonIsDown() ) { //for ( int i = 0; i < 10000; i++ ) { // draw a small, filled circle around the current point DrawCircle(cp); UpdateDisplay(); // randomly choose any of the perimeter vertices vertex = RandomInteger(0, nPOINTS-1); // move the current point halfway towards the new point cp.xp = ( tri[vertex].xp + cp.xp ) / 2; cp.yp = ( tri[vertex].yp + cp.yp ) / 2; //} } return 0; }
void Initialize(matrix Array) { /* * Intializes the given array with random integers. */ int OuterIndex, InnerIndex; // printf("Valores da Matriz: \n\n"); for (OuterIndex = 0; OuterIndex < UPPERLIMIT; OuterIndex++) { /* max 650 */ for (InnerIndex = 0; InnerIndex < UPPERLIMIT; InnerIndex++) { /* max 650 */ Array[OuterIndex][InnerIndex] = RandomInteger(); // printf("(%d)", Array[OuterIndex][InnerIndex]); } } }
/* * Intializes the given array with random integers. */ void Initialize(matrix Array) { int OuterIndex, InnerIndex; // printf("Valores da Matriz: \n\n"); for (OuterIndex = 0; OuterIndex < UPPERLIMIT; OuterIndex++) /* max 770 */ { for (InnerIndex = 0; InnerIndex < UPPERLIMIT; InnerIndex++) /* max 770 */ { Array[OuterIndex][InnerIndex] = RandomInteger(); // printf("(%d)", Array[OuterIndex][InnerIndex]); } } }