Пример #1
0
/*!

*/
boost::int32_t
AudioCodec::posToBit18( const Vector2D & pos ) const
{
    boost::int32_t rval = 0;

    // pos.x value -> 9 bits (=[0,511])
    {
        double x = min_max( -52.0, pos.x, 52.0 );
        x += 52.0;
        x *= ( 511.0 / 104.0 ); // x /= (104.0/511.0);
        rval |= static_cast< boost::int32_t >( rint( x ) );
    }

    rval <<= 9; // 9 bits shift for next info

    // pos.y value -> 9 bits (=[0,511])
    {
        double y = min_max( -34.0, pos.y, 34.0 );
        y += 34.0;
        y *= ( 511.0 / 68.0 ); // y /= (68.0/511.0);
        rval |= static_cast< boost::int32_t >( rint( y ) );
    }

    return rval;
}
Пример #2
0
void OddEvenMerge(fmpz_poly_t * poly_nums, int n, int nbits, int lo, int high, int r, fhe_pk_t pk){

	//printf("Inside OddEven Merge");		
	mpz_t * max;
	mpz_t * min;
	max = malloc(sizeof(mpz_t) * nbits);
	min = malloc(sizeof(mpz_t) * nbits);
	for(int i=0;i<nbits;i++){
		mpz_init(max[i]);
		mpz_init(min[i]);
	}

	
	int m = 2*r;
	
	if(m<high){
		OddEvenMerge(poly_nums, n, nbits, lo, high, m, pk); // even subsequence
		OddEvenMerge(poly_nums, n, nbits, lo+r, high, m, pk); //odd subsequence	
	for(int i=lo+r; i+r<lo+high; i+=m){
			min_max(min, max, poly_nums[i], poly_nums[i+r], pk, nbits);
			for(int k=0;k<nbits;k++){
				fmpz_poly_set_coeff_mpz(poly_nums[i], k, min[k]);
				fmpz_poly_set_coeff_mpz(poly_nums[i+r],k, max[k]);
			}
		


		}

	}	
	else {
		min_max(min, max, poly_nums[lo], poly_nums[lo+r], pk, nbits);		
		for(int k=0;k<nbits;k++){
			fmpz_poly_set_coeff_mpz(poly_nums[lo], k, min[k]);
			fmpz_poly_set_coeff_mpz(poly_nums[lo+r],k, max[k]);
		}


		
	}

	for(int k=0;k<nbits;k++){
		mpz_clear(max[k]);
		mpz_clear(min[k]);
	}
	free(max);
	free(min);
	
	
}
Пример #3
0
int8_t min_max(Morpion game) {
    int8_t val;
    val = game.win();
    Morpion exploration;
    // cout << " . " << (int) val << endl;
    if (val != 0) return val;
    if (game.is_tie()) return 0;

    if (game.player == 1) {
        // Looking for a maximum
        cilk::reducer< cilk::op_max<int8_t>> best;
        cilk_for (int i = 0; i < 3; i++) {
            cilk_for (int j = 0; j < 3; j++) {
                if (game.valid_move(i, j)) {
                    exploration = game;
                    exploration.move(i, j); // move changes the player's turn

                    val = min_max(exploration);

                    best->calc_max(val);
                }
            }
        }
        return best.get_value();
    }
Пример #4
0
void bitonicMergeDown(fmpz_poly_t *poly_nums, int  nbits, int n,  int lo , int  high, fhe_sk_t sk, fhe_pk_t pk){
	if(high==0) return;

	//////////// SWAP //////////////////

	mpz_t * max;
	mpz_t * min;
	max = malloc(sizeof(mpz_t) * nbits);
	min = malloc(sizeof(mpz_t) * nbits);
	for(int i=0;i<nbits;i++){
		mpz_init(max[i]);
		mpz_init(min[i]);
	}


	for(int i = 0; i<high;i++){
		min_max(min, max, poly_nums[i+lo], poly_nums[i+lo+high], pk, nbits);		
		for(int k=0;k<nbits;k++){
			fmpz_poly_set_coeff_mpz(poly_nums[i+lo+high], k, min[k]);
			fmpz_poly_set_coeff_mpz(poly_nums[i+lo],k, max[k]);
		}
			
	}

	bitonicMergeDown(poly_nums, nbits, n, lo, high/2,  sk, pk);
	bitonicMergeDown(poly_nums, nbits, n, lo+high, high/2,  sk, pk);
	for(int k=0;k<nbits;k++){
		mpz_clear(max[k]);
		mpz_clear(min[k]);
	}
	free(max);
	free(min);	
}
Пример #5
0
// Player 1 wants max, player -1 wants min
int8_t min_max(Morpion game) {
    int8_t val;
    val = game.win();
    Morpion exploration;
    // cout << " . " << (int) val << endl;
    if (val != 0) return val;
    if (game.is_tie()) return 0;

    if (game.player == 1) {
        // Looking for a maximum
        int8_t best = -1;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (game.valid_move(i, j)) {
                    exploration = game;
                    exploration.move(i, j); // move changes the player's turn

                    val = min_max(exploration);

                    best = max(best, val);
                }
            }
        }
        return best;
    }
    else {
        // Looking for a minimum
        int8_t best = 1;
        // Get the min/max of all the children
        cilk_for (int i = 0; i < 3; i++) {
            cilk_for (int j = 0; j < 3; j++) {
                if (game.valid_move(i, j)) {
                    exploration = game;
                    exploration.move(i, j); // move changes the player's turn

                    val = min_max(exploration);

                    best = min(best, val);
                }
            }
        }
        return best;
    }
    return 0;
}
Пример #6
0
void main(){
int m = 0;
double *min = &m, *max = &m; 
printf("Before min_max: Values are: %lg \t %lg\n and addresses are: %p\t %p\n", *min, *max, min, max);
double a[10] = {1, 2, 4, 5, 6, 2, 7, 8, 12, -9};
min_max(min, max, 10, a); 
printf("Outside min_max: Values: %lg\t %lg\n and addresses: %p\t%p\n", *min, *max, min, max); 
printf("Entering correct_min_max\n");
correct_min_max(&min, &max, 10, a); 
printf("Outside correct_min_max: Values: %g\t%lg \n", *min, *max); 
}
Пример #7
0
extern int reversi(void)
{
    int all,al,be,put;
    init();
        printf("counter:%d\n ",c);
    

    
c=sekisa();
c=man+com;
    if(c>=D){
        open=0;
        e=OFF;
                al=-1;
                be=1;
                if(c>=D+3){al=-64;be=64;}
                put=min_maxf(65-c,al,be,c);
                printf("\nput:%d#man:%d\n",put,maxe);
              
                all=check(put,COM,OFF);

                if (all){
                        check(put,COM,ON);
                }
    }
    else if(c<8){
                        al=-10000;be=10000;e=ON;put=min_max(jo,al,be,c);e=OFF;open=11;c=64;
    }
    else if(c<35){
                            al=-10000;be=10000;e=ON;put=min_max(chu,al,be,c);e=OFF;open=11;c=64;
                }
                else if(c<D){
                    al=-10000;be=10000;e=ON;put=min_max(shu,al,be,c);e=OFF;open=0;
                }
  {check(put,COM,ON);xy=put;return(put);}
  
    
    
 //       init();
   // return(put);
}
Пример #8
0
int main(void){
   
    int i, *p, a[5];

    p = &a[0];
    i = 0;
    for (i = 0; i < 4; i++){
        printf("podaj liczbe \n");
        scanf("%d", &a[i]);
    }
    min_max(p);
}
Пример #9
0
int main()
{
	const int a[] = { 1,2,5,6,7,8,3,2,5 };
	const int b[] = { 0,2,5,6,9 };
	const int c[] = { 7,2,5,6,7,8,3,2,5,5,3,2,7 };

	int x = 123456789;
	int y = 45584234;
	int z = 2133123;

	size_t n = 9;
	int min, max;
	int *pmin, *pmax;

	pmin = &min;
	pmax = &max;

	min_max(a, n, pmin, pmax);
	printf("Min:%d Max:%d\n", min, max);

	n = 5;
	min_max(b, n, pmin, pmax);
	printf("Min:%d Max:%d\n", min, max);

	n = 13;
	min_max(c, n, pmin, pmax);
	printf("Min:%d Max:%d\n", min, max);

	printf("Number:%d num_digits:%d\n", x, num_digits(x));
	printf("Number:%d  num_digits:%d\n", y, num_digits(y));
	printf("Number:%d   num_digits:%d\n", z, num_digits(z));

	printf("Number:%d reverse:%lu\n", x, reverse(x));
	printf("Number:%d  reverse:%lu\n", y, reverse(y));
	printf("Number:%d   reverse:%lu\n", z, reverse(z));

	getchar();
	return 0;
}
Пример #10
0
Game* play_ai(Game* game) {
	
	if(!game)
		return NULL;
	
	/* If the game doesn't imply the computer, no need to play */
	if(!is_computer_game(game))
		return game;
	
	/* If the turn is not to the computer, no need to play */
	if(!((game->turn == BLACK && game->p1.player_type == COMPUTER) || (game->turn == WHITE && game->p2.player_type == COMPUTER)))
		return game;
	
	short turn = game->turn;

	printf("Loading...\n");
	
	/* Finding the best move to play */
	short position = min_max(YES, game, game->turn, GLOBAL_DEPTH, GLOBAL_DEPTH, SHRT_MIN, SHRT_MAX, game->coefs);
	
	/* If the move is not legal or the coordinates don't have the good format, which should not happen */
	if(move_processing(game, UNKNOWN, position) != 1) {
		return game;
	}
	
	destroy_end_boards_tab(game);
	destroy_end_moves_tab(game);
	
	update_othellier(game);
	
	clear_screen();
	display_othellier(game);

	/* If the end of the game is reached, performing and end of game action */
	if(end_of_game(game))
		game = end_of_game_action(game);
		
	else if(game->turn == turn) {
		printf("### %s passe son tour !###\n\n", game->turn==BLACK?game->p2.player_name:game->p1.player_name);
		printf("Au tour de %s de jouer :\n", game->turn==BLACK?game->p1.player_name:game->p2.player_name);
		game = play_ai(game);
	}
	
	else
		printf("Au tour de %s de jouer : \n", game->turn==BLACK?game->p1.player_name:game->p2.player_name);
	
	/* Playing another time if it's a C_VS_C game */
	game = play_ai(game);
	
	return game;
}
Пример #11
0
void User::memcachify(char* name) {
  pair<char*, size_t> record = toBinary(true);
  pair<float, float> m_m = min_max();
  float x[2];
  x[0] = m_m.first;
  x[1] = m_m.second;
  cout << "\tStoring " << size() << " records and " << 
    record.second << " bytes  --> " << name << endl;
  mc.set(name, record.first, record.second);
  char name2[80];
  sprintf(name2, "%s_min_max", name);
  mc.set(name2, x, 2*sizeof(float));
  delete record.first;
  
}
Пример #12
0
void  table_view(void)
{
   int  reading, min, max;

   clrscr();                                /* clear the screen */
   printf("Reading\t\tTemperature(F)\n");

   for (reading = 0; reading < READINGS; reading++)
      printf("%d\t\t\t%d\n", reading + 1, temps[reading]);

   min_max(READINGS, temps, &min, &max);
   printf("Minimum temperature: %d\n", min);
   printf("Maximum temperature: %d\n", max);
   printf("Average temperature: %f\n", avg_temp(READINGS, temps));
}
Пример #13
0
void init_rama(char *infile,char *topfile,t_xrama *xr)
{
  static t_topology *top;
  real   t;

  top=read_top(topfile);
  
  /*get_dih2(xr,top->idef.functype,&(top->idef.bondeds),&(top->atoms));*/
  get_dih(xr,&(top->atoms));
  get_dih_props(xr,&(top->idef));
  xr->natoms=read_first_x(&xr->traj,infile,&t,&(xr->x),xr->box);
  xr->idef=&(top->idef);
  
  min_max(xr);
  calc_dihs(xr);
}
Пример #14
0
int main()
{
  // Testing with ints

  // testing min_max
  int int_arr[] = {1, 7, 2, -4, 23, 42, 5 };
  int int_min = 0;
  int int_max = 0;

  min_max( int_arr, 7, int_min, int_max );
  
  if( ( int_min == -4 ) && ( int_max == 42 ) ) {
    printf( "int min_max succeeded!\n" );
  }
  else {
    printf( "int min_max failed (%d,%d)\n", int_min, int_max );
  }

  // testing swap2
  int int_a = 7;
  int int_b = 8;

  swap2( int_a, int_b );

  if( ( int_a == 8 ) && ( int_b == 7 ) ) {
    printf( "int swap2 succeeded!\n" );
  }
  else {
    printf( "int swap2 failed (%d,%d)\n", int_a, int_b );
  }

  // testing rot3			       
  int_a = 7;
  int_b = 8;
  int int_c = 9;
  
  rot3( int_a, int_b, int_c );

  if( ( int_a == 9 ) && ( int_b == 7 ) && ( int_c == 8 ) ) {
    printf( "int rot3 succeeded!\n" );
  }
  else {
    printf( "int rot3 failed (%d, %d, %d)\n", int_a, int_b, int_c );
  }
  
  return 0;
}
Пример #15
0
t_topology *init_rama(char *infile,char *topfile,t_xrama *xr,int mult)
{
  t_topology *top;
  int    ePBC;
  real   t;

  top=read_top(topfile,&xr->ePBC);
  
  /*get_dih2(xr,top->idef.functype,&(top->idef.bondeds),&(top->atoms));*/
  get_dih(xr,&(top->atoms));
  get_dih_props(xr,&(top->idef),mult);
  xr->natoms=read_first_x(&xr->traj,infile,&t,&(xr->x),xr->box);
  xr->idef=&(top->idef);
  
  min_max(xr);
  calc_dihs(xr);

  return top;
}
		bool OmegaCornerPointsConfigurator::configure(Model& m) const
		{		
			size_t i(0);
			Point<3> ebc;
			m.UpdateIndices();
			for (const auto& cpp : cpts_) {
				auto cmm = min_max(cpp);
				vector<size_t> omega_ids;
				omega_ids.reserve(m.Region("Model").Elements());
				for (const auto& eit : m.Region("Model").ElementVector())
				{
					ebc = eit->BaryCenter();
					if (!within_bounds(ebc, cmm))
						continue;						// not within min-max bounds
					omega_ids.push_back(eit->Idx());    // is within min-max bounds
				}
				auto rname = (string)"omega_" + to_string(i); ++i;
				if (omega_ids.size())
					m.FormRegionFrom(rname.c_str(), omega_ids);
			}
			return true;
		}
