예제 #1
0
int largest(int a, int b)
{
    int l,m;
    if(cache[a][b] != -1)
    return(cache[a][b]);
    else if(a == rows)
    {
    cache[a][b] = z[a][b];
    return(z[a][b]);
    }
    else
    {
     l = largest(a+1,b);
     m = largest(a+1,b+1);
     if(l > m)
     {
     cache[a][b] = z[a][b] + l;
     return(cache[a][b]);
     }
     else
     {
     cache[a][b] = z[a][b] + m;
     return(cache[a][b]);
     }
    }
}
예제 #2
0
int main(void)
// Takes a series of scores from judges and displays all scores,
// the highest score, the lowest score, and the average score.
{
#define scores_size 6
    int scores[scores_size] = {0};
    double score;
    int usable_total;
    double avg;

    for (int i = 0; i < scores_size; i++)
    {
        printf("\nPlease input the score from judge #%d: ", i + 1);
        scanf("%lf", &score);
        score = (int)rint(score*adjust);
        scores[i] = score;
    }
    // Return all scores
    printf("The gymnast's scores are ");
    printArray(scores, scores_size);

    // Sort scores and output high and low values
    sortArray(scores, scores_size);
    printf("The high score is %.1f\n", (double)largest(scores, scores_size) / adjust);
    printf("The low score is %.1f\n", (double)smallest(scores, scores_size) / adjust);

    // Calculate and output average score without high/low values
    usable_total = sum(scores, scores_size);
    usable_total -= largest(scores, scores_size);
    usable_total -= smallest(scores, scores_size);
    avg = average(usable_total, (scores_size - 2));
    printf("The score for this event is %.2f\n", avg / adjust);
}
예제 #3
0
int main()
{
	int x,y,z;
	x=20;
	y=10;
	z=30;
	printf("largest of %d, %d is %d\n",x,y,largest(x,y);
	printf("largest of %d, %d is %d\n",y,z,largest(y,z);
	printf("largest of %d, %d is %d\n",x,z,largest(x,z);

	return 0;
}
예제 #4
0
int main()
{
	double x[100];
	double y[30];
	double z[10];
	
	int i;
	srand(time(NULL));
	
	/* set element to zero	*/
	init(x,100);
	init(y,30);
	init(z , 10);
	
	/*fillArray(&z[0],10);*/
	fillRandom(x,100);
	/*fillRandom(y, 30);*/
	printArray(x,100);
	printf("The largest is :%6.2f\n",largest(x,100));
	doSort(x,100);
	printf("@@@@@@@@@@@  Sorted @@@@@@@@@@@@@@@@@@\n");
	printArray(x,100);
	
	
	
	/*
	printf("Total is :%6.2f\n",sumArray(x,100)+sumArray(y,30)); 
	printf("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
	printf("Total is :%6.2f\n",aveArray(x,100));
	*/
	
	return 0;
}
int main()
{
	struct clinkedlist* last;
	last = NULL;
	int choice;
	int value;
	int p, s, l, d;
	while(1) {
		printf("Choices:\n");
		printf("1. Insert at beginning\n");
		printf("2. Print all the nodes\n");
		printf("3. Print Smallest\n");
		printf("4. Print largest\n");
		printf("5. Print largest - smallest\n");
		printf("6. Exit\n");
		printf("Enter your choice:\n");
		scanf("%d", &choice); 
		
		switch(choice)
		{
			case 1:
				printf("Enter value to be inserted:\n");
				scanf("%d", &value);
				last = insert_beg(last,value);
				break ;
			case 2:
				print_all(last);
				break ;
			case 3:
				s = smallest(last);
				if (s != 0) {
					printf("%d\n", s);
					break;
				}
				printf("List is Empty!!\n");
				break;
			case 4:
				l = largest(last);
				if (l != 0) {
					printf("%d\n", l);
					break;
				}
				printf("List is Empty!!\n");
				break;
			case 5:
				d = difference(last);
				if (d != 0) {
					printf("%d\n", d);
					break;
				}
				printf("List is Empty!!\n");
				break;
			case 6:
				exit(1);
			default:
				printf("Invalid Choice!\n");		
		}
	}
	return 0;
}
예제 #6
0
int main()
{
	double x [100];
	double y [50];
	int i;
	
	srand(time(NULL));
		
	setToZero(x,100);
	/*fillArray(x, 10);*/
	
	fillRandom(&x[0],100);
	printArray(x,100);
	printf("The largest is %6.2f\n",largest(x,100));
	printf("Total is %6.2f\n",sumArray(x,100));
	printf("Ave is %6.2f\n",aveArray(x,100));
	printf("\n@@@@@@@@@@Sorted@@@@@@@@@@@@@@@@@@\n");
	doSort(x,100);
	
	printArray(x,100);
	/*
	fillRandom(y,50);
	printArray(y,50);
	*/
	
	
	
	
	
	
	return 0;
}
예제 #7
0
	Word BallSearch::findWord()
	{
		for (;;) {
			WordPair largest(pairs.top());
			Word result(largest.currentCombination);
			string oldName = result.name;
			findNames(result);			
			pairs.pop();
			largest.setCurrentIndex(largest.distanceIndex+1);
			pairs.push(largest);
			list<Word>::iterator it;
			for (it = words.begin(); it != words.end(); ++it)
				if (result.nameClass == it->nameClass)
					break;
			if (result.nameClass != "" && it == words.end()) {
				double sizeRatio = norm(result.matrix.c) / norm(words.front().matrix.c);
				//fprintf(stderr, "%s: sizeRatio = %f gPower = %d\n", result.name.c_str(), sizeRatio, gPower(result));
				if (sizeRatio < 1) {
					m_foundBigBall = true;
				}
				return result;
			}
			//fprintf(stderr, "rejecting %s^-1 *(%d,%d) %s = %s -> %s (%s)\n",
				//largest.firstWord->name.c_str(),
				//largest.distances[largest.distanceIndex-1].x,
				//largest.distances[largest.distanceIndex-1].y,
				//largest.secondWord->name.c_str(),
				//oldName.c_str(),
				//result.name.c_str(),
				//result.nameClass.c_str()
			//);
			//printf("duplicate; resorting\n");
		}
	}
int difference(struct clinkedlist* last)
{
	int s, l, d;
	s = smallest(last);
	l = largest(last);
	d = l - s;
	return d;
}
예제 #9
0
파일: rgbhist.c 프로젝트: 10crimes/code
 void RGBHistogram::display() {
   #ifdef ALLEGRO
   int winwid=640,winhei=480;
   set_color_depth(24);
   allegrosetup(winwid,winhei);
   PALETTE pal;
   generate_332_palette(pal);
   set_palette(pal);
   float rot=pi/4,elev=pi/8,rotspeed=pi/64;
   int smallize=largest();
   PPsetup(winwid,winhei,3);
   BITMAP *b=create_bitmap(winwid,winhei);
   do {
     clear(b);
     Matrix m1=Matrix();
     m1.makerotation(V3d(0,1,0),rot);
     Matrix m2=Matrix();
     m2.makerotation(V3d(1,0,0),elev);
     for (int i=0;i<quant;i++) {
       for (int j=0;j<quant;j++) {
         for (int k=0;k<quant;k++) {
           V3d c=V3d(i,j,k);
           c=c/c.getlongestside();
           c=c*(float)rgb[i][j][k]/smallize*255;
           // c=c*255;
           c.chop(0,255);
           if (c.getlongestside()>64) {
             V3d v=2*(V3d(i,j,k)/quant-V3d(.5,.5,.5));
             // v=V3d::rotate(v,V3d(0,1,0),rot);
             // v=V3d::rotate(v,V3d(1,0,0),elev);
             v=m1*v;
             v=m2*v;
             V3d u=v+V3d(.02,0,0);
             int x,y,rx,dx;
             PPgetscrpos(v,&x,&y);
             PPgetscrpos(u,&rx,&dx);
             dx=rx-x;
             circle(b,x,y,dx,makecol(c.x,c.y,c.z));
           }
         }
       }
     }
     blit(b,screen,0,0,0,0,winwid,winhei);
     if (key[KEY_LEFT])
       rot-=rotspeed;
     if (key[KEY_RIGHT])
       rot+=rotspeed;
     if (key[KEY_UP])
       elev-=rotspeed;
     if (key[KEY_DOWN])
       elev+=rotspeed;
     if (key[KEY_Z])
       smallize=smallize*1.2;
     if (key[KEY_X])
       smallize=smallize/1.2;
   } while (!key[KEY_ESC]);
   #endif
 }
예제 #10
0
void main()
{
	int a[10],n,i,max1,max2;
	printf("enter the no.of elements");
	scanf("%d",&n);
	printf("enter the elements");
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);
	largest(a,n,&max1,&max2);
	printf("%d\t%d",max1,max2);
}
예제 #11
0
파일: map2d2.c 프로젝트: 10crimes/code
List<Region> Map2d<Object>::collectregions() {
  int numrs=largest();
  List<Region> rs=List<Region>(numrs);
  for (int i=1;i<=numrs;i++)
    rs.add(Region(width,height));
  for (int i=0;i<width;i++)
  for (int j=0;j<height;j++)
    if (getpos(i,j)>0)
      rs.p2num(getpos(i,j))->list->add(Pixel(i,j));
  return rs;
}
예제 #12
0
int main(int argc, char **argv)
{
	int var = 10;

/* When assigning pointer variables, the value should be a memory address. */
	int * p_var = &var; // p_var is a pointer to var

	printf("%x\n", p_var); // Prints address of var
	printf("%d\n", *p_var); // Prints value of var

/* We are able to change the value of var by dereferencing the pointer to
 * var. */
	*p_var += 5;

	int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

/* Array variables are pointer constants, meaning the array name without a
 * subscript is a pointer to the beginning of the array. */

// This means that
	int * p_array = &array[0];
// and
	 p_array = array;
// are equivalent.

/* You can use basic arithmetic on pointers to access later elements
 * of an array. */
	printf("%d\n", *(p_array + 5)); // Prints the 5th element of array
/* This is called array pointer notation. Note that this works the same
 * regardless of the data type of the array. */

/* You can subtract one pointer from another pointer that points to an element
 * in the same array to determine how far apart they are. */
	int * p_array2 = array + 3;
/* Prints the number of elements between p_array2 and p_array. */
	printf("%d\n", p_array2 - p_array);
/* Note that this only works for pointers pointing to elements within the same
 * array. */

/* You must use pointers to pass arrays to functions. Remember that the name
 * of an array (without a subscript) is a pointer to the first element in the
 * array. */
	printf("The largest value in the array is %d.\n", largest(array, 10));

/* When passing a regular variable to a function, only a copy of the value is
 * passed. In other words, a called function cannot alter the value of a
 * variable in the calling function's scope. This is not so with arrays, or
 * with any variable you pass by address. */
	int change_me = 5;
	add_three(&change_me); // change_me passed by address, not value.
	printf("%d\n", change_me); // change_me is altered despite its local scope.

	return 0;
}
예제 #13
0
main()
{
     int numbers[ROW][COLS];
     int i, ans;
     for (i = 0; i < ROW; i++)  {
	  printf("enter data for ROW %d ", i + 1);
          fill(numbers[i], COLS);
          print(numbers[i], COLS);
     }
     ans = largest(numbers, ROW);
     printf("largest is %d\n", ans);
}
예제 #14
0
Real Polynomial::lInfinityNorm(void) const {
  Real largest(RealZero);
  Real current;
  PowersToCoeffMap::const_iterator pc;
  for (pc = terms_.begin(); pc != terms_.end(); ++pc) {
    assert(isValidCoeff(pc->second));
    current = fabs(pc->second); //bad!
    if (current > largest) {
      largest = current;
    }
  }
  return largest;
}
예제 #15
0
int main()
{
	cunit_init();
	int length = 10;
	int input[length];
	int i = 0;
	for(i = 0; i < length; i++)
	{
		input[i] = i;
	}
	
	assert_eq("Testing old with n=1, l=0", largest(input, 1, 0), input[length - 1]);
	assert_eq("Testing old with n=10, l=20", largest(input, 10, 20), input[length - 1]);
	assert_eq("Testing old with n=202, l=0", largest(input, 202, 0), input[length - 1]);
	assert_eq("Testing old with n=10, l=-1", largest(input, 10, -1), input[length - 1]);
	assert_eq("Testing old with n=-1, l=10", largest(input, 10, -1), input[length - 1]);
	
	assert_eq("Testing fixed with standardized n, l=500", largestFixed(input, length, 500), input[length - 1]);
	assert_eq("Testing fixed with standardized n, l=700", largestFixed(input, length, 700), input[length - 1]);
	assert_eq("Testing fixed with standardized n, l=200", largestFixed(input, length, 200), input[length - 1]);
	return 0;
}
예제 #16
0
 std::vector<SyntaxElement> largestMatches(const EBNF& grammar,const std::string& content, const SyntaxElement& previous) {
     /*
         Function that returns a vector of the largest, first occuring matches
         for further processing.
     */
     
     std::vector<SyntaxElement> matches;
     std::vector<std::pair<std::string,std::vector<std::pair<std::string,uint_type> > > > all_matches;
     uint_type index = 0;
     /*
         Find all matches for all regular expressions.
     */
     for (auto& elem : grammar.regex_map) {
         PARSE_OUT << "Finding matches for: " << elem.second.rule_id << std::endl;
         auto regex_matches = RegexHelper::getListOfMatches(elem.second.assemble(grammar.regex_map),content);
         all_matches.push_back(std::pair<std::string,std::vector<std::pair<std::string,uint_type> > >(elem.second.rule_id,regex_matches));
     }
     /*
         Find the  largest match by checking all matches.
     */
     #ifndef EBNF_GIVE_UP_EASILY
     while (index < content.size()) {
     #endif
         bool are_matches = true;
         while(index < content.size() && are_matches) {
             std::pair<std::string,uint_type> largest("",0);
             std::string type_string;
             are_matches = false;
             for (uint_type iter_all = 0; iter_all < all_matches.size(); iter_all++) {
                 for (uint_type iter = 0; iter < all_matches[iter_all].second.size(); iter++) {
                     if (all_matches[iter_all].second[iter].second == index 
                      && all_matches[iter_all].second[iter].first.size() > largest.first.size()
                      && all_matches[iter_all].second[iter].first != content) {
                          type_string = all_matches[iter_all].first;
                          largest = all_matches[iter_all].second[iter];
                          are_matches |= true;
                     }
                 }
             }
             if (are_matches) {
                 index = largest.first.size() + largest.second;
                 matches.push_back(SyntaxElement(largest.second + previous.index, type_string, largest.first));
             }
         }
     #ifndef EBNF_GIVE_UP_EASILY
         index++;
     }
     #endif
     return matches;
 }
예제 #17
0
main()                        
{
     int numbers[ROW][COLS], i, ans;
     
     for (i = 0; i < ROW; i++)
     {
          printf("Entering for ROW %d ", i + 1);
          fill(numbers[i], COLS);
          display(numbers[i], COLS);
     }
     
     ans = largest(numbers, ROW);
     printf("largest is %d\n", ans);
}
예제 #18
0
파일: test.c 프로젝트: AmitMaraj/COMP3000
void findAge(int num){
	int i,j,k;

	for (i=1; i<=Max; i++)
		for (j=1; j<=Max; j++)
			for (k=1; k<=Max; k++){
				if ( ((k*j*i) == num) && (k*2 == (k+j+i)) ) {
						printf("start num %d\n",num);
						printf("the ages are %d %d %d\n",i,j,k );
						printf("the prist age is %d\n", largest(i,j,k)+1 );
						printf("++++++++++++++++++++\n");
						return;
				}
			}
}
예제 #19
0
파일: question9.c 프로젝트: eokeeffe/C-code
void main()
{
	int n,a;
	int A[n]={1,3,5,67,54,-1,-19,-54,0};
	char answer[100];
	while(a<100){answer[a]='\0';a++;}
	a=0;
	
	printf("Please enter the size of the A\r\n");
	printf("if you want all the functions to work please enter 9\r\n");
	scanf("%d",&n);
	
	largest(A,n);
	average(A,n);
	positive(A,n);
}
예제 #20
0
파일: Ex7-3.c 프로젝트: ragmha/C
int main()
{
    int max,min,num1, num2, num3;
    printf("Enter the 1. number:");
    scanf("%d", &num1);
    printf("Enter the 2. number:");
    scanf("%d", &num2);
    printf("Enter the 3. number:");
    scanf("%d", &num3);

    max = largest(num1, num2, num3);
    min = smallest(num1, num2, num3);

    printf("Among the numbers you entered,\nthe largest was %d and the smallest was %d.",max,min);


    return 0;
}
예제 #21
0
int main(){
	struct sockaddr_in server,client;
	int numbers[3],result;
	int sock;
	
	memset((struct sockaddr*)&server,0,sizeof(server));
	memset((struct sockaddr*)&client,0,sizeof(client));
	
	//Set server address
	server.sin_family = AF_INET;
	server.sin_port = htons(SERVER_PORT);
	server.sin_addr.s_addr = inet_addr(LOOPBACK_ADDR);
	//Set client address
	client.sin_family = AF_INET;
	client.sin_port = htons(CLIENT_PORT);
	client.sin_addr.s_addr = inet_addr(LOOPBACK_ADDR);
	int sz = sizeof(client);
	
	//Create socket and bind address
	if((sock = socket(AF_INET,SOCK_DGRAM,0)) == -1){
		perror("socket");
		exit(1);
	}
	if(bind(sock,(struct sockaddr*)&server,sizeof(server)) == -1){
		perror("bind");
		exit(1);
	}
	
	//communication begins
	while(1){
		printf("Waiting for client data...");
		fflush(stdout);
		if(recvfrom(sock,(int*)numbers,sizeof(numbers),0,(struct sockaddr*)&client,&sz) == -1){
			perror("recvfrom");
			exit(1);
		}
		printf("\nRecieved numbers (%d,%d,%d) from client\n",numbers[0],numbers[1],numbers[2]);
		result = largest(numbers,sizeof(numbers)/sizeof(int));
		sendto(sock,(int*)&result,sizeof(result),0,(struct sockaddr*)&client,sz);
		printf("Result sent to the client.\n");
	}	
	
	return 0;
}
예제 #22
0
int main(void)
{
     /* Input MAX values from the keyboard. */

     for (count = 0; count < MAX; count++)
     {
	 printf("Enter an integer value: ");
	 scanf("%d", &array[count]);

	 if ( array[count] == 0 )
	     count = MAX;               /* will exit for loop */
     }
     array[MAX] = 0;

     /* Call the function and display the return value. */
     printf("\n\nLargest value = %d\n", largest(array));

     return 0;
}
예제 #23
0
파일: exec-10.c 프로젝트: clovery410/mycode
int main(void)
{
  int n, i;

  printf("Enter length of the array: ");
  scanf("%d", &n);

  int a[n];

  printf("Ente array elements: ");
  for (i = 0; i < n; i++)
    scanf("%d", &a[i]);
  
  printf("The largest element of this array is: %d\n", largest(a, n));
  printf("The average of all elements in this array is: %d\n", average(a, n));
  printf("The number of positive elements in this array is: %d\n", num_positive(a, n));

  return 0;
}
예제 #24
0
파일: main.c 프로젝트: jennylia/CPractice
int main(){
    printf("Hello my darling\n");
    i = 0;
    while(1){
        printf("Enter a number please: \n");
        scanf("%d", &array[i]);
        
        if(array[i] == 0)
            break;
        
        i++;
        
    }
    
    int answer = largest(array);
    
    printf("And the largest number is %d in this array\n", answer);
    return 1;
}
예제 #25
0
int main()
{
	struct tnode *root;
	int lcv;
	FILE *fp;
 
	char word[MAXWORD];
	root = NULL;
 
	while (getword(word, MAXWORD) != EOF) {
		if (isalpha(word[0]) || word[0] == '\'')
			root = addtree(root, word);
	}
	//treeprint(root);

	fp = fopen( "words.txt", "w" );

	printf( "Most common 256 words, weighted by lengths\n" );

	for( lcv = 0; lcv < 256; lcv++ ) {
		struct tnode *node;
		
		do {
			node = largest( root );
			if( strlen( node -> word ) > 1 ) break;
			node -> count = 0;
		} while( 1 );

		printf( "%4d %s\n", node -> count, node -> word );
		fprintf( fp, "%s\n", node -> word );
		node -> count = 0;

		if( lcv == 127 ) printf( "\n----------------------------\n\n" );
	}

	destroy( root );

	fclose( fp );
 
	return 0;
}
예제 #26
0
파일: test.c 프로젝트: akhilmd/btech-sem3
void test_rec()
{
    printf("\tTesting Recursion Algorithms...\n\n");

    long num = 20;
    printf("factorial of %ld = %ld\n", num, fact(num));

    int len = 10000;
    int i = 0;

    int numbers[len];

    for (i = 0; i < len; ++i)
        numbers[i] = i + 1;

    printf("sum of array = %d\n", sumArray(numbers, len));
    printf("largest in array = %d\n", largest(numbers, len));
    printf("largest in array = %d\n", largest2(numbers, 0, len - 1));

    int big_num = 203041;
    printf("sum of digits of %d = %d\n", big_num, sumOfDigits(big_num));
}
예제 #27
0
void radixsort(int raw[],int n){
	int pass,remainder,nod=0,i,j,k,large,divisor=1;
	large=largest(raw,n);
	while(large>0){
		nod++;
		large/=10;
	}
	int bucket[10][n],bucketcount[10];
	for(pass=0;pass<nod;pass++){
        for(i=0;i<10;i++)
		bucketcount[i]=0;
		for(i=0;i<n;i++){
			remainder=(raw[i]/divisor)%10;
			bucket[remainder][bucketcount[remainder]++]=raw[i];
		}
		i=0;
		for(k=0;k<10;k++){
			for(j=0;j<bucketcount[k];j++)
				raw[i++]=bucket[k][j];
		}
		divisor*=10;
	}
}
예제 #28
0
파일: std_types.cpp 프로젝트: sarnold/cbmc
constant_exprt unsignedbv_typet::largest_expr() const
{
  return to_constant_expr(from_integer(largest(), *this));
}
예제 #29
0
char *V_pretifymem( float value, int digitsafterdecimal /*= 2*/, bool usebinaryonek /*= false*/ )
{
	static char output[ NUM_PRETIFYMEM_BUFFERS ][ 32 ];
	static int  current;

	float		onekb = usebinaryonek ? 1024.0f : 1000.0f;
	float		onemb = onekb * onekb;

	char *out = output[ current ];
	current = ( current + 1 ) & ( NUM_PRETIFYMEM_BUFFERS -1 );

	char suffix[ 8 ];

	// First figure out which bin to use
	if ( value > onemb )
	{
		value /= onemb;
		V_snprintf( suffix, sizeof( suffix ), " MB" );
	}
	else if ( value > onekb )
	{
		value /= onekb;
		V_snprintf( suffix, sizeof( suffix ), " KB" );
	}
	else
	{
		V_snprintf( suffix, sizeof( suffix ), " bytes" );
	}

	char val[ 32 ];

	// Clamp to >= 0
	digitsafterdecimal = largest( digitsafterdecimal, 0 );

	// If it's basically integral, don't do any decimals
	if ( fabs( value - (int)value ) < 0.00001 )
	{
		V_snprintf( val, sizeof( val ), "%i%s", (int)value, suffix );
	}
	else
	{
		char fmt[ 32 ];

		// Otherwise, create a format string for the decimals
		V_snprintf( fmt, sizeof( fmt ), "%%.%if%s", digitsafterdecimal, suffix );
		V_snprintf( val, sizeof( val ), fmt, value );
	}

	// Copy from in to out
	char *i = val;
	char *o = out;

	// Search for decimal or if it was integral, find the space after the raw number
	char *dot = strstr( i, "." );
	if ( !dot )
	{
		dot = strstr( i, " " );
	}

	// Compute position of dot
	int pos = dot - i;
	// Don't put a comma if it's <= 3 long
	pos -= 3;

	while ( *i )
	{
		// If pos is still valid then insert a comma every third digit, except if we would be
		//  putting one in the first spot
		if ( pos >= 0 && !( pos % 3 ) )
		{
			// Never in first spot
			if ( o != out )
			{
				*o++ = ',';
			}
		}

		// Count down comma position
		pos--;

		// Copy rest of data as normal
		*o++ = *i++;
	}

	// Terminate
	*o = 0;

	return out;
}
예제 #30
0
/**Function********************************************************************

  Synopsis    [Genetic algorithm for DD reordering.]

  Description [Genetic algorithm for DD reordering.
  The two children of a crossover will be stored in
  storedd[popsize] and storedd[popsize+1] --- the last two slots in the
  storedd array.  (This will make comparisons and replacement easy.)
  Returns 1 in case of success; 0 otherwise.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
int
cuddGa(
  DdManager * table /* manager */,
  int  lower /* lowest level to be reordered */,
  int  upper /* highest level to be reorderded */)
{
    int 	i,n,m;		/* dummy/loop vars */
    int		index;
#ifdef DD_STATS
    double	average_fitness;
#endif
    int		small;		/* index of smallest DD in population */

    /* Do an initial sifting to produce at least one reasonable individual. */
    if (!cuddSifting(table,lower,upper)) return(0);

    /* Get the initial values. */
    numvars = upper - lower + 1; /* number of variables to be reordered */
    if (table->populationSize == 0) {
	popsize = 3 * numvars;  /* population size is 3 times # of vars */
	if (popsize > 120) {
	    popsize = 120;	/* Maximum population size is 120 */
	}
    } else {
	popsize = table->populationSize;  /* user specified value */
    }
    if (popsize < 4) popsize = 4;	/* enforce minimum population size */

    /* Allocate population table. */
    storedd = ALLOC(int,(popsize+2)*(numvars+1));
    if (storedd == NULL) {
	table->errorCode = CUDD_MEMORY_OUT;
	return(0);
    }

    /* Initialize the computed table. This table is made up of two data
    ** structures: A hash table with the key given by the order, which says
    ** if a given order is present in the population; and the repeat
    ** vector, which says how many copies of a given order are stored in
    ** the population table. If there are multiple copies of an order, only
    ** one has a repeat count greater than 1. This copy is the one pointed
    ** by the computed table.
    */
    repeat = ALLOC(int,popsize);
    if (repeat == NULL) {
	table->errorCode = CUDD_MEMORY_OUT;
	FREE(storedd);
	return(0);
    }
    for (i = 0; i < popsize; i++) {
	repeat[i] = 0;
    }
    computed = st_init_table(array_compare,array_hash);
    if (computed == NULL) {
	table->errorCode = CUDD_MEMORY_OUT;
	FREE(storedd);
	FREE(repeat);
	return(0);
    }

    /* Copy the current DD and its size to the population table. */
    for (i = 0; i < numvars; i++) {
	STOREDD(0,i) = table->invperm[i+lower]; /* order of initial DD */
    }
    STOREDD(0,numvars) = table->keys - table->isolated; /* size of initial DD */

    /* Store the initial order in the computed table. */
    if (st_insert(computed,(char *)storedd,(char *) 0) == ST_OUT_OF_MEM) {
	FREE(storedd);
	FREE(repeat);
	st_free_table(computed);
	return(0);
    }
    repeat[0]++;

    /* Insert the reverse order as second element of the population. */
    for (i = 0; i < numvars; i++) {
	STOREDD(1,numvars-1-i) = table->invperm[i+lower]; /* reverse order */
    }

    /* Now create the random orders. make_random fills the population
    ** table with random permutations. The successive loop builds and sifts
    ** the DDs for the reverse order and each random permutation, and stores
    ** the results in the computed table.
    */
    if (!make_random(table,lower)) {
	table->errorCode = CUDD_MEMORY_OUT;
	FREE(storedd);
	FREE(repeat);
	st_free_table(computed);
	return(0);
    }
    for (i = 1; i < popsize; i++) {
	result = build_dd(table,i,lower,upper);	/* build and sift order */
	if (!result) {
	    FREE(storedd);
	    FREE(repeat);
	    st_free_table(computed);
	    return(0);
	}
	if (st_lookup_int(computed,(char *)&STOREDD(i,0),&index)) {
	    repeat[index]++;
	} else {
	    if (st_insert(computed,(char *)&STOREDD(i,0),(char *)(long)i) ==
	    ST_OUT_OF_MEM) {
		FREE(storedd);
		FREE(repeat);
		st_free_table(computed);
		return(0);
	    }
	    repeat[i]++;
	}
    }

#if 0
#ifdef DD_STATS
    /* Print the initial population. */
    (void) fprintf(table->out,"Initial population after sifting\n");
    for (m = 0; m < popsize; m++) {
	for (i = 0; i < numvars; i++) {
	    (void) fprintf(table->out," %2d",STOREDD(m,i));
	}
	(void) fprintf(table->out," : %3d (%d)\n",
		       STOREDD(m,numvars),repeat[m]);
    }
#endif
#endif

    small = find_best();
#ifdef DD_STATS
    average_fitness = find_average_fitness();
    (void) fprintf(table->out,"\nInitial population: best fitness = %d, average fitness %8.3f",STOREDD(small,numvars),average_fitness);
#endif

    /* Decide how many crossovers should be tried. */
    if (table->numberXovers == 0) {
	cross = 3*numvars;
	if (cross > 60) {	/* do a maximum of 50 crossovers */
	    cross = 60;
	}
    } else {
	cross = table->numberXovers;      /* use user specified value */
    }

    /* Perform the crossovers to get the best order. */
    for (m = 0; m < cross; m++) {
	if (!PMX(table->size)) {	/* perform one crossover */
	    table->errorCode = CUDD_MEMORY_OUT;
	    FREE(storedd);
	    FREE(repeat);
	    st_free_table(computed);
	    return(0);
	}
	/* The offsprings are left in the last two entries of the
	** population table. These are now considered in turn.
	*/
	for (i = popsize; i <= popsize+1; i++) {
	    result = build_dd(table,i,lower,upper); /* build and sift child */
	    if (!result) {
		FREE(storedd);
		FREE(repeat);
		st_free_table(computed);
		return(0);
	    }
	    large = largest();	/* find the largest DD in population */

	    /* If the new child is smaller than the largest DD in the current
	    ** population, enter it into the population in place of the
	    ** largest DD.
	    */
	    if (STOREDD(i,numvars) < STOREDD(large,numvars)) {
		/* Look up the largest DD in the computed table.
		** Decrease its repetition count. If the repetition count
		** goes to 0, remove the largest DD from the computed table.
		*/
		result = st_lookup_int(computed,(char *)&STOREDD(large,0),
				       &index);
		if (!result) {
		    FREE(storedd);
		    FREE(repeat);
		    st_free_table(computed);
		    return(0);
		}
		repeat[index]--;
		if (repeat[index] == 0) {
		    int *pointer = &STOREDD(index,0);
		    result = st_delete(computed, (char **)&pointer,NULL);
		    if (!result) {
			FREE(storedd);
			FREE(repeat);
			st_free_table(computed);
			return(0);
		    }
		}
		/* Copy the new individual to the entry of the
		** population table just made available and update the
		** computed table.
		*/
		for (n = 0; n <= numvars; n++) {
		    STOREDD(large,n) = STOREDD(i,n);
		}
		if (st_lookup_int(computed,(char *)&STOREDD(large,0),
				  &index)) {
		    repeat[index]++;
		} else {
		    if (st_insert(computed,(char *)&STOREDD(large,0),
		    (char *)(long)large) == ST_OUT_OF_MEM) {
			FREE(storedd);
			FREE(repeat);
			st_free_table(computed);
			return(0);
		    }
		    repeat[large]++;
		}
	    }
	}
    }

    /* Find the smallest DD in the population and build it;
    ** that will be the result.
    */
    small = find_best();

    /* Print stats on the final population. */
#ifdef DD_STATS
    average_fitness = find_average_fitness();
    (void) fprintf(table->out,"\nFinal population: best fitness = %d, average fitness %8.3f",STOREDD(small,numvars),average_fitness);
#endif

    /* Clean up, build the result DD, and return. */
    st_free_table(computed);
    computed = NULL;
    result = build_dd(table,small,lower,upper);
    FREE(storedd);
    FREE(repeat);
    return(result);

} /* end of cuddGa */