Example #1
0
int Application::Run(TestCases::TestCase p_testCase)
{
	m_Al_The_Croc = new MemoryAllocator(p_testCase.customAllocation);
	
	if(p_testCase.functionFlag == 1)
	{		
		unsigned int numberOfThreads = p_testCase.nrThreads;

		m_pool = m_Al_The_Croc->CreatePool<Particle>(p_testCase.pool.nrOfBlocks, p_testCase.alignment, numberOfThreads == 1 ? false : true);
		m_pool->init();

		srand (time(NULL));
		std::thread* thread = new std::thread[numberOfThreads];

		for(int i = 0; i < numberOfThreads; i++) {
			threadParam params;
			params.emissionRate = rand() % 10000 + 1000;
			params.freeBlocks = 0;
			params.runTime = p_testCase.pool.runTime;
			params.pool = m_pool;
			thread[i] = std::thread(PoolTest, params);
		}
		for(int i = 0; i < numberOfThreads; i++) {
			thread[i].join();
		}
	}
	else if(p_testCase.functionFlag == 2)
	{
		unsigned int numberOfThreads = p_testCase.nrThreads;

		m_stack = m_Al_The_Croc->CreateStack(TOTAL_SIZE, 4, numberOfThreads == 1 ? false : true); 
		srand (time(NULL));

		std::thread* thread = new std::thread[numberOfThreads];

		unsigned int* pixmap;
		if(p_testCase.customAllocation)
			pixmap = reinterpret_cast<unsigned int*>(m_stack->Push<unsigned int[WIDTH*HEIGHT]>());
		else
			pixmap = (unsigned int*)malloc(TOTAL_SIZE);	

		for(int i = 0; i < numberOfThreads; i++) 
		{
			threadParam params;
			params.al_the_croc = m_Al_The_Croc;
			params.stack = m_stack;
			params.customAllocation = p_testCase.customAllocation;
			params.id = i;
			params.pixmap = pixmap;
			thread[i] = std::thread(StackTest, params);
		}

		for(int i = 0; i < NUM_THREADS; i++) {
			thread[i].join();
		}
		//writeTga(pixmap, WIDTH, HEIGHT, "image.tga");
	}

	return (int)StopCode::CleanStop;
}
Example #2
0
// Funktion som fråga efter ett frö till slumpgeneratörn 
// (om en 1:a anges ska ett slumpmässigt frö användas).
void throwDice(int dice[], int nrOfDice, int nrOfDieValues)
{
    int seed;
    int i;
    
    // Fråga efter ett frö.
    printf("Enter seed (1 gives a random seed): ");
    scanf("%d", &seed);
    
    // Om valet är 1 så slumpas ett frö.
    if (seed == 1)
    {
        srand(time(NULL));
    }
    
    // Om inte används de frö som användaren angivit.
    else
    {
        srand(seed);
    }
    
    // För varje tärning.
    // Ta fram ett slumptal mellan 1 och 6 (nrOfDieValues).
    for (i = 0; i < nrOfDice; i++)
    {
        dice[i] = rand() % 6 + 1;
    }
    
    printf("\n");
}
Example #3
0
int main() {
  double result;
  double bestsofar = -999;
  double bestA[10];
  double ss[10];
  int i;
  while(result < 9 && numeval <= NUMEVAL) {
    srand(time(NULL));
    result = geneticAlgorithm(ss);
    if(result > bestsofar) {
      bestsofar = result;
      memcpy(bestA,ss,sizeof(double)*10);
    }
    printf("\nBestSoFarGeneral: %lf No. Eval: %d \n", bestsofar,numeval);
  }

  while(result < 10 && numeval <= NUMEVAL) {
    srand(time(NULL));
    result = simulatedAnnealing(300000,ss);
    if(result > bestsofar) {
      bestsofar = result;
      memcpy(bestA,ss,sizeof(double)*10);
    }
    for(i = 0; i < 10; i++){
      printf("\nBSF[%d]: %lf",i,bestA[i]);
    }
    printf("\nBestSoFarGeneral: %lf No. Eval: %d \n", bestsofar,numeval);
  }  
}
Example #4
0
int main(int argc, string argv[])
{
    // Verify that the user entered at least 1 argument, but no more than 2, else state usage.
    if (argc != 2 && argc != 3)
    {
        printf("Usage: ./generate n [s]\n");
        return 1;
    }

    // Convert first argument to an integer.
    int n = atoi(argv[1]);

    // Seed rand() with either the users seed, or use the time seed function.
    if (argc == 3)
    {
        srand((unsigned int) atoi(argv[2]));
    }
    else
    {
        srand((unsigned int) time(NULL));
    }

    // Run the rand() fuction and print the output repeatedly until the number of cycles == the requested number of randoms.
    for (int i = 0; i < n; i++)
    {
        printf("%i\n", rand() % LIMIT);
    }

    // that's all folks
    return 0;
}
Example #5
0
Matrix 
Assignment::RandomGenerate(size_t nrows, size_t ncols, int MAX, unsigned int _seed){
 
  //accept new seed for random generator
  if(_seed != SEED)
    srand(_seed);
  else 
    srand(this->seed);
  
  //update data members
  this->num_agents = nrows;
  this->num_tasks = ncols;

  //define a matrix
  Matrix matrix;
  matrix.resize(nrows);
  for(unsigned int i=0; i<nrows; i++)
    matrix[i].resize(ncols);

  //randomly generate
  for(unsigned int i=0; i<nrows; i++)
    for(unsigned int j=0; j<ncols; j++){
      int rdm=rand()%MAX-1; 
      if(rdm<0) rdm = 0;
      matrix[i][j].SetWeight(rdm);
  }      
  return matrix;
}
void				Map::generate_map()
{
  std::ofstream			debug;
  Leaf				_root = Leaf(Size(0, 0), Size(map_size.x, map_size.y));
  std::vector<Rooms>		tmpRooms;

  if (_seed != -1)
    srand(_seed);
  else
    srand(time(NULL));
  debug.open("map.txt");
  _leafs.push_back(_root);
  split();
  for(size_t i = 0; i < _leafs.size();i++)
    _leafs[i].create_rooms(tmpRooms, room_max_size);
  for (int i = 0; i < room_nbr;i++)
    _rooms.push_back(tmpRooms[rand() % tmpRooms.size()]);
  for(size_t i = 0; i < _leafs.size();i++)
    {
      delete(_leafs[i].leftChild);
      delete(_leafs[i].rightChild);
    }
  blank_map();
  draw_rooms();
  draw_better_walls();
  draw_hallways();
  draw_in_out();
  draw_hallways_walls();
  draw_angles();
  for (size_t i = 0; i < _map.size() ; i++)
    debug << _map[i] << std::endl;
  debug.close();
}
Example #7
0
//塵の描画
void draw_Dust() {
	substance *sub = dust.getSub();
	substance *p = player.getSub();
	//乱数を時刻ごとに決める

	//塵の座標をランダムに決めるために、乱数を設定
	unsigned int seed = int(rand() % 1000 + 1);
	srand(0);

	//float range = 20.0f;		  
	int range = 1000;
	for (int i = 0; i < dust.getSize(); i++) {
		//遠くのものは点で描画
		sub[i].x = (float)GetRandom(-DUST_RANGE, DUST_RANGE);
		sub[i].y = (float)GetRandom(-DUST_RANGE, DUST_RANGE);
		sub[i].z = (float)GetRandom(-DUST_RANGE, DUST_RANGE);
		DrawPixel3D(VGet(sub[i].x, sub[i].y, sub[i].z), GetColor(255, 255, 255));

		//近くのものは線で描画 
		sub[i].x = (float)GetRandom(0, DUST_RANGE);
		sub[i].y = (float)GetRandom(0, DUST_RANGE);
		sub[i].z = (float)GetRandom(0, DUST_RANGE);
		sub[i].x = modulo(-p[0].x + sub[i].x, (float)range) - range * 0.5f;
		sub[i].y = modulo(-p[0].y + sub[i].y, (float)range) - range * 0.5f;
		sub[i].z = modulo(-p[0].z + sub[i].z, (float)range) - range * 0.5f;
		DrawLine3D(VGet(sub[i].x, sub[i].y, sub[i].z), 
			VGet(sub[i].x - p[0].vx * (range * 0.001f) + 0.001f, 
			sub[i].y - p[0].vy * (range * 0.001f), 
			sub[i].z - p[0].vz * (range * 0.001f)), 
			GetColor(255, 255, 255));
	}

	srand(seed);
}
Example #8
0
/**
 * @short Initializes the global random number generator
 * 
 * Initializes the global random number generator with some random seed.
 *
 * onion_random_free() must be called later to free up used memory.
 *
 * It is safe to call onion_random_init() more than once, but union_random_free() must be called the same amount of times.
 */