Пример #17
0
int main(void)
{
    int min = -1, max = -1;
    int array[LENGTH];

    for(size_t c=0;c<LENGTH/2; c++) {
        array[c] = c+3;
        printf("%d ", array[c]);
    }

    for(size_t c=LENGTH/2;c<LENGTH; c++) {
        array[c] = c-3;
        printf("%d ", array[c]);
    }

    putchar('\n');

    min_max(array, LENGTH, &min, &max);

    printf("Min=%d , Max=%d\n", min,max);

    return 0;
}
Пример #18
0
int dynamic_max_value(int nums[], int len_nums, char ops[]) {
  int start_num, diff, a_size, result, i;
  a_size = len_nums + 1;
  int(*mins)[a_size] = malloc(a_size * a_size * sizeof(int));
  int(*maxs)[a_size] = malloc(a_size * a_size * sizeof(int));

  for (i = 1; i <= len_nums; i++) {
    mins[i][i] = nums[i - 1];
    maxs[i][i] = nums[i - 1];
  }

  for (diff = 1; diff <= len_nums; diff++) {
    for (start_num = 1; start_num <= (len_nums - diff); start_num++) {
      int end_num = start_num + diff;
      min_max(a_size, start_num, end_num, mins, maxs, ops);
    }
  }

  result = maxs[1][len_nums];
  free(maxs);
  free(mins);
  return result;
}
Пример #19
0
pair<char*, size_t>  User::toBinary(bool rescale) {
  const int record_size = (sizeof(int) + 1);
  pair<float, float> m_m = min_max();

  char * record = new char[record_size*size() + 2 * sizeof(int)];
  char * rec_ptr = record;
  *(rec_ptr++) = char(record_size);
  if(m_m.first == 0 && m_m.second == 0) {
    rec_ptr += int_to_bytes(0, rec_ptr);
  }
  else {
    float scale = rescale ? max(-m_m.first, m_m.second) : 1.;
    vector<pair<int, float> > vec = sort();
    rec_ptr += int_to_bytes(vec.size(), rec_ptr);
    for(vector<pair<int, float> >::iterator it = vec.begin();
        it != vec.end(); it++) {
      entry_to_bytes((*it), rec_ptr, scale);
      rec_ptr += record_size;
    }
    vec.clear();
  }
  return pair<char*, size_t>(record, rec_ptr - record);
}
Пример #20
0
int sort_int(char request){
	int i = 0;
	int result_min;
	int result_max;
	int_array my_array;
	sort_array sorted_array;
	int *min;
	int *max;
	min = (int *)malloc(10*sizeof(int));
	max = (int *)malloc(10*sizeof(int));
	get_int(&my_array);

	for (i = 0 ; i < my_array.length ; i ++){
		min_max(&my_array,&sorted_array);
		build_order(&my_array, &sorted_array ,i,min,max,request);
	}
	for (i = 0 ; i < my_array.length ; i ++){
		if (request == 'D'){
			printf(" %d ",*sorted_array.decending[i]);
		} else {
			printf(" %d ",*sorted_array.accending[i]);	
		}
	}
}
Пример #21
0
static int play_dataset (midi_spec *spec, midi_track *track,
			 const dataset *dset)
{
    double xmin, xmax, xavg;
    double ymin, ymax;
    double xscale, yscale;
    int i;

    track->notes = malloc(dset->n * sizeof *track->notes); 
    if (track->notes == NULL) {
	fputs("out of memory\n", stderr);
	return 1;
    }

    track->channel = 0;
    track->patch = PC_GRAND; 
    track->n_notes = dset->n;

    if (dset->pd == 0) {
	/* scatter plot: sort data by x value */
	qsort((void *) dset->points, (size_t) dset->n, 
	      sizeof dset->points[0], compare_points);
    }

    points_min_max(dset->points, &xmin, &xmax, &ymin, &ymax, dset->n);
   
    if (dset->y2 != NULL) {
	double y2min, y2max;

	min_max(dset->y2, &y2min, &y2max, dset->n);
	if (y2min < ymin) ymin = y2min;
	if (y2max > ymax) ymax = y2max;
    }

    xavg = (xmax - xmin) / (dset->n - 1);
    /* normalize average x step to quarter note */
    xscale = 1.0 / xavg;

#if ADEBUG
    fprintf(stderr, "xavg = %g, xscale = %g\n", xavg, xscale);
#endif

    yscale = YMAX / (ymax - ymin);

    for (i=0; i<dset->n; i++) {
	double dtx, dux, ypos;

	if (!na(dset->points[i].y)) {	
	    ypos = (dset->points[i].y - ymin) * yscale;
	} else {
	    ypos = NADBL;
	}

	if (i == 0) {
	    dtx = 0.0;
	} else {
	    dtx = xscale * (dset->points[i].x - dset->points[i-1].x);
	}

	if (i == dset->n - 1) {
	    dux = xscale * xavg;
	} else {
	    dux = xscale * (dset->points[i+1].x - dset->points[i].x);
	}

	track->notes[i].dtime = dtx;
	track->notes[i].duration = dux;
	if (!na(ypos)) {
	    track->notes[i].pitch = 36 + (int) (ypos + 0.5);
	    track->notes[i].force = DEFAULT_FORCE;
	} else {
	    track->notes[i].pitch = 36;
	    track->notes[i].force = 0;
	}	    

#if ADEBUG
	fprintf(stderr, "Obs %d: x = %g, y = %g, ypos = %g\n", i, 
		dset->points[i].x, dset->points[i].y, ypos);
	fprintf(stderr, " dtime=%g, duration=%g, pitch=%d\n",
		track->notes[i].dtime, track->notes[i].duration,
		track->notes[i].pitch);
#endif
    }

    write_midi_track(track, spec);

    if (dset->series2) {
	for (i=0; i<dset->n; i++) {
	    double yi, ypos = 0;

	    if (dset->y2 != NULL) {
		yi = dset->y2[i];
	    } else {
		yi = dset->intercept + dset->slope * dset->points[i].x;
	    }

	    if (!na(yi)) {
		ypos = (yi - ymin) * yscale;
		track->notes[i].pitch = 36 + (int) (ypos + 0.5);
		track->notes[i].force = DEFAULT_FORCE;
	    } else {
		track->notes[i].pitch = 36;
		track->notes[i].force = 0;
	    }
#if ADEBUG
	    fprintf(stderr, "Series2, Obs %d: x = %g, y = %g, ypos = %g\n", i, 
		    dset->points[i].x, yi, ypos);
	    fprintf(stderr, " dtime=%g, duration=%g, pitch=%d\n",
		    track->notes[i].dtime, track->notes[i].duration,
		    track->notes[i].pitch);
#endif
	}

	track->channel = 1;
	/* below: was PC_MARIMBA, but that's not in freepats */
	track->patch = PC_CELLO;
	write_midi_track(track, spec);
    }	

    free(track->notes);

    return 0;
}
Пример #22
0
image<uchar> *imageFLOATtoUCHAR(image<float> *input) {
  float min, max;
  min_max(input, &min, &max);
  return imageFLOATtoUCHAR(input, min, max);
}
Пример #23
0
image<uchar> *imageSHORTtoUCHAR(image<short> *input) {
  short min, max;
  min_max(input, &min, &max);
  return imageSHORTtoUCHAR(input, min, max);
}
Пример #24
0
image<uchar> *imageLONGtoUCHAR(image<long> *input) {
  long min, max;
  min_max(input, &min, &max);
  return imageLONGtoUCHAR(input, min, max);
}
Пример #25
0
/*
 Fonction principale
 */
