void simulateTour(int currentAnt){ int nextNode; int prevNode; ANT * ant = swarm[currentAnt]; ant->way = headWay; nextNode = roulette(ant); ant->BD[0][getColumn(ant, nextNode)] = 1; ant->column[getColumn(ant, nextNode)] = 1; ant->tour[0] = nextNode; ant->way = ant->way->next[nextNode]; while(ant->way){ prevNode = nextNode; nextNode = roulette(ant); ant->x++; ant->y = nextNode / N; ant->z = nextNode % N; ant->BD[ant->y][ant->z] = 1; ant->tour[ant->x][0] = prevNode; ant->tour[ant->x][1] = nextNode; } for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ if((ant->BD[i][j]) && (!checkChessBoard(ant->BD, i, j))) ant->GD++; } } //printf("ant%2d : (%d, %d, %d) GD : %d\n", currentAnt, ant->x, ant->y, ant->z, ant->GD); }
void simulateTour(int currentAnt){ int nextNode; int prevNode; ANT * ant = swarm[currentAnt]; nextNode = firstRoulette(); ant->x = 0; ant->y = 0;//nextNode / N; ant->z = 0;//nextNode % N; ant->BD[ant->y][ant->z] = 1; ant->tour[0][0] = 0; ant->tour[0][1] = nextNode; while(ant->x < N-1){ prevNode = nextNode; nextNode = roulette(ant); ant->x++; ant->y = nextNode / N; ant->z = nextNode % N; ant->BD[ant->y][ant->z] = 1; ant->tour[ant->x][0] = prevNode; ant->tour[ant->x][1] = nextNode; } for(int i = 0; i < N; i++){ for(int j = 0; j < N; j++){ if((ant->BD[i][j]) && (!checkChessBoard(ant->BD, i, j))) ant->GD++; } } //printf("ant%2d : (%d, %d, %d) GD : %d\n", currentAnt, ant->x, ant->y, ant->z, ant->GD); }
void main() { int total=100; char choice; clrscr(); cout << "Crappy program gambling game"; gotoxy(12,12); cout << "Press any key to get on da street"; getch(); while(choice!='Q') { clrscr(); cout << "Dollars : " << total << endl; cout << "(C)raps" << endl << "(B)lackjack" << endl << "(R)oulette" << endl << "(S)lots" << endl << "(Q)uit"; choice=getch(); choice=toupper(choice); switch(choice) { case('C'): { clrscr(); total=craps(total); break; } case('B'): { clrscr(); total=blackjack(total); break; } case('Q'): { clrscr(); quit(total); getch(); break; } case('R'): { clrscr(); total=roulette(total); break; } case('S'): { total=slots(total); break; } } } }
void GA::step() { pop_vector children; children.clear(); children.reserve(m_population_size); // elitism unsigned int elite_size = m_population_size * m_elitism_rate; for (unsigned int i=0; i<elite_size; i++) { children.push_back(m_population[i]->copy()); } // crossover while (children.size() < (m_population_size - elite_size)) { // select parents int p1 = roulette(); int p2 = roulette(); // crossover parents crossover(m_population[p1], m_population[p2], children); } // mutation mutate(children); // update population and save last population update(children); // evaluate fitness and sort evaluate_fitness(); // log, save generation log(); save_histograms(); }
int GAConjProblemForORGroupSolver::selectGene( ) const { int result; double *p = new double[numGenes]; for( int t=0 ; t<numGenes ; ++t ) if( genes[t] ) p[t] = 1/genes[t]->fitness( ); else p[t] = 0; result = roulette( numGenes , p ); delete []p; return result; }
void psuedo_carlo(Map map, Particle *particles) { float probabilities[NUM_PARTICLES]; Particle new_particles[NUM_PARTICLES]; int i; for (i = 0; i < NUM_PARTICLES; i++) { probabilities[i] = (float)i / (float)NUM_PARTICLES; } for (i = 0; i < NUM_PARTICLES; i++) new_particles[i] = particles[roulette(probabilities, NUM_PARTICLES)]; for (i = 0; i < NUM_PARTICLES; i++) particles[i] = new_particles[i]; }
void Ga::selectSurvive(vector<Individual*> &family) { sort(family.begin(),family.end(),Individual::Comparator); m_Population.push_back(family[0]); Util::removeVector(family,0); int r=roulette(family); m_Population.push_back(family[r]); Util::removeVector(family,r); for(int i=0; i<family.size(); i++) { delete(family[i]); } #ifdef DEBUG cout<<"crossover"<<endl; printList(); #endif }
/*選択*/ void selection(char gene[POOLSIZE][RULESIZE][LOCUSSIZE],char midgene[POOLSIZE*2][RULESIZE][LOCUSSIZE], char lines[MAXLINES][LINESIZE],int lineno) { int i,j,k ; int fvalue[POOLSIZE*2] ;//midgeneプールの適応度 int sumf ;//適応度の合計値 int point=0 ;//ルーレットのスタート場所 int midpoint ; setfvalue(midgene,fvalue,lines,lineno) ;//fvalueに値をセット sumf=sumupfvalue(fvalue) ;//適応度の合計値を計算 for(i=0;i<POOLSIZE;++i){//ルーレットにしたがって選択 midpoint=roulette(fvalue,sumf,point) ; for(j=0;j<RULESIZE;++j) for(k=0;k<LOCUSSIZE;++k) gene[i][j][k]=midgene[midpoint][j][k]; } }
void MPILock::try_request_token(MPIResource *resource, vector<unsigned> &choices) { for (unsigned i = 0; i < choices.size();) { if (resource->has_any_tokens(choices[i])) { i += 1; } else { choices.erase(choices.begin() + i); } } if (choices.empty()) { return; } { unsigned side_index = roulette(resource, choices); resource->remove_token(side_index); MPIRequestMessage message(resource->get_type()); interface->send_request(sides[side_index], &message); } }
unsigned int GraphComponent::chooseResource(std::vector<unsigned long> & ram, double pherDeg, double heurDeg) { unsigned int size = physArcs.size(); std::vector<double> roulette(size); double value = 0, sum = 0; double maxHeur = heurCalc->getMax(); for (unsigned int i = 0; i < size; i ++) { if (ZERO(physArcs[i]->heur+1) || ZERO(physArcs[i]->heur) || physArcs[i]->heur < 0 || (type == VMACHINE && ram[i] < ramRequired)) value = 0; else value = pow(physArcs[i]->pher, pherDeg)*pow(physArcs[i]->heur/maxHeur, heurDeg); // std::cerr << "resulting heur was " << physArcs[i]->heur/maxHeur << '\n'; sum += value; roulette[i] = sum; } if (ZERO(sum)) return size+1; double choose = rand()/(double)RAND_MAX * sum; /* std::cerr << "physArcs = "; for (int q = 0; q < physArcs.size(); ++ q) std::cerr << physArcs[q]->heur << ' ';*/ for (unsigned int i = 0; i < size; ++ i) if (choose < roulette[i]) return i; return size+1; }
int GAConjProblemForORGroupSolver::reproduction( ) { int pr = ( theIter2<2*numGenes ? 0 : 1 ); switch( roulette( 3 , prob[pr] ) ) { case 0: { int g = selectGene( ); *newGene[0] = *genes[g]; if( newGene[0]->mutation( ) ) return 1; } break; case 1: { int g = selectGene( ); *newGene[0] = *genes[g]; if( newGene[0]->permutation( ) ) return 1; } break; case 2: { int g1 = selectGene( ); int g2; { GACPforORGSolverGene *_tmp = genes[g1]; genes[g1] = 0; g2 = selectGene( ); genes[g1] = _tmp; } *newGene[0] = *genes[g1]; *newGene[1] = *genes[g2]; if( crossover( *newGene[0] , *newGene[1] ) ) return 2; } break; } return 0; }
unsigned int InternalGraph::selectVertex(AntPath* pt, unsigned int cur, std::set<unsigned int> & available, bool& s, std::map<Element *, std::set<Link *> >& chan) { // choose request unsigned int vertex = 0; unsigned int size = available.size(); std::vector<double> roulette(size); std::vector<unsigned int> rouletteIndex(size); double value = 0, sum = 0; unsigned int index = 0; std::set<unsigned int>::iterator itEnd = available.end(); for (std::set<unsigned int>::iterator i = available.begin(); i != itEnd; i ++, index ++) { value = pow(arcs[cur][*i]->pher, pherDeg)*pow(arcs[cur][*i]->heur, heurDeg); sum += value; roulette[index] = sum; rouletteIndex[index] = *i; } double choose = rand()/(double)RAND_MAX * sum; if (ZERO(sum)) { std::set<unsigned int>::iterator sel = available.begin(); vertex = *sel; available.erase(sel); } else { for (unsigned int i = 0; i < size; ++ i) { if (choose < roulette[i]) { vertex = rouletteIndex[i]; unsigned int res = available.erase(rouletteIndex[i]); assert(res == 1); break; } } } // choose resource GraphComponent * gc = vertices[vertex-1]; unsigned int res = gc->chooseResource(curNodesRam, pherDeg, heurDeg); if (res >= gc->getResNum()) { // failed to choose a resource s = false; return vertex; } if (gc->getType() == GraphComponent::VMACHINE) { curNodesRes[res] -= gc->getRequired(); curNodesRam[res] -= gc->getRequiredRam(); updateInternalHeuristic(res, GraphComponent::VMACHINE); std::map<Element *, std::set<Link *> >::iterator iter = chan.find(gc->getPointer()); std::set<Link *> * chanPtr = (iter != chan.end()) ? &(iter->second) : NULL; pt->addElement(new PathElement(vertex, gc->getPointer(), res, physNodes[res], chanPtr)); } else if (gc->getType() == GraphComponent::STORAGE) { curStoresRes[res] -= gc->getRequired(); updateInternalHeuristic(res, GraphComponent::STORAGE); std::map<Element *, std::set<Link *> >::iterator iter = chan.find(gc->getPointer()); std::set<Link *> * chanPtr = (iter != chan.end()) ? &(iter->second) : NULL; pt->addElement(new PathElement(vertex, gc->getPointer(), res, physStores[res], chanPtr)); } s = true; return vertex; }
/**Function******************************************************************** Synopsis [Performs the crossover between two parents.] Description [Performs the crossover between two randomly chosen parents, and creates two children, x1 and x2. Uses the Partially Matched Crossover operator.] SideEffects [None] SeeAlso [] ******************************************************************************/ static int PMX( int maxvar) { int cut1,cut2; /* the two cut positions (random) */ int mom,dad; /* the two randomly chosen parents */ int *inv1; /* inverse permutations for repair algo */ int *inv2; int i; /* loop vars */ int u,v; /* aux vars */ inv1 = ALLOC(int,maxvar); if (inv1 == NULL) { return(0); } inv2 = ALLOC(int,maxvar); if (inv2 == NULL) { FREE(inv1); return(0); } /* Choose two orders from the population using roulette wheel. */ if (!roulette(&mom,&dad)) { FREE(inv1); FREE(inv2); return(0); } /* Choose two random cut positions. A cut in position i means that ** the cut immediately precedes position i. If cut1 < cut2, we ** exchange the middle of the two orderings; otherwise, we ** exchange the beginnings and the ends. */ cut1 = rand_int(numvars-1); do { cut2 = rand_int(numvars-1); } while (cut1 == cut2); #if 0 /* Print out the parents. */ (void) fprintf(table->out, "Crossover of %d (mom) and %d (dad) between %d and %d\n", mom,dad,cut1,cut2); for (i = 0; i < numvars; i++) { if (i == cut1 || i == cut2) (void) fprintf(table->out,"|"); (void) fprintf(table->out,"%2d ",STOREDD(mom,i)); } (void) fprintf(table->out,"\n"); for (i = 0; i < numvars; i++) { if (i == cut1 || i == cut2) (void) fprintf(table->out,"|"); (void) fprintf(table->out,"%2d ",STOREDD(dad,i)); } (void) fprintf(table->out,"\n"); #endif /* Initialize the inverse permutations: -1 means yet undetermined. */ for (i = 0; i < maxvar; i++) { inv1[i] = -1; inv2[i] = -1; } /* Copy the portions whithin the cuts. */ for (i = cut1; i != cut2; i = (i == numvars-1) ? 0 : i+1) { STOREDD(popsize,i) = STOREDD(dad,i); inv1[STOREDD(popsize,i)] = i; STOREDD(popsize+1,i) = STOREDD(mom,i); inv2[STOREDD(popsize+1,i)] = i; } /* Now apply the repair algorithm outside the cuts. */ for (i = cut2; i != cut1; i = (i == numvars-1 ) ? 0 : i+1) { v = i; do { u = STOREDD(mom,v); v = inv1[u]; } while (v != -1); STOREDD(popsize,i) = u; inv1[u] = i; v = i; do { u = STOREDD(dad,v); v = inv2[u]; } while (v != -1); STOREDD(popsize+1,i) = u; inv2[u] = i; } #if 0 /* Print the results of crossover. */ for (i = 0; i < numvars; i++) { if (i == cut1 || i == cut2) (void) fprintf(table->out,"|"); (void) fprintf(table->out,"%2d ",STOREDD(popsize,i)); } (void) fprintf(table->out,"\n"); for (i = 0; i < numvars; i++) { if (i == cut1 || i == cut2) (void) fprintf(table->out,"|"); (void) fprintf(table->out,"%2d ",STOREDD(popsize+1,i)); } (void) fprintf(table->out,"\n"); #endif FREE(inv1); FREE(inv2); return(1); } /* end of PMX */
bool GAConjProblemForORGroupSolver::tournament( GACPforORGSolverGene &gene ) { double newFit = gene.fitness( ); // number of last iterations with conjecture // I do next iteration through 1000 iterations static int it = theIter1; if( newFit==0 ) { bestFit = 0; lastImprovement = 0; if( file ) *file << "Generation " << theIter1 << ", best fitness " << bestFit << endl << endl; return false; } if( gene.getHasShorterWords( ) ) { if( file ) *file << "Given words can be shortened." << endl << endl; toStart( gene.getWord1( ) , gene.getWord2( ) ); theIter2 = 0; return true; } //Conjecture if( gene.getHasConjecture( ) && theIter1 - it>1000 ) { Word conjWord = gene.getConjectureWord( ); int nCheck = 1; if( checkedWords.bound(conjWord) ) nCheck = checkedWords.valueOf( conjWord )+1; if( theIter1 - it > 1000*nCheck ) { checkedWords.bind( conjWord , nCheck ); if( file ) { *file << "The algorithm will try to check whether "; theGroup.printWord( *file , conjWord ); *file << " is trivial."; *file << endl << endl; } GAConjProblemForORGroupConjecture conjecture( theGroup , conjWord , file ); bool conjResult = conjecture.isConj( 1000 , theIter1 ); it = theIter1; if( conjResult ) { bestFit = 0; lastImprovement = 0; if( file ) { *file << "The word is trivial." << endl << endl; *file << "Generation " << theIter1 << ", best fitness " << bestFit << endl << endl; } return false; } if( file ) *file << "The algorithm couldn't determine whether the word was trivial." << endl << endl; } } // get random chromosome and compare it with the new one by roulette wheel int g = rnd1( numGenes ); if( newFit<bestFit ) { delete genes[g]; genes[g] = new GACPforORGSolverGene( gene ); bestFit = newFit; lastImprovement = 0; if( file ) *file << "Generation " << theIter1 << ", best fitness " << bestFit << endl << endl; return false; } if( !genes[g] ) genes[g] = new GACPforORGSolverGene( gene ); else { double prob1 = newFit, prob2 = genes[g]->fitness( ); double min = ( prob1<prob2 ? prob1 : prob2 ); if( min>5 ) { prob1 -= min - 5; prob2 -= min - 5; } prob1 += fitnessRate; prob2 += fitnessRate; if( (roulette( prob1 , prob2 )==1 ) ) { delete genes[g]; genes[g] = new GACPforORGSolverGene( gene ); } } return false; }
int GAConjProblemForORGroupSolver::roulette( double d1 , double d2 ) { double d[2] = {d1 , d2}; return roulette( 2 , d ); }
/*MONTE CARLO*/ void mc1m(int num_photons,double ma, double ms, double g, double *x0,double *x1, double *x2, double *u0, double *u1, double *u2, double *na_fiber, double r_max, double x2_max,double n_tissue, double *n_fiber, double *fiber_radii, int t_grid, double *th, double *ph,double tissue[],double fiber_tissue[], double r[],double depth[],double weight[],double path[], double z[],double num_scatt[]) { int i; double s = 0; /*Fiber NA*/ float na_clad = na_fiber[1]; float na_core = na_fiber[0]; /*Fiber refractive indices*/ float n_clad = n_fiber[1]; float n_core = n_fiber[0]; /*Maximum angle for detection*/ double theta_clad = asin(na_clad/n_tissue); double Ralphi; /*ran1 seed*/ srand ( time(NULL) ); long idum = -(rand() % 1000 +1); /*Image array*/ int t_grid0 = t_grid*r_max; int t_grid2 = t_grid*x2_max; double dim_arr = t_grid0*t_grid2; double *aux_tissue = malloc(dim_arr*sizeof(double)); double r_tissue; /*Fibre geometry*/ double r_dclad = fiber_radii[2]; double r_clad = fiber_radii[1]; double r_core = fiber_radii[0]; /*Tissue and fiber_tissue initialization for each monte carlo run*/ int it,jt, count=0; for (it = 0; it< t_grid2; it++){ for (jt = 0; jt< t_grid0; jt++){ *(tissue+count) = 0; *(fiber_tissue+count) = 0; count++;}} /*Auxiliar arrays initialization*/ int ji,count2=0; for (ji = 0; ji< num_photons; ji++){ *(r+count2) = 0; *(depth+count2) = 0; *(weight+count2) = 0; *(path+count2) = 0; *(z+count2) = 0; *(num_scatt+count2)=0; count2++;} /*LAUNCHING*/ for (i=0;i<num_photons;i++) { int status=1; /*Photon alive*/ double x[]={x0[i],x1[i],x2[i]}; /*Position*/ double u[]={u0[i],u1[i],u2[i]}; /*Direction*/ double path_pp=0; /*Pathlength*/ double weight_pp=1; /*Weigth*/ double num_pp = 0; double depth_pp=0; /*Maximum depth*/ double dw=0; /*Weigth lost*/ double fiber_boundary; double z_na, r_na, cone; /*Specular reflection*/ specular(n_core, n_tissue,&weight_pp); /*aux_ tissue initialization for each photon*/ int count1 = 0,j; for (it = 0; it< t_grid2; it++){ for (jt = 0; jt< t_grid0; jt++){ *(aux_tissue+count1)=0; count1++;}} while (status==1) { /*Propagation distance*/ if (s == 0){s=log(ran1(&idum))/(-(ma+ms));} int tz0=0; int tz2=0; /*HIT FIBER BOUNDARY*/ fiber_boundary = -x[2]*(ma+ms)/u[2]; /*Position before updating*/ z_na = x[2]; r_na = r_tissue; cone = theta_clad*z_na + r_clad; if (u[2] < 0 && fiber_boundary <= s && z_na >0) { move_s(x, u, fiber_boundary, &depth_pp, &path_pp, &s, &r_tissue,&num_pp); /*whether the photon is internally reflected*/ reflection(u, n_core, n_tissue, &Ralphi); if (ran1(&idum)<= Ralphi){u[2]=-u[2];} } else{ move_s(x, u, s, &depth_pp, &path_pp, &s, &r_tissue, &num_pp); absorption(ma, ms,&weight_pp,&dw); spin_thph(u, g, &idum,th,ph); /*Absortion array updating*/ tz0=floor(r_tissue*t_grid); tz2=floor(x[2]*t_grid); if(tz0>t_grid0-1){tz0=t_grid0-1;} if(tz0<0){tz0=0;} if(tz2>t_grid2-1){tz2=t_grid2-1;} if(tz2<0){tz2=0;} *(tissue+(tz0*t_grid2+tz2))+=dw; *(aux_tissue+(tz0*t_grid2+tz2))+=dw; } /*else (the photon didn't reach the boundary)*/ /*PHOTON TERMINATION*/ if(x[2] > x2_max ){status=0;} if(status==1 && weight_pp<0.00001 /*threshold*/ ){roulette(&weight_pp,&idum,&status);} /*The photon reach the sensing area?*/ if(x[2] < 0 && r_tissue <= r_clad && r_tissue >= r_core && z_na >0 && r_na <= cone){ for(j=0;j<dim_arr;j++){fiber_tissue[j]+=aux_tissue[j];} /*Final status of detected photons*/ r[i] = r_tissue; z[i] = x[2]; path[i] = path_pp; weight[i] = weight_pp; depth[i] = depth_pp; num_scatt[i] = num_pp;} } /*while status is alive*/ } /*for i num_photons launched*/ return; } /*mcml2m*/