void onion_random_init() {
  onion_random_refcount_mutex_lock();
  if (onion_random_refcount == 0) {
    int fd = open("/dev/random", O_RDONLY);
    if (fd < 0) {
      ONION_WARNING
          ("Unsecure random number generation; could not open /dev/random to feed the seed");
      // Just in case nobody elses do it... If somebody else do it, then no problem.
      srand(time(NULL));
    } else {
      unsigned int sr;
      ssize_t n;
      n = read(fd, &sr, sizeof(sr));
      if (n != sizeof(sr)) {
        ONION_ERROR
            ("Error reading seed value from /dev/random after file descriptor opened");
        exit(1);
      } else {
        close(fd);
        srand(sr);
      }
    }
  }
  onion_random_refcount++;
  onion_random_refcount_mutex_unlock();
}
/**
 Initializes the object.
 
 @return true if initialized correctly, false otherwise
 */
bool IND_Math::init() {
	end();
	freeVars();
 
    //----- Random seed ------
    
#ifdef PLATFORM_LINUX
	struct timespec tp;
	clock_gettime(CLOCK_MONOTONIC, &tp);
	srand(tp.tv_nsec);
#endif
    
    // OS X does not have clock_gettime, use clock_get_time
    // Great solution from StackOverflow:http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x
#if defined (PLATFORM_IOS) || defined (PLATFORM_OSX) 
    struct timespec tp;
    clock_serv_t cclock;
    mach_timespec_t mts;
    host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
    clock_get_time(cclock, &mts);
    mach_port_deallocate(mach_task_self(), cclock);
    tp.tv_sec = mts.tv_sec;
    tp.tv_nsec = mts.tv_nsec;
    srand(static_cast<unsigned>(tp.tv_nsec));
#endif
    
#ifdef PLATFORM_WIN32	 
	srand(GetTickCount());
#endif
	_ok = true;

	return _ok;
}
Example #10
0
void Noise :: setSeed( unsigned int seed )
{
  if ( seed == 0 )
    srand( (unsigned int) time( NULL ) );
  else
    srand( seed );
}
Example #11
0
	void Pop3DigestMd5Mech::GenerateClientNonce(string& cnonce)
	{
		uint64_t rand_num = 0;
		uint64_t rand_num2 = 0;

		pid_t pid = getpid();	
		pthread_t tid = pthread_self();

		srand(pid);
		rand_num += rand_r(reinterpret_cast<unsigned int*>(&pid));

		srand(tid);
		rand_num += rand_r(reinterpret_cast<unsigned int*>(&tid));

		struct timespec cur_time;
		clock_gettime(CLOCK_REALTIME, &cur_time);

		rand_num += cur_time.tv_sec;
		srand(cur_time.tv_sec);
		rand_num2 += rand_r(reinterpret_cast<unsigned int*>(&cur_time.tv_sec));
		rand_num2 += cur_time.tv_nsec;

		rand_num2 = rand_num2 << 32;
		rand_num |= rand_num2;

		stringstream ss;
		cnonce = ss.str();
		string temp = "";
		Pop3AuthCommon::Base64Encode(cnonce, temp);

		cnonce = temp;

		POP3_DEBUG_INFO1("D-MD5 client nonce = %s\n", cnonce.c_str());
	}
Example #12
0
int main(int argc, string argv[])
{
    // check for correct number of command line arguments
    if (argc != 2 && argc != 3)
    {
        printf("Usage: ./generate n [s]\n");
        return 1;
    }

    // convert the first argument to int
    int n = atoi(argv[1]);

    // seed using current time or seed if given
    if (argc == 3)
    {
        srand((unsigned int) atoi(argv[2]));
    }
    else
    {
        srand((unsigned int) time(NULL));
    }

    // print the numbers
    for (int i = 0; i < n; i++)
    {
        printf("%i\n", rand() % LIMIT);
    }

    // that's all folks
    return 0;
}
/* Set the program parameters from the command-line arguments */
void parameters(int argc, char **argv) {
    int seed = 0;  /* Random seed */
    char uid[32]; /*User name */

    /* Read command-line arguments */
    srand(time_seed());  /* Randomize */

    if (argc == 3) {
        seed = atoi(argv[2]);
        srand(seed);
        printf("Random seed = %i\n", seed);
    }
    if (argc >= 2) {
        N = atoi(argv[1]);
        if (N < 1 || N > MAXN) {
            printf("N = %i is out of range.\n", N);
            exit(0);
        }
    }
    else {
        printf("Usage: %s <matrix_dimension> [random seed]\n",
               argv[0]);
        exit(0);
    }

    /* Print parameters */
    printf("\nMatrix dimension N = %i.\n", N);
}
// Try not to change this. Use it as is.
void init(char **argv) {
    int i,j,k,flag=0;
    float sum;
    int seed = time(0) % 100;	/* seconds since 1/1/1970 */

    srand(seed);
    for (i=0; i<n; i++) {
        for (j=0; j<n; j++) {
            a[i][j] = rand() & 0x7;
            if (rand() & 0x1) a[i][j] = -a[i][j];
        }
        sum = 0;
        for (j=0; j<n; j++) if(i!=j) sum = sum + fabs(a[i][j]);
        if (a[i][i] < sum) a[i][i] = sum + a[i][i];
    }

    for (i=0; i<n; i++) x[i]=1;

    srand(seed);
    for (i=0; i<n; i++) {
        b[i]=rand() & 0x7;
        if (rand() & 0x1) b[i] = -b[i];
    }

    print_equation();

}
Example #15
0
int main(int argc, string argv[])
{
    // Check that the correct number of arguments were passed
    if (argc != 2 && argc != 3)
    {
        printf("Usage: ./generate n [s]\n");
        return 1;
    }

    // Convert the user's input (string) into an int
    int n = atoi(argv[1]);

    // Set the seed
    if (argc == 3)
    {
        srand((unsigned int) atoi(argv[2]));
    }
    else
    {
        srand((unsigned int) time(NULL));
    }

    // Print each of the n random numbers
    for (int i = 0; i < n; i++)
    {
        printf("%i\n", rand() % LIMIT);
    }

    // that's all folks
    return 0;
}
Example #16
0
int main (int argc, char **argv) {
        printf ("Example program for calculating Pareto optimal elements\n");
        printf ("    author: <pieter.eendebak@gmail.com>\n");

/* initialize random seed: */
#ifdef WIN32
        srand (0);
#else
        srand (time (NULL));
#endif

        Pareto< long, int > pareto;

        // select 12 random objects with each 3 values
        const int number_elements = 12;
        const int nvals = 3;

        const int nmax = 4;
        std::vector< long > multi_value (nvals);
        printf ("adding 12 random elements\n");
        for (int i = 0; i < number_elements; i++) {
                for (int j = 0; j < nvals; j++)
                        multi_value[j] = rand () % nmax;

                pareto.addvalue (multi_value, i);
                printf ("  element %d: ", i);
                detail::display_vector (multi_value);
                printf ("\n");
        }

        printf ("The pareto optimal values are:\n");
        pareto.show (3);
}
Example #17
0
int ge_clouds_thread(int args, void* argp){
	ge_Scene* scene = (ge_Scene*)argp;
	nClouds = scene->cloudsGenerator->n_clouds[0] + scene->cloudsGenerator->n_clouds[1] + scene->cloudsGenerator->n_clouds[2];
	float map_size_x = scene->cloudsGenerator->map_size_x;

	while(1){
		if(!ge_current_camera){
			geSleep(1000);
			continue;
		}

		int c=0;
		for(c=0; c<nClouds; c++){
			if(!ge_current_camera)break;
			int type = scene->cloudsGenerator->types[c];
			ge_Cloud* cloud = &scene->cloudsGenerator->clouds[c];

			float scale = 1.5;
			if(type == GE_CLOUD_TYPE_HIGH_LEVEL){
				scale = 5.0;
			}else
			if(type == GE_CLOUD_TYPE_MID_LEVEL){
				scale = 10.0;
			}else{
				scale = 20.0;
			}

		//	if(cloud->x > map_size_x/2.0){
			if(cloud->z <= 0.0 && cloud->x > 0.0){
				srand(0);
				int first_rand = rand()*geGetTick();
				srand(first_rand);
				GenerateCloud(scene, cloud, c);
			//	cloud->x = -map_size_x/2.0;
				float D = -4 * (-1.0/scene->cloudsGenerator->map_size_x) * (scene->cloudsGenerator->map_size_x / 2.0);
				cloud->x = sqrt(D) / (-2.0 / scene->cloudsGenerator->map_size_x);
			}

			cloud->alpha = 1.0;
			if(abs(cloud->x) > map_size_x/2.0*0.6){
			//	cloud->alpha = 1.0 - (abs(cloud->x) - map_size_x/2.0*0.6) / (map_size_x/2.0*0.4);
			}


			float dx = (ge_current_camera->x - cloud->x);
			float dy = (ge_current_camera->y - cloud->y);
			float dz = (ge_current_camera->z - cloud->z);
			float rotX = atanf(dx/dz);
			float rotY = atanf(dy/dz);
		//	float rotZ = atanf(dx/-dy);

			ge_LoadIdentity(cloud->matrix);
			ge_Scale(cloud->matrix, scale, scale, scale);
			ge_Rotate(cloud->matrix, -rotY, rotX, 0.0);
		}
		geSleep(100);
	}

	return 0;
}
Example #18
0
int main(int argc, char** argv) {
	if (argc > 1) {
		srand(atoi(argv[1]));
	} else {
		srand(time(NULL));
	}

	// gnuplot: plot 'data_points.dat', 'hull_points.dat' with lines
	DATA_POINTS_FILE = fopen("data_points.dat", "w");
	HULL_POINTS_FILE = fopen("hull_points.dat", "w");

	assert(DATA_POINTS_FILE != NULL);
	assert(HULL_POINTS_FILE != NULL);

	std::vector<t_point2i> data_points(NUM_DATA_POINTS);
	std::vector<t_point2i> hull_points;
	std::vector<t_convex_hull_builder*> builders = {
		new t_graham_scan_convex_hull_builder(),
		new t_line_wrap_convex_hull_builder(),
	};

	builders[1]->setup(data_points, hull_points);
	builders[1]->build(data_points, hull_points);

	for (unsigned int n = 0; n < builders.size(); n++) {
		delete builders[n];
	}

	fclose(DATA_POINTS_FILE);
	fclose(HULL_POINTS_FILE);
	return 0;
}
Example #19
0
int main(int argc, string argv[])
{
    // TODO: comment me
    if (argc != 2 && argc != 3)
    {
        printf("Usage: ./generate n [s]\n");
        return 1;
    }

    // Conver first argument from character array to int
    // and store it on a variable
    int n = atoi(argv[1]);

    // Check if a third argument was passed
    // and use it as seed for the rad func using srand
    if (argc == 3)
    {
        srand((unsigned int) atoi(argv[2]));
    }
    else
    {
        srand((unsigned int) time(NULL));
    }

    // Print the generated n "random" numbers
    for (int i = 0; i < n; i++)
    {
        printf("%i\n", rand() % LIMIT);
    }

    // that's all folks
    return 0;
}
Example #20
0
/*
 * Simulator constructor -
 *
 * Constructor initialises the appropriate variables. It starts with the default
 * configuration.
 */
Simulator::Simulator()
//:	radio_s(0,NET_RADIO_PROTOCOL, NET_RADIO_ACK_PERIOD)
{
    /* initialise the random seed */
    struct timeval tv;
    gettimeofday(&tv, NULL);
    srand(tv.tv_usec);

    srand(GetTickCount());

    running_state = RUNSTATE_PLAY;

    // goal depth on screen appears to be short..so make a little short to make sure
    // we can get the ball back
    field_max.set(FIELD_LENGTH_H + FieldConstantsRoboCup2012::boundary_width_-OMNIBOT_RADIUS
                  , FIELD_WIDTH_H + FieldConstantsRoboCup2012::boundary_width_ -OMNIBOT_RADIUS);

    // default number of robots
    num_yellow = num_blue = 0;
    //num_blue=1;

    frameCount = 0;
    goalscored = false;

    int i;
    for(i=0;i<MAX_TEAM_ROBOTS;i++)
    {
        blue_robots[i].conf = 0;
        yellow_robots[i].conf = 0;
    }
}
Example #21
0
int
main(int argc, char *argv[])
{
    // Tells the user about the uasge and exit. 
    if (argc != 2 && argc != 3)
    {
        printf("Usage: generate n [s]\n");
        return 1;
    }

    // Converts the character array (argv[1]) provided at the command line into an integer.
    int n = atoi(argv[1]);

    // Here if no of arguments (argc) provided at command line are 3 three then the rand func is seeded by the the no "s", else seed becomes NULL.
    if (argc == 3)
        srand((unsigned int) atoi(argv[2]));
    else
        srand((unsigned int) time(NULL));

    // Printing the required no of random numbers making it less then LIMIT.
    for (int i = 0; i < n; i++)
        printf("%d\n", rand() % LIMIT);

    // that's all folks
    return 0;
}
Example #22
0
/* INTERNAL FUNCTION
   Seed the random function.
 */
void fann_seed_rand()
{
#ifndef _WIN32
	FILE *fp = fopen("/dev/urandom", "r");
	unsigned int foo;
	struct timeval t;

	if(!fp)
	{
		gettimeofday(&t, NULL);
		foo = t.tv_usec;
#ifdef DEBUG
		printf("unable to open /dev/urandom\n");
#endif
	}
	else
	{
		fread(&foo, sizeof(foo), 1, fp);
		fclose(fp);
	}
	srand(foo);
#else
	/* COMPAT_TIME REPLACEMENT */
	srand(GetTickCount());
#endif
}
Example #23
0
int main(int argc, string argv[])
{
    // TODO: Checking user input to make sure it's correct.
    if (argc != 2 && argc != 3)
    {
        printf("Usage: ./generate n [s]\n");
        return 1;
    }

    // TODO: Sets int n to the integver value of the string arg v.
    int n = atoi(argv[1]);

    // TODO: If they put in a seed, change the behavior.
    if (argc == 3)
    {
        srand((unsigned int) atoi(argv[2]));
    }
    else
    {
        srand((unsigned int) time(NULL));
    }

    // TODO: Print each digit on a consecutive line.
    for (int i = 0; i < n; i++)
    {
        printf("%i\n", rand() % LIMIT);
    }

    // that's all folks
    return 0;
}
Example #24
0
GF_EXPORT
void gf_rand_init(Bool Reset)
{
	if (Reset) {
		srand(1);
	} else {
		srand( (u32) time(NULL) );
	}
}
int main(int argc, char* argv[]){
	int N, i, *rankings, not_assigned, tid, *threads_rand, not_assignedT;
	pthread_t *threads;
	arg_t *args;

	if(argc < 2){
		fprintf(stderr, "Invalid number of input parameters\n"); return -1;
	}
	
	N = atoi(argv[1]);
	if(N <= 8){
		fprintf(stderr, "N must be greater than 8\n"); return -1;
	}

	threads = (pthread_t*) malloc(N * sizeof(pthread_t));
	args = (arg_t*) malloc(N * sizeof(pthread_t));
	rankings = (int*) malloc(N * sizeof(int));
	threads_rand = (int*) malloc(N * sizeof(int));

	not_assigned = N;
	srand(time(NULL));
	for(i = 0; i < N; i++){
		rankings[i] = i;
	}

	sem_init(&barrier1, 0, N-3);
	sem_init(&barrier2, 0, 0);
	pthread_mutex_init(&best_ranking.lock, NULL);
	pthread_mutex_init(&c.lock, NULL);
	
	
	for(i = 0; i < N; i++){
		args[i].tid = i;
		args[i].ranking = Random_Generator(rankings, &not_assigned);
		args[i].count = N - 3;
		pthread_create(&threads[i], NULL, Thread, (void*)&args[i]);
	}
	
	srand(time(NULL));
	while(1){
		int sleep_time = rand() % 4 +2;
		sleep(sleep_time);

		/*i need to reset threads num generator, at each loop*/
		not_assignedT = N;
		for(i = 0; i < N; i++)
			threads_rand[i] = i;
		fprintf(stdout, "\n------------>New elections<------------\n");
		best_ranking.ranking = 0; best_ranking.leader_id = 0;
		for(i = 0; i < N -3; i++){
			tid = Random_Generator(threads_rand, &not_assignedT);
			pthread_kill(threads[tid], SIGUSR1);
		}
	}

	return 0;
}
Example #26
0
BedShuffle::BedShuffle(string &bedFile, string &genomeFile, string &excludeFile, string &includeFile, 
                       bool haveSeed, bool haveExclude, bool haveInclude, bool sameChrom, 
                       float overlapFraction, int seed) {

    _bedFile         = bedFile;
    _genomeFile      = genomeFile;
    _excludeFile     = excludeFile;
    _includeFile     = includeFile;
    _sameChrom       = sameChrom;
    _haveExclude     = haveExclude;
    _haveInclude     = haveInclude;
    _overlapFraction = overlapFraction;
    _haveSeed        = haveSeed;


    // use the supplied seed for the random
    // number generation if given.  else,
    // roll our own.
    if (_haveSeed) {
        _seed = seed;
        srand(seed);
    }
    else {
        // thanks to Rob Long for the tip.
        srand((unsigned)time(0)+(unsigned)getpid());
    }

    _bed         = new BedFile(bedFile);
    _genome      = new GenomeFile(genomeFile);
    _chroms      = _genome->getChromList();
    _numChroms   = _genome->getNumberOfChroms();

    if (_haveExclude) {
        _exclude = new BedFile(excludeFile);
        _exclude->loadBedFileIntoMap();
    }
    
    if (_haveInclude) {
        _include = new BedFile(includeFile);
        _include->loadBedFileIntoMapNoBin();

        masterBedMapNoBin::const_iterator it    = _include->bedMapNoBin.begin(); 
        masterBedMapNoBin::const_iterator itEnd = _include->bedMapNoBin.end();
        for(; it != itEnd; ++it) {
            _includeChroms.push_back(it->first);
            _numIncludeChroms++;
        }
    }

    if (_haveExclude == true && _haveInclude == false)
        ShuffleWithExclusions();
    else if  (_haveExclude == false && _haveInclude == true)
        ShuffleWithInclusions();
    else
        Shuffle();
}
Example #27
0
int main(int argc, char *argv[]) {
  int num_buffers;
  int init_size;
  int max_size;
  int doublings;
  int iterations;

  if (argc < 6 ||
      argc > 7 ||
      (num_buffers = atoi(argv[1])) == 0 ||
      (init_size = atoi(argv[2])) == 0 ||
      (max_size = atoi(argv[3])) == 0 ||
      init_size > max_size ||
      (iterations = atoi(argv[4])) == 0 ||
      (doublings = atoi(argv[5])) == 0 ||
      (argc == 7 && atoi(argv[6]) == 0)) {
    fprintf(stderr, "usage: realloc_test <num_buffers> <init_size> <max_size> <doublings> <iterations> [seed]\n");
    exit(EXIT_FAILURE);
  }

  for ( int i = 0 ; i < argc ; i++ ) {
    printf("%s ", argv[i]);
  }
  printf("\n");

  if (argc == 7) {
    srand(atoi(argv[6]));
  } else {
    srand(time(NULL));
  }

  struct TMemoryBuffer* buffers = calloc(num_buffers, sizeof(*buffers));
  if (buffers == NULL) abort();

  for ( int i = 0 ; i < num_buffers ; i++ ) {
    buffers[i].size = max_size;
  }

  while (iterations --> 0) {
    for ( int i = 0 ; i < doublings * num_buffers ; i++ ) {
      struct TMemoryBuffer* buf = &buffers[rand() % num_buffers];
      buf->size *= 2;
      if (buf->size <= max_size) {
        buf->ptr = realloc(buf->ptr, buf->size);
      } else {
        free(buf->ptr);
        buf->size = init_size;
        buf->ptr = malloc(buf->size);
      }
      if (buf->ptr == NULL) abort();
    }
  }

  printf("Non-copied %d/%d (%.2f%%)\n", non_copies, copies + non_copies, 100.0 * non_copies / (copies + non_copies));
  return 0;
}
Example #28
0
/* Get random data.
*/
void
get_random_data(unsigned char *data, const size_t len)
{
    uint32_t    i;
#ifdef WIN32
	int				rnum;
	struct _timeb	tb;

	_ftime_s(&tb);

	srand((uint32_t)(tb.time*1000)+tb.millitm);

	for(i=0; i<len; i++)
	{
		rnum = rand();
        *(data+i) = rnum % 0xff;
	}
#else
	FILE           *rfd;
    struct timeval  tv;
    int             do_time = 0;
    size_t          amt_read;

    /* Attempt to read seed data from /dev/urandom.  If that does not
     * work, then fall back to a time-based method (less secure, but
     * probably more portable).
    */
    if((rfd = fopen(RAND_FILE, "r")) == NULL)
    {
        do_time = 1;
    }
    else
    {
        /* Read seed from /dev/urandom
        */
        amt_read = fread(data, len, 1, rfd);
        fclose(rfd);

        if (amt_read != 1)
            do_time = 1;
    }

    if (do_time)
    {
        /* Seed based on time (current usecs).
        */
        gettimeofday(&tv, NULL);
        srand(tv.tv_usec);

        for(i=0; i<len; i++)
            *(data+i) = rand() % 0xff;
    }

#endif

}
Example #29
0
int main()
{
  uint32_t errors = 0;
  int seed = 1;
  srand(seed);

  printf("Mersenne Twister -- printing the first %zu numbers w/seed %d\n\n",
    sizeof(expected)/sizeof(expected[0]), seed);

  for ( size_t n=0; n<sizeof(expected)/sizeof(expected[0]); ++n ) {
    uint32_t r = rand_u32();

    bool error = r != expected[n];
    if ( error ) ++errors;

    printf("%10u%c%c", r,
      error? '*' : ' ',
      n % 5 == 4 ? '\n' : ' ');
    fflush(stdout);
  }

  printf("\nGenerating 64-bit pseudo-random numbers\n\n");
  for ( int n=0; n<27; ++n )
    printf("%20" PRIu64 "%c", rand_u64(), n % 3 == 2 ? '\n' : ' ');

  printf("\nFloat values in range [0..1]\n\n");
  for ( int n=0; n<40; ++n )
    printf("%f%c", randf_cc(), n % 5 == 4 ? '\n' : ' ');

  printf("\nDouble values in range [0..1]\n\n");
  for ( int n=0; n<40; ++n )
    printf("%f%c", randd_cc(), n % 5 == 4 ? '\n' : ' ');

  printf("\nChecking reference numbers for seed 1 (may take some time)\n\n");
  srand(1);
  for ( size_t n=0, target=1, idx=0; n<=0xffffffff; ++n ) {
    uint32_t r = rand_u32();

    if ( n != (target-1) )
      continue;

    bool error = r != doubled_reference_seed1[idx];
    if ( error ) ++errors;

    printf("%11zu %11u%c %c", n, r,
      error? '*' : ' ',
      idx % 4 == 3 ? '\n' : ' ');
    fflush(stdout);
    target *= 2;
    ++idx;
  }

  printf("\nFound %u incorrect numbers\n\n", errors);
  return errors > 0;
}
Example #30
0
void f_srand(const Variant& seed /* = null_variant */) {
  s_rand_is_seeded = true;
  if (seed.isNull()) {
    return srand(math_generate_seed());
  }
  if (seed.isNumeric(true)) {
    srand(seed.toInt32());
  } else {
    raise_warning("srand() expects parameter 1 to be long");
  }
}