int main(int argc, char **argv)
{
    int mode, rep;
    int nb_coups = 0, i, j, passe=0;
    char joueur;
    char gagnant = '-';


	//TODO: changer la force de l'ordi en diminuant/augmentant la max depth j1 et/ou j2
    int max_depth_j1 = 5;
    int max_depth_j2 = 1;
    
    srand(time(NULL));
    init_pile();
    
    printf("Bienvenue dans SPIOTHELLO, l'othello des L2 SPI de l'Université du Maine !\n");

    /* mode de jeu */
    do{
        printf("Choisissez le mode de jeu:\n");
        printf("\t1. J1 [Humain] vs. J2 [Humain]\n");
        printf("\t2. J1 [Humain] vs. J2 [Ordinateur]\n");
        printf("\t3. J1 [Ordinateur] vs. J2 [Ordinateur]\n");
        printf("Choix : ");
        scanf("%d",&mode);
        if(mode!=1 && mode!=2 && mode!=3)
            printf("Le mode %d n'existe pas, saisissez à nouveau.", mode);
    } while(mode!=1 && mode!=2 && mode!=3);
    
    /* demander qui commence */
    do {
        printf("Qui commence ? J1 [%c] -> 1 ou J2 [%c] -> 2\nChoix : ", J1, J2);
        scanf("%d", &rep);
        if(rep != 1 && rep != 2)
            printf("Saisie incorrecte, recomencez");
    } while(rep!=1 && rep!=2);
    if(rep==1) joueur = J1;
    else joueur = J2;
    printf("Le joueur J%d [%c] commence ...\n", rep, joueur);
    
    othello *jeu = creer_othello();
    afficher_othello(jeu);
    
    while(!partie_finie(nb_coups, passe)){
        if(mode == 1 || (mode==2 && joueur==J1)){            // Si humain-humain ou humain-ordi et joueur courant == J1
            //demander une case
            if(humain_joue_un_coup(jeu, joueur)) {
                nb_coups++;
                passe = 0;
            }
            else {
                printf("J%d [%c], vous ne pouvez pas jouer ... !\n", joueur==J1?1:2, joueur);
                scanf(" ");
                passe++;
            }
        } else {    // si humain-ordi et joueur courant == J2 ou ordi-ordi
            
            //déterminer la case à jouer
            fprintf(stderr, "C'est à J%d [%c] de jouer !\n", joueur==J1?1:2, joueur);
            min_max(jeu, joueur, joueur, nb_coups, &i, &j, 0, joueur==J1?max_depth_j1:max_depth_j2);
            // on joue le meilleur coup s'il existe
            if(i==-1 && j==-1){
                printf("Aucun coup possible ... je passe mon tour\n");
                passe++;
            } else {
                jouer_un_coup(jeu, joueur, i, j);
                nb_coups++;
                passe = 0;
            }
        }
        afficher_othello(jeu);
        joueur = adversaire(joueur); // on change de joueur
    }
    
    int sc1 = score(jeu, J1, 0, nb_coups);
    int sc2 = score(jeu, J2, 0, nb_coups);
    gagnant = sc1>sc2?J1:(sc1<sc2?J2:'-');
    
    if(gagnant == J1)
        printf("Le joueur J1 [%c] a gagné !!\n", gagnant);
    else if(gagnant == J2)
        printf("Le joueur J2 [%c] a gagné !!\n", gagnant);
    else
        printf("Les joueurs n'ont pas pu se départager ... !!\n");
    
	return 0;
}
Пример #26
0
int main(void)
{ 
    bool StanbyWakeUp ;
    float Current_STBY;
  
 /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_stm32l1xx_md.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_stm32l1xx.c file
     */ 
  
    Int_CurrentSTBY = Current_Measurement();
  
    /* Check if the StandBy flag is set */
    if (PWR_GetFlagStatus(PWR_FLAG_SB) != RESET)
    {
        /* System resumed from STANDBY mode */
        /* Clear StandBy flag */
        RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR,ENABLE);
        PWR_ClearFlag(PWR_FLAG_SB); 
        
        StanbyWakeUp = TRUE;
    
    } else
    {
        StanbyWakeUp = FALSE;    
    } 

    PWR_PVDCmd(DISABLE);
    
    RCC_Configuration();
    
    PWR_VoltageScalingConfig(PWR_VoltageScaling_Range1);
    
    /* Wait Until the Voltage Regulator is ready */
    while (PWR_GetFlagStatus(PWR_FLAG_VOS) != RESET) ;
     
    /* Init I/O ports */
    Init_GPIOs ();
    
    /* Initializes ADC */
    ADC_Icc_Init();
    
    enableInterrupts();	
    
    /* Warning ! in TSL Init the sysTick interrupt is setted to:
    SysTick_Config(RCC_Clocks.HCLK_Frequency / 2000 ---> 500 µs*/
    
    /* Init Touch Sensing configuration */  
    TSL_Init();
    
    sMCKeyInfo[0].Setting.b.IMPLEMENTED = 1;
    sMCKeyInfo[0].Setting.b.ENABLED = 1;
    sMCKeyInfo[0].DxSGroup = 0x00; 
 
    /* Initializes the LCD glass */
    LCD_GLASS_Init();
  
    // EECE 337 Code -- Start
        
    char str[50];                       // Used to display results
    unsigned int delay_time = 5000;      // Will delay for 5 seconds
    const unsigned int numItems = 10;          // # items in array
	int MyArray[10] = { 365, 245, -499, 0, 23, 8, 200, -4, -50, 25 };

	int minimum = 0;                    // Will hold minimum value
	int maximum = 0;                    // Will hold maximum value
    
    // Call Function to obtain Min and Max values from array
	min_max(MyArray, numItems, &minimum, &maximum);	
    
    // Copy min result to str
    sprintf (str, "%d", minimum);
    
    // Display on LCD
    LCD_GLASS_DisplayString(str);
    
    // Pause for 5 seconds
    Delay(delay_time);
    
    // Clear LCD
    LCD_GLASS_Clear();
    
    // Copy max result to str
    sprintf (str, "%d", maximum);
    
    // Display on LCD
    LCD_GLASS_DisplayString(str);
    
    // Pause for 5 seconds
    Delay(delay_time);
    
    // EECE 337 Code -- End
    
    return(0);
}		
Пример #27
0
float
inv_transform(int icase, int jvar, xgobidata *xg) {
/*-- using tform2 instead of tform1 -- AB --*/
  double tx = xg->tform2[icase][jvar];
  double rx = xg->raw_data[icase][jvar];
  double new_rx = tx;

  float min, max, diff;
  int *cols;
  int ncols = 0, i, j, n;
  float mean, stddev;

  cols = (int *) XtMalloc((Cardinal) (xg->ncols-1) * sizeof(int));
  ncols = which_cols(cols, jvar, xg);

  switch (tform_tp[jvar].tform1) {
    case RESTORE:
      /* new_rx = tx; */
      break;

    case POWER:

      if (fabs(tform_tp[jvar].param) < .001)
        new_rx = exp(tx);
      else
        new_rx = pow(
          (double) ((tx * tform_tp[jvar].param) + 1),
          (double) (1.0/tform_tp[jvar].param));

      if (!finite(new_rx)) {
        INV_DOMAIN_ERROR;
        show_message(message, xg);
        new_rx = tx;
      }
      break;

    case ABSVALUE:
      new_rx = tx * signum(rx);
      break;

    case INVERSE:
      if (tx == 0) {
        INV_DOMAIN_ERROR;
        show_message(message, xg);
      } else
        new_rx = 1.0/tx;
      break;

    case LOG10:    /* Base 10 log */
      new_rx = pow(10.0, tx);
      break;

    case SCALE:    /* Map onto [0,1] */

      min_max(xg, xg->raw_data, cols, ncols, &min, &max);
      adjust_limits(&min, &max);
      diff = max - min;

      new_rx = (tx * diff) + min;
      break;

    case STANDARDIZE:    /* (x-mean)/sigma */
      mean_stddev(xg, jvar, tform_tp[jvar].inv_domain_adj,
        &mean, &stddev);
       
      new_rx = (tx * stddev) + mean;
      break;

    case DISCRETE2:    /* x>median */
      show_message(
        "Sorry, I\'m unable to perform the transformation for this point\n", 
        xg);
      break;

/*
 * for the rest of these, I've apparently just decided to restore
 * the data to its untransformed state.  Let's worry about it later ...
*/

    case ZSCORE:
    case NORMSCORE:
      cols = (int *) XtMalloc((Cardinal) (xg->ncols-1) * sizeof(int));
      ncols = which_cols(cols, jvar, xg);

      for (n=0; n<ncols; n++) {
        j = cols[n];
        for (i=0; i<xg->nrows; i++)
          xg->tform1[i][j] = xg->raw_data[i][j];
      }
      break;

    default:
      /* new_rx = tx; */
      break;
  }

  inv_domain_adj = tform_tp[jvar].inv_domain_adj;
  return((float) ((*inv_domain_adj)(new_rx)));
}
Пример #28
0
void test_min_max(){
	
	clock_t START_init = clock();

	struct timeval start, end;
	
    	long mtime, seconds, useconds;    

   	 gettimeofday(&start, NULL);
    	
   
 	
	////////////////  Initialization ////////////////

	unsigned a ,b, aux1, aux2;

	a=2; b=5;  

	printf("a = %d et b = %d\n", a, b);
	aux1 = a ; aux2=b;
	int i = 0;
//	unsigned a =30050183, b= 504195648;
//	unsigned aux1, aux2;


	int nbits;   // Number of bits in the binary representation of the integers

	mpz_t c0, c1;
	fmpz_poly_t poly_c1;
	fmpz_poly_t poly_c2;	
	
	mpz_init(c0);
	mpz_init(c1);

	fmpz_poly_init(poly_c1);
	fmpz_poly_init(poly_c2);

		
	fhe_pk_t pk;
	fhe_sk_t sk;
	fhe_pk_init(pk);
	fhe_sk_init(sk);
	
	double T_Elapsed1 = (double) ( clock () - START_init ); 
	printf(" Initialization of the variables etc took %f clocks / sec \n ", T_Elapsed1);

	gettimeofday(&end, NULL);
	seconds  = end.tv_sec  - start.tv_sec;
  	useconds = end.tv_usec - start.tv_usec;
   	mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

   	 printf("Elapsed time in Init : %ld milliseconds\n", mtime);
  	
	////////////////////// Initialization Ends ////////////////////
	

	//////////////////////// Key Generation /////////
	
	clock_t  START_keygen = clock();
	gettimeofday(&start, NULL);


	fhe_keygen(pk, sk);

	double T_Elapsed2 = (double) (clock () - START_keygen);	
	printf(" KeyGen took %f clocks/sec \n", T_Elapsed2);
	
	gettimeofday(&end, NULL);
	seconds  = end.tv_sec  - start.tv_sec;
  	useconds = end.tv_usec - start.tv_usec;
   	mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

   	printf("Elapsed time in KeyGen : %ld milliseconds\n", mtime);
  		
	////////////////////// Key Generation Ends /////////////
	
	////// Encryption of the bit sequences ////////////////

	clock_t  START_enc = clock();
	gettimeofday(&start, NULL);

	fhe_encrypt(c0, pk, a % 2);
	fhe_encrypt(c1, pk, b % 2);

	fmpz_poly_set_coeff_mpz( poly_c1 , i , c0 );
	fmpz_poly_set_coeff_mpz( poly_c2, i, c1 );

	aux1 = aux1 >> 1;
	
	aux2 = aux2 >> 1;
	
	do {
		//printf("--------->%i\n", aux % 2);
		fhe_encrypt(c0, pk, aux1 % 2);
		fhe_encrypt(c1, pk, aux2 %2);
		i++;
		fmpz_poly_set_coeff_mpz ( poly_c1 , i , c0 );
		fmpz_poly_set_coeff_mpz (poly_c2, i, c1);
		aux1 = aux1 >> 1;
		aux2 = aux2 >> 1;

	}while(aux1 != 0 || aux2 !=0);

	nbits=i+1;

	printf("Maximum number of bits is %d", nbits);
	
	double T_Elapsed3 = (double) (clock () - START_enc);
	printf(" Encryption took %f clocks/sec \n ", T_Elapsed3);	
	gettimeofday(&end, NULL);
	seconds  = end.tv_sec  - start.tv_sec;
  	useconds = end.tv_usec - start.tv_usec;
   	mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

   	printf("Elapsed time in Encryption  : %ld milliseconds\n", mtime);
  	/////////////////// Encryption Ends /////////////



	/////////// Evaluation ////////////////////
	clock_t  START_eval = clock();
	gettimeofday(&start, NULL);

	mpz_t * max;
	mpz_t * min;
	max = malloc(sizeof(mpz_t) * nbits);
	min = malloc(sizeof(mpz_t) * nbits);
	for(i=0;i<nbits;i++){
		mpz_init(max[i]);
		mpz_init(min[i]);
	}


	/////////// Evaluation ////////////////////
	//nbits= i +1;
	//fmpz_poly_t max;
	//fmpz_poly_t min;
	//mpz_t * max;
	//mpz_t * min;
	//fmpz_poly_init(max);
	//fmpz_poly_init(min);
	//max = malloc(sizeof(mpz_t) * nbits);
	//min = malloc(sizeof(mpz_t) * nbits);
	//for(i=0;i<nbits;i++){
	//	mpz_init(max[i]);
	//	mpz_init(min[i]);
	//}

	
	mpz_t a_k;
	mpz_t b_k;
	mpz_t tmp;

	mpz_init(a_k);
	mpz_init(b_k);
	mpz_init(tmp);
	
	mpz_t aIsGreater;
	mpz_init(aIsGreater);

	
	min_max(min, max, poly_c1, poly_c2, pk, nbits);
	
	double T_Elapsed4 = (double) (clock () - START_eval);
	printf(" Evaluation took %f clock/sec \n ", T_Elapsed4);
					
	gettimeofday(&end, NULL);
	seconds  = end.tv_sec  - start.tv_sec;
  	useconds = end.tv_usec - start.tv_usec;
   	mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;


   	printf("Elapsed time in Evaluation : %ld milliseconds\n", mtime);
  	


	//////////////// Evaluation Ends ////////////////

/*
		fmpz_poly_set_coeff_mpz(max , k , tmp) ;
		//mpz_set(max[k],tmp);

		fmpz_poly_get_coeff_mpz(a_k, poly_c1,k);	
		fmpz_poly_get_coeff_mpz(b_k, poly_c2,k);
			
		fhe_mul(b_k, b_k, aIsGreater,pk);
		not(tmp, aIsGreater,pk);
		fhe_mul(a_k, a_k, tmp,pk);
		or(tmp, a_k,b_k, pk);

		fmpz_poly_set_coeff_mpz(min , k , tmp) ;
		//mpz_set(min[k],tmp);		
			
	}*/



	///////////////////// Decryption /////////////////
	

	clock_t  START_dec = clock();
	gettimeofday(&start, NULL);

	aux1= 0; aux2= 0;

	unsigned d; int k;
	for(k=nbits-1; k>=0 ;k--){
		d =  fhe_decrypt(max[k],sk);
		aux1= (aux1 * 2) + d;
		
	}

	printf("le max est: %d \n", aux1);

	for(k=nbits-1;k>=0 ;k--){
		d= fhe_decrypt(min[k],sk);
		aux2= (aux2 * 2) +d;
	}
	printf("le min est: %d\n", aux2);
	
	double T_Elapsed5 = (double) (clock () - START_dec);
	printf(" Decryption took  %f clocks/sec \n ", T_Elapsed5);
	gettimeofday(&end, NULL);
	seconds  = end.tv_sec  - start.tv_sec;
  	useconds = end.tv_usec - start.tv_usec;
   	mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;


   	printf("Elapsed time in Decryption : %ld milliseconds\n", mtime);
  	
	//////////////////////// Decryption Ends /////////////
	
	
	for(k=0;k<nbits;k++){
		mpz_clear(max[k]);
		mpz_clear(min[k]);
	}
	

	free(max);
	free(min);
	fmpz_poly_clear( poly_c1 );
	fmpz_poly_clear( poly_c2 ); 
	
	fhe_pk_clear(pk);
	fhe_sk_clear(sk);	
	mpz_clear(c0);
	mpz_clear(c1);
	mpz_clear(a_k);
	mpz_clear(b_k); 
	mpz_clear(tmp);

	mpz_clear(aIsGreater);


}
Пример #29
0
void FeatureEval::drawFloats(boost::shared_ptr<const std::vector<float> > out_img, boost::shared_ptr<PointCloud> cloud){
    if(!visualise_on_)
        return;

    qDebug() << "DRAW!";
    // translates grid idx to cloud idx
    boost::shared_ptr<const std::vector<int>> lookup = cloud->gridToCloudMap();

    if(image_ != nullptr)
        delete image_;
    image_ = new QImage(cloud->scan_width(), cloud->scan_height(), QImage::Format_Indexed8);

    for(int i = 0; i < 256; i++) {
        image_->setColor(i, qRgb(i, i, i));
    }

    float min, max;
    min_max(*out_img, min, max);
    qDebug() << "Minmax" << min << max;

    // Draw image
    auto select = boost::make_shared<std::vector<int> >();
    for(int y = 0; y < cloud->scan_height(); y++){
        for(int x = 0; x < cloud->scan_width(); x++){
            int i = (cloud->scan_height() -1 - y) + x * cloud->scan_height();

            // Mask disabled
            if(lookup->at(i) == -2) {
                image_->setPixel(x, y, 0);
                continue;
            }

            //int intensity = 255 * (1 - distmap[i]/max_dist);
            float mag = (*out_img)[i];
            //int intensity = 255 * (1 - (mag - min)/(max - min));

            int intensity = 255 * (mag - min)/(max - min);

            if(intensity > 255 || intensity < 0) {
                qDebug() << "Nope, sorry > 255 || < 0: " << mag;
                qDebug() << "Mag: " << mag;
                qDebug() << "Intensity" << intensity;
                return;
            }

/*
            // Select
            if(lookup->at(i) != -1 && intensity > 100) {
                select->push_back(lookup->at(i));
            }

            if(intensity < 40) {
                intensity = 0;
            } else {
                intensity = 255;
            }
*/
            image_->setPixel(x, y, intensity);
        }
    }

    qDebug() << "Done";

    core_->us_->beginMacro("Experiment");
    core_->us_->push(new Select(cloud, select));
    core_->us_->endMacro();
    qDebug() << "Done1";
    image_container_->setPixmap(QPixmap::fromImage(*image_));
    qDebug() << "Done1.1";
    image_container_->resize(image_->size());
    qDebug() << "Done 2";

}
Пример #30
0
/* Fonction min-max permettant de déterminer ou jouer
    - le meilleur coup est stocké dans *ti et *tj
    - joueur est le joueur devant joue le meilleur coup
    - joueur_actif est le joueur jouant le tour actuel
    - depth = profondeur actuelle dans l'arbre de recherche
    - max-depth = profondeur maximale, la récursion s'arrête si on l'atteind
 */
int min_max(othello* jeu, char joueur, char joueur_actif, int nb_coups, int*ti, int*tj, int depth, int max_depth){
    
    int meilleur_score =-1;
    int cur_score;
    int i, j;
	
	typedef struct coord_meilleur_coup{ int ligne; int colonne;} coord_MC; //structure des coordonnées d'un meilleur coup
	int compteur_mc= 0; //compteur de meilleur coup 
	coord_MC tab[TAILLE*TAILLE]; /* tableau stockant chaque meilleur coup possible */
	
    /* Si la partie est finie ou si on a atteind la profondeur maximale -> on renvoie le score du plateau */
	if(partie_finie(nb_coups, 0)||depth == max_depth){
		meilleur_score = score(jeu, joueur_actif, depth, nb_coups);
	}
	else {
		//on parcours toutes les positions
		for(i=0; i<TAILLE; i++){
			for(j=0; j<TAILLE; j++){
				//si on a un coup possible on renvoi le meilleur coup a jouer
				if(coup_possible(jeu, joueur_actif, i, j)){
					empiler(*jeu);
					jouer_un_coup(jeu, joueur_actif, i, j);
					cur_score = min_max(jeu, joueur, adversaire(joueur_actif), nb_coups+1, ti, tj, depth+1, max_depth);
					depiler(jeu);
					
					if(joueur_actif == joueur){
						meilleur_score = -1000;
						if(cur_score > meilleur_score){
							meilleur_score = cur_score;
							*ti = i;
							*tj = j;
							tab[compteur_mc].ligne = i;
							tab[compteur_mc].colonne = j;
						}
						compteur_mc++;
					}
					
					if(joueur_actif == adversaire(joueur)){
						meilleur_score = 1000;
						if(cur_score < meilleur_score){
								meilleur_score = cur_score;
								*ti = i;
								*tj = j;
								tab[compteur_mc].ligne = i;
								tab[compteur_mc].colonne = j;
						}
						compteur_mc++;
					}
				} //endif coup_possible()			
			}
		}
		if(compteur_mc > 0){
			int al = rand()%compteur_mc;
			*ti = tab[al].ligne;
			*tj = tab[al].colonne;
		}
		else{
			*ti =-1;
			*tj =-1;
		}
	}
    /*  pour tous les coups possibles
            sauvegarder le jeu (empiler)
            jouer ce coup
            score = appel récursif de min_max avec les paramètres mis à jour
            restaurer le jeu (dépiler)
            
            Si c'est à nous de jouer -> conserver le score max et le coup correspondant
            Si c'est à l'adversaire de jouer -> conserver le score min et le coup correspondant
     
        S'il y a au moins 1 meilleur coup possible
            mettre le coup correspondant dans ti et tj
            Amélioration : choisir aléatoirement un coup parmis les meilleurs possibles
        Sinon
            mettre -1,-1 dans ti et tj
        renvoyer le score
     
     */
    
    
    return meilleur_score;
}