double noise1(int x) { int iterations, invpersistence, period_factor, smallest_period; int i; double y; iterations = 8; invpersistence = 2; period_factor = 2; smallest_period = 1; y = 0; for (i = 1; i <= iterations; i++) { double c, period, x_anchor, v0, v1, v2, v3, x_transformed; int x_i; c = 1 / pow(invpersistence, i); period = smallest_period * pow(period_factor, (iterations-i)); x_i = x / period; x_anchor = x_i * period; x_transformed = (x - x_anchor) / period; v0 = nrand(x_i-1, 0, i); v1 = nrand(x_i+0, 0, i); v2 = nrand(x_i+1, 0, i); v3 = nrand(x_i+2, 0, i); y += c * interpolate_cubic(v0, v1, v2, v3, x_transformed); } y *= (invpersistence - 1); return (y+1)/2; }
void Phantom::chooseTarget() { if(status == Idle || status == AtDestination) { bool chosen = false; int rx,ry; while(!chosen) { rx = nrand(0,map->getGridSizeX()-1)%map->getGridSizeX(); ry = nrand(0,map->getGridSizeY()-1)%map->getGridSizeY(); if(!map->honeyPotActive) { if(!map->getRoom(rx,ry)->isGone()) { if( map->getSquare(map->getRoom(rx,ry)->getMidX(),map->getRoom(rx,ry)->getMidY())->getChar()==HALLWAY || map->getSquare(map->getRoom(rx,ry)->getMidX(),map->getRoom(rx,ry)->getMidY())->getChar()==FLOOR || map->getSquare(map->getRoom(rx,ry)->getMidX(),map->getRoom(rx,ry)->getMidY())->getChar()==ENEMYNODE || map->getSquare(map->getRoom(rx,ry)->getMidX(),map->getRoom(rx,ry)->getMidY())->getChar()==NODE ) { chosen = true; targetID = map->getRoom(rx,ry)->getID(); status = Walking; break; } } } else { if(!map->getRoom(rx,ry)->isGone()) { if(map->getRoom(rx,ry)->getNode()->containsFlag(Node::HoneyPot)) { chosen = true; targetID = map->getRoom(rx,ry)->getID(); status = Walking; break; } } } } } }
String strRand(uint8_t min, uint8_t max, uint8_t seed) { char *newString, loopChar; int diff = max - min, size, i; short type; if(diff < 0) { newString = NULL; } else { size = nrand() % (diff+1) + min; newString = (char *) malloc(size + 1); for(i = 0; i < size; i++) { type = nrand() % 3; switch(type) { case 0: //number loopChar = nrand() % 10 + 48; //'0' a '9' break; case 1: //upper loopChar = nrand() % 26 + 65; //'A' a 'Z' break; case 2: //lower loopChar = nrand() % 26 + 97; //'a' a 'b' break; //É possível adicionar outras faixas de caracteres } newString[i] = loopChar; } newString[i] = '\0'; } return newString; }
int main(int argc, char **argv) { if(argc != 5) { std::cout << "USEGE : [genset seed/int size/int scale/int output-filename/string]" <<std::endl; return 0; } std::cout << "RND_MIN : " << 0 << " / RND_MAX : " << RAND_MAX; int seed = atoi(argv[1]); srand(seed); int size = atoi(argv[2]); int scale = atoi(argv[3]); std::vector<int> x(size), y(size); for(int i=0; i<size; ++i) { int a = 0; int b = 0; do { a = nrand(scale); } while(is_member(x, a)); do { b = nrand(scale); } while(is_member(y, b)); x[i] = a; y[i] = b; } std::ofstream fout(argv[4]); if(fout.is_open()) { for(int i=0; i<size; ++i) { fout << x[i] << " " << y[i] << std::endl; } } return 0; }
void initlevel(void) { int i, cnt = 10, x, y; for(x = 0; x < SzX; x++) for(y = 0; y < SzY; y++) ogrid[x][y] = 100; switch(difficulty){ case DEasy: cnt = 10 + nrand(5); break; case DMed: cnt = 5 + nrand(5); break; case DHard: cnt = nrand(5); break; } for(i = 0; i < cnt; i++) { do { x = nrand(SzX); y = nrand(SzY); } while(ogrid[x][y] != 100); ogrid[x][y] = 999; } ogrid[SzX/2][SzY/2] = 1000; memcpy(grid, ogrid, sizeof grid); finished = 0; }
static void chkwinner (enum EPlayer player) { for (unsigned i = 0; i < RANKS; ++i) if (_hand[player][i] > 0 && _hand[player][i] < SUITS) return; draw_panel(); printplayer (player); waddstr (_wmsg, "don't have any more cards!\n\nMy books:"); unsigned cb = countbooks (COMPUTER); waddstr (_wmsg, "Your books:"); unsigned ub = countbooks (USER); wprintw (_wmsg, "\nI have %d, you have %d.\n", cb, ub); if (ub > cb) { waddstr (_wmsg, "\nYou win!!!\n"); if (!nrand(64)) waddstr (_wmsg, "Cheater, cheater, pumpkin eater!\n"); } else if (cb > ub) { waddstr (_wmsg, "\nI win!!!\n"); if (!nrand(64)) waddstr (_wmsg, "Hah! Stupid peasant!\n"); } else waddstr (_wmsg, "\nTie!\n"); wgetch (_wmsg); exit (EXIT_SUCCESS); }
Effect* EffectFactory::createRandomEffect() { int region = nrand( 1, 10 ); if ( region >= 1 && region <= 3 ) { int val = nrand( 1, 10 ); switch ( val ) { case 1: case 2: return createAccelerateEffect(); case 3: case 4: return createFrozenEffect(); case 5: case 6: return createSlimEffect(); case 7: case 8: return createSlowDownEffect(); case 9: return createTurnEffect(); case 10: return createStealScoreEffect(); default: break; } } return createNullEffect(); }
void Level::spawnLevel() { setupSettingsBasedGlobals(); generateTerrain(terrain); cannonL.live(); cannonR.live(); is_a_player_dead = false; // find placement for left cannon, top ground pixel at randomized x int cannonL_cx = 100 + nrand(200); // center x of cannon auto lt = std::find_if(terrain.begin(), terrain.end(), [&cannonL_cx](Pixel p) { if (p.x == cannonL_cx && p.status) return true; else return false; }); cannonL.setPosition(cannonL_cx - CANNON_WIDTH/2, lt->y - CANNON_HEIGHT); fixTerrain(terrain, cannonL.getRect()); // find placement for right cannon, top ground pixel at randomized x int cannonR_cx = 500 + nrand(200); auto rt = std::find_if(terrain.begin(), terrain.end(), [&cannonR_cx](Pixel p) { if (p.x == cannonR_cx && p.status) return true; else return false; }); cannonR.setPosition(cannonR_cx - CANNON_WIDTH/2, rt->y - CANNON_HEIGHT); fixTerrain(terrain, cannonR.getRect()); // find positions for obstacles // make sure they don't collide with cannons or themselves std::vector<SDL_Rect *> rects; rects.push_back(cannonL.getRect()); rects.push_back(cannonR.getRect()); for (int i = 0; i < gObstacleTotal; i++) { obstacles[i].findPosition(terrain, rects); if (i < 10) // don't worry about trees colliding after 10+ obstacles rects.push_back(obstacles[i].getRect()); } missed_left = false; missed_right = false; missed_distance = 0; last_ai_angle = -60.0; last_ai_shot_dt = 1.0; // copy terrain vector to SDL_Points array for faster rendering copyTerrainToPointsArray(); }
static inline uint32_t do_congruential(void) { /* REVISIT: We could probably generate a 32-bit value with a single * call to nrand(). */ return (uint32_t)nrand(65536L) << (uint32_t)nrand(65536L); }
void local_coordinate_vector_diffusion(double *u_second_1, double *u_second_2, double *u_second_3) { double theta_d, phi_d; phi_d = 2.0 * PI * nrand(); theta_d = acos(sqrt(nrand())); *u_second_1 = sin(theta_d) * cos(phi_d); *u_second_2 = sin(theta_d) * sin(phi_d); *u_second_3 = cos(theta_d); }
void determine_direction(double *v_x, double *v_y, double *v_z) { double cos_theta,sin_theta,phi; phi = 2 * PI * nrand(); cos_theta = 1 - 2 * nrand(); sin_theta = sqrt(1 - pow(cos_theta,2)); *v_x = sin_theta * cos(phi); *v_y = sin_theta * sin(phi); *v_z = cos_theta; //printf("vx:%f\n",*v_x); }
int zzz(void) { int oldtime; int n; oldtime = ourtime; if ((snooze - ourtime) < (0.75 * CYCLE)) { ourtime += 0.75 * CYCLE - (snooze - ourtime); printf("<zzz>"); for (n = 0; n < ourtime - oldtime; n++) printf("."); printf("\n"); snooze += 3 * (ourtime - oldtime); if (notes[LAUNCHED]) { fuel -= (ourtime - oldtime); if (location[position].down) { position = location[position].down; crash(); } else notes[LAUNCHED] = 0; } if (OUTSIDE && nrand(100) < 50) { puts("You are awakened abruptly by the sound of someone nearby."); switch (nrand(4)) { case 0: if (ucard(inven)) { n = nrand(NUMOFOBJECTS); while (!testbit(inven, n)) n = nrand(NUMOFOBJECTS); clearbit(inven, n); if (n != AMULET && n != MEDALION && n != TALISMAN) setbit(location[position].objects, n); carrying -= objwt[n]; encumber -= objcumber[n]; } puts("A fiendish little Elf is stealing your treasures!"); fight(ELF, 10); break; case 1: setbit(location[position].objects, DEADWOOD); break; case 2: setbit(location[position].objects, HALBERD); break; default: break; } } } else return 0; return 1; }
void choosepiece(void) { int i; do { i = nrand(NP); setpiece(&pieces[i]); pos = rboard.min; pos.x += nrand(NX)*pcsz; } while(collide(Pt(pos.x, pos.y+pcsz-DY), piece)); drawpiece(); flushimage(display, 1); }
double noise2(int x, int y) { // z = SUM( noise at x y for each iteration ) // Each iteration zooms out by a given factor (period_factor), and // decreases in intensity by a given factor (invpersistence) // The first iteration is smallest_period*smallest_period in size int iterations, smallest_period; double invpersistence, period_factor; int i; double z; iterations = 10; invpersistence = 1.1; period_factor = 2; smallest_period = 1; z = 0; for (i = 1; i <= iterations; i++) { double c, period, v0, v1, v2, v3; double x_anchor, x_transformed, y_anchor, y_transformed; int x_i, y_i; c = 1 / pow(invpersistence, i); // period = how many pixels wide the squares are period = smallest_period * pow(period_factor, (iterations-i)); // x_i and y_i uniquely identify a random value for an iteration x_i = x / period; x_anchor = x_i * period; x_transformed = (x - x_anchor) / period; y_i = y / period; y_anchor = y_i * period; y_transformed = (y - y_anchor) / period; // nrand(x, y, i) calculates the noise for iteration i at point (x,y) // We get the noise then do diamond interpolation on four points v0 = nrand(x_i+0, y_i+0, i) * max(0, 2-x_transformed-y_transformed-1); v1 = nrand(x_i+1, y_i+0, i) * max(0, 1+x_transformed-y_transformed-1); v2 = nrand(x_i+0, y_i+1, i) * max(0, 1-x_transformed+y_transformed-1); v3 = nrand(x_i+1, y_i+1, i) * max(0, 0+x_transformed+y_transformed-1); z += c * (v0 + v1 + v2 + v3)/2; } // The maximum of z is sum(1/invpersistence^i, i=0..inf) = (invpersistence-1) // However, since we averaged many random values, z is already (usually) in the right range // z *= (invpersistence - 1); if (z > 1) z = 1; if (z < -1) z = -1; return (z+1)/2.0; }
static unsigned compmove (void) { for (unsigned i = 0; i < RANKS; ++i) { if (_asked[USER][i] && _hand[COMPUTER][i] > 0 && _hand[COMPUTER][i] < SUITS) { _asked[USER][i] = false; return i; } } if (!nrand(3)) { unsigned i, max; for (i = 0;; ++i) { if (_hand[COMPUTER][i] && _hand[COMPUTER][i] != SUITS) { max = i; break; } } while (++i < RANKS) if (_hand[COMPUTER][i] != SUITS && _hand[COMPUTER][i] > _hand[COMPUTER][max]) max = i; return max; } for (;;) { for (unsigned i = 0; i < RANKS; ++i) if (_hand[COMPUTER][i] && _hand[COMPUTER][i] != SUITS && !_asked[COMPUTER][i]) return i; for (unsigned i = 0; i < RANKS; ++i) _asked[COMPUTER][i] = false; } }
bool rjMcMC1DSampler::propose_move(rjMcMC1DModel& mcur, rjMcMC1DModel& mpro) { np_move++; size_t n = mcur.nlayers(); if (n <= 1)return false; size_t index = irand((size_t)1, n - 1); double pold = mcur.layers[index].ptop; //double std = sd_move; double std = DEFAULTMOVESTDFRACTION*pold; double pnew = pold + std*nrand(); double qpdfforward = gaussian_pdf(pold, pold*DEFAULTMOVESTDFRACTION, pnew); double qpdfreverse = gaussian_pdf(pnew, pnew*DEFAULTMOVESTDFRACTION, pold); bool isvalid = mpro.move_interface(index, pnew); if (isvalid == false)return false; set_misfit(mpro); double pqratio = qpdfreverse / qpdfforward; double logpqratio = log(pqratio); double loglr = -(mpro.misfit() - mcur.misfit()) / 2.0; double logar = logpqratio + loglr; double logu = log(urand()); if (logu < logar){ na_move++; return true; } return false; }
void run(void (*fn)(char*, char*), Channel *c) { int i, t, j, packets; char *buf2, *buf; buf2 = vtmalloc(blocksize); buf = vtmalloc(blocksize); cur = 0; packets = totalbytes/blocksize; if(maxpackets == 0) maxpackets = packets; order = vtmalloc(packets*sizeof order[0]); for(i=0; i<packets; i++) order[i] = i; if(permute){ for(i=1; i<packets; i++){ j = nrand(i+1); t = order[i]; order[i] = order[j]; order[j] = t; } } for(i=0; i<packets && i<maxpackets; i++){ memmove(buf, template, blocksize);
int main (void) { initialize_curses(); initialize_field_window(); bdinit (_board); // Randomly choose who goes first enum { USER, // get input from standard input PROGRAM // get input from program }; unsigned input[2]; _humanPlayer = nrand(2); input[_humanPlayer] = USER; input[!_humanPlayer] = PROGRAM; _plyr[_humanPlayer] = "you"; _plyr[!_humanPlayer] = "me"; for (unsigned color = BLACK;; color = !color) { bdisp(); unsigned curmove; if (input[color] == USER) curmove = _lastHumanMove = usermove(); else curmove = _lastComputerMove = pickmove (color); int mv = makemove(color, curmove); if (mv != MOVEOK) { // Game finished. Display result and quit. if (mv != RESIGN) display_game_result_message (mv, input[color] == USER); break; } } return EXIT_SUCCESS; }
int find(int* a, int n, int x, int k) { int i = 0; int p; while (i++<k) { if (a[p=nrand(n)]==x) return p; } return -1; }
void nextglenda(void) { int min =1000, next, dir, nextdir = 0, count = 0; Point p = findglenda(); calc(); calc(); calc(); grid[p.x][p.y] = 1000; for(dir = NE; dir <= NW; dir++) { next = checknext(dir, p.x, p.y); if(next < min) { min = next; nextdir = dir; ++count; } else if(next == min) { nextdir = (nrand(++count) == 0)?dir:nextdir; } } if(min < 100) domove(nextdir, p.x, p.y); else finished = Won; if(eqpt(findglenda(), Pt(-1, -1))) finished = Lost; }
s_texmod get_texture2(s_mat mat, vec3 pos, vec3 normal) { int val; vec3 tmp; vec4 v; tmp = pos / mat.m_param.xyz; if (mat.m_id == RTILES) { tmp += sin(tmp); if (INT(floor(tmp.x) + floor(tmp.y) + floor(tmp.z)) % 2 == 1) return (S_TEXMOD(mat.m_color, normal, mat.m_prop.x, mat.m_prop.y)); } if (mat.m_id == RAND) { tmp = tmp * nrand(floor(tmp * mat.m_param.w) / mat.m_param.w); if (INT(floor(tmp.x) + floor(tmp.y) + floor(tmp.z)) % 2 == 1) return (S_TEXMOD(mat.m_color, normal, mat.m_prop.x, mat.m_prop.y)); } if (mat.m_id == PERLIN) { v.x = noise(tmp, 5); return (S_TEXMOD(mix(mat.color, mat.m_color, v.x), normal, mix(mat.smoothness, mat.m_prop.x, v.x), mix(mat.metallic, mat.m_prop.y, v.x))); } return (S_TEXMOD(mat.color, normal, mat.smoothness, mat.metallic)); }
// xworkdir creates a new temporary directory to hold object files // and returns the name of that directory. char* xworkdir(void) { Buf b; char *p; int fd, tries; binit(&b); fd = 0; for(tries=0; tries<1000; tries++) { bprintf(&b, "/tmp/go-cbuild-%06x", nrand((1<<24)-1)); fd = create(bstr(&b), OREAD|OEXCL, 0700|DMDIR); if(fd >= 0) goto done; } fatal("xworkdir create"); done: close(fd); p = btake(&b); bfree(&b); return p; }
void set_1d_ordered_connection(){ int i,j; for (i = 1; i <= N_INPUTS; i++) { for (j = N_INPUTS+1; j <= N_NEURONS; j++) { if ( j == i + N_INPUTS){ W[i][j] = 1.0; } else{ W[i][j] = 0.0; } W[j][i] = W[i][j]; } } /* add noise */ for (i = 1; i <= N_INPUTS; i++) { for (j = N_INPUTS+1; j <= N_NEURONS; j++) { W[i][j] += SIGMA*nrand(); W[j][i] = W[i][j]; } } }
/* * Compute intensity ('color') of extended light source 'lp' from 'pos'. */ static int ExtendedIntens( LightRef lr, Color *lcolor, ShadowCache *cache, Ray *ray, Float /*dist*/, int noshadow, Color *color) { Extended *lp = (Extended*)lr; Float jit, vpos, upos, lightdist; Ray newray; Vector Uaxis, Vaxis, ldir; if (noshadow) { *color = *lcolor; return TRUE; } newray = *ray; /* * Determinte two orthoganal vectors that lay in the plane * whose normal is defined by the vector from the center * of the light source to the point of intersection and * passes through the center of the light source. */ VecSub(lp->pos, ray->pos, &ldir); VecCoordSys(&ldir, &Uaxis, &Vaxis); jit = 2. * lp->radius * Sampling.spacing; /* * Sample a single point, determined by SampleNumber, * on the extended source. */ vpos = -lp->radius + (ray->sample % Sampling.sidesamples)*jit; upos = -lp->radius + (ray->sample / Sampling.sidesamples)*jit; vpos += nrand() * jit; upos += nrand() * jit; VecComb(upos, Uaxis, vpos, Vaxis, &newray.dir); VecAdd(ldir, newray.dir, &newray.dir); lightdist = VecNormalize(&newray.dir); return !Shadowed(color, lcolor, cache, &newray, lightdist, noshadow); }
void main(int argc, char *argv[]) { VtSession *z; int i, j, t; int start; uchar buf[BlockSize]; srand(time(0)); ARGBEGIN{ case 'r': rflag++; break; case 'n': nblock = atoi(ARGF()); break; }ARGEND for(i=0; i<nblock; i++) perm[i] = i; if(rflag) { for(i=0; i<nblock; i++) { j = nrand(nblock); t = perm[j]; perm[j] = perm[i]; perm[i] = t; } } if(readn(0, data, VtScoreSize*nblock) < VtScoreSize*nblock) sysfatal("read failed: %r"); vtAttach(); z = vtDial("iolaire2"); if(z == nil) sysfatal("cound not connect to venti"); if(!vtConnect(z, 0)) vtFatal("vtConnect: %s", vtGetError()); print("starting\n"); start = times(0); if(rflag && nblock > 10000) nblock = 10000; for(i=0; i<nblock; i++) { if(vtRead(z, data+perm[i]*VtScoreSize, VtDataType, buf, BlockSize) < 0) vtFatal("vtRead failed: %d: %s", i, vtGetError()); } print("time = %f\n", (times(0) - start)*0.001); vtClose(z); vtDetach(); }
bool rjMcMC1DSampler::propose_birth(rjMcMC1DModel& mcur, rjMcMC1DModel& mpro) { np_birth++; size_t n = mcur.nlayers(); if (n >= nl_max)return false; double pos = urand(0.0, pmax); size_t index = mcur.which_layer(pos); double vold = mcur.layers[index].value; double vnew, pqratio; if (mBirthDeathFromPrior){ vnew = urand(vmin, vmax); pqratio = 1.0; } else{ double vcpdf; double logstd = DEFAULTLOGSTDDECADES; if (param_value == LINEAR){ double m = (pow(10.0, logstd) - pow(10.0, -logstd)) / 2.0; vnew = vold + m*vold*nrand(); vcpdf = gaussian_pdf(vold, m*vold, vnew); } else{ vnew = vold + logstd*nrand(); vcpdf = gaussian_pdf(vold, logstd, vnew); } pqratio = 1.0 / ((vmax - vmin)*vcpdf); } //pqratio *= (double)(n) / double(n + 1); bool isvalid = mpro.insert_interface(pos, vnew); if (isvalid == false)return false; set_misfit(mpro); double logpqratio = log(pqratio); double loglikeratio = -(mpro.misfit() - mcur.misfit()) / 2.0; double logar = logpqratio + loglikeratio; if (log(urand()) < logar){ na_birth++; return true; } return false; }
int main(void) { GLFWwindow* window; srand((unsigned int) time(NULL)); glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); window = glfwCreateWindow(640, 480, "Event Wait Timeout Test", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); gladLoadGL(glfwGetProcAddress); glfwSetKeyCallback(window, key_callback); while (!glfwWindowShouldClose(window)) { int width, height; float r = nrand(), g = nrand(), b = nrand(); float l = (float) sqrt(r * r + g * g + b * b); glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); glClearColor(r / l, g / l, b / l, 1.f); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window); glfwWaitEventsTimeout(1.0); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
/* * randomly don't send packets */ static void doipoput(Conv *c, Fs *f, Block *bp, int x, int ttl, int tos) { Rudpcb *ucb; ucb = (Rudpcb*)c->ptcl; if(ucb->randdrop && nrand(100) < ucb->randdrop) freeblist(bp); else ipoput4(f, bp, x, ttl, tos, nil); }
void mySend(Chan *c) { for (;;) { for (int r = nrand(10); r >= 0; r--) { usleep(10); } eb_chan_send(c->sc, (const void *)((intptr_t)c->sv)); if (sendOnChan(c)) { break; } } changeNproc(-1); }
static char* espconnect(Conv *c, char **argv, int argc) { char *p, *pp, *e = nil; uint32_t spi; Espcb *ecb = (Espcb*)c->ptcl; switch(argc) { default: e = "bad args to connect"; break; case 2: p = strchr(argv[1], '!'); if(p == nil){ e = "malformed address"; break; } *p++ = 0; if (parseip(c->raddr, argv[1]) == -1) { e = Ebadip; break; } findlocalip(c->p->f, c->laddr, c->raddr); ecb->incoming = 0; ecb->seq = 0; if(strcmp(p, "*") == 0) { qlock(c->p); for(;;) { spi = nrand(1<<16) + 256; if(convlookup(c->p, spi) == nil) break; } qunlock(c->p); ecb->spi = spi; ecb->incoming = 1; qhangup(c->wq, nil); } else { spi = strtoul(p, &pp, 10); if(pp == p) { e = "malformed address"; break; } ecb->spi = spi; qhangup(c->rq, nil); } nullespinit(ecb, "null", nil, 0); nullahinit(ecb, "null", nil, 0); } Fsconnected(c, e); return e; }