Ejemplo n.º 1
0
int main ()
{
    int numItems = 0, i, searchItem = 0, algoIdx = 0;
    Boolean itemFound = FALSE;

    printf ("\nEnter the number of items in search array (1-100): ");
    while (1)
    {
        scanf ("%d", &numItems);
        if ((numItems <= 100) && (numItems > 0))
        {
            break;
        }
        printf ("\nEntered value is greater than 100 or is negative, please enter a value between 1-100: ");
    }
    printf ("\nPlease enter the list of values to fill the search array:");
    for (i = 0; i < numItems; i++)
    {
        scanf ("%d", &searchArr[i]);
    }

    while (1)
    {
        printf ("\nEnter the search item:");
        scanf ("%d", &searchItem);

        printf ("\nList of search algo's available:\n");
        printf ("1) Linear search\n2) Linear search with sentinel\n3) Exit\n");
        printf ("Choose one:");
        scanf ("%d", &algoIdx);

        switch (algoIdx)
        {
        case 1:
            itemFound = linearSearch (numItems, searchItem);
            break;
        case 2:
            itemFound = linearSearchSentinel (numItems, searchItem);
            break;
        case 3:
            printf ("\nExiting...\n");
            exit(0);
        default:
            printf ("\nOption not available, defaulting to Linear search!\n");
            itemFound = linearSearch (numItems, searchItem);
            break;
        }

        if (itemFound == TRUE)
        {
            printf ("Holy Cow!!! Item %d is found in the DB\n", searchItem);
        }
        else
        {
            printf ("Oops! The item you requested is not found in the DB\n");
        }
    }

    return 0;
}
Ejemplo n.º 2
0
/*Main method, automated test*/
int main(){
 
  int array[] = {1, 2, 3, 4};
  
  printf("Start of Automated test\n\n");
  
  /*Test for factorial*/
  printf("Factorial Test Start\n");
  
  if(factorial(0) == 1) printf("Passed\n");
  else printf("Failed\n");
  
  if(factorial(1) == 1) printf("Passed\n");
  else printf("Failed\n");
  
  if(factorial(6) == 720) printf("Passed\n\n");
  else printf("Failed\n\n");
  
  /*Test for Fibonacci*/
  printf("Fibonacci Test Start\n\n");
  
  if(fibonacci(0) == 0) printf("Passed\n");
  else printf("Failed\n");
  
  if(fibonacci(1) == 1) printf("Passed\n");
  else printf("Failed\n");
  
  if(fibonacci(6) == 8) printf("Passed\n\n");
  else printf("Failed\n\n");
  
  /*Test for linearSearch*/
  printf("Linear Search Test Start\n\n");
  
  if(linearSearch(array, 4, 3) == 2) printf("Passed\n");
  else printf("Failed\n");
  
  if(linearSearch(array, 4, 1) == 0) printf("Passed\n");
  else printf("Failed\n");
  
  if(linearSearch(array, 4, 4) == 3) printf("Passed\n\n");
  else printf("Failed\n\n");
  
  /*Test for Sumation*/
  printf("Sumation Test Start\n\n");
  
  if(sum(0) == 0) printf("Passed\n");
  else printf("Failed\n");
  
  if(sum(1) == 1) printf("Passed\n");
  else printf("Failed\n");
  
  if(sum(5) == 15) printf("Passed\n\n");
  else printf("Failed\n\n");
  
  printf("End of Automated test\n");
  
  return 0;

}
Ejemplo n.º 3
0
int main() {
    srand(time(NULL));
    int sizeLijst = 10;

    int* lijst = generateRandomList(sizeLijst);
    printf("Lijst ongesorteerd: ");
    printList(lijst, sizeLijst);

    int teZoekenGetal;
    do{
        printf("Geef een getal (-1 = exit):");
        scanf("%d*c",&teZoekenGetal);
        if(teZoekenGetal != -1){
            int indexGetal = linearSearch(lijst, sizeLijst, teZoekenGetal);
            if (indexGetal==-1) {
                printf("'%d' is niet gevonden in de lijst! ", teZoekenGetal);
            } else {
                printf("'%d' staat op positie %d in de lijst! ", teZoekenGetal, indexGetal);
            }
            printf("(#compares = %d)\n",compareCounter);
        }
    }while(teZoekenGetal != -1);

    free(lijst);

    return 0;
}
Ejemplo n.º 4
0
/* function main begins program execution */
int main( void )
{   
   int a[ SIZE ]; /* create array a */
   int x; /* counter for initializing elements 0-99 of array a */
   int searchKey; /* value to locate in array a */
   int element; /* variable to hold location of searchKey or -1 */

   /* create data */
   for ( x = 0; x < SIZE; x++ ) { 
      a[ x ] = 2 * x;
   } /* end for */

   printf( "Enter integer search key:\n" );
   scanf( "%d", &searchKey );

   /* attempt to locate searchKey in array a */
   element = linearSearch( a, searchKey, SIZE );

   /* display results */
   if ( element != -1 ) {
      printf( "Found value in element %d\n", element );
   } /* end if */
   else {
      printf( "Value not found\n" );
   } /* end else */

   return 0; /* indicates successful termination */
} /* end main */
Ejemplo n.º 5
0
int
main(int argc, char *argv[])
{
    char *sorted_data[26] = {
	"ALPHA","BRAVO","CHARLIE","DELTA","ECHO","FOXTROT","GOLF",
	"HOTEL","INDIA","JULIET","KILO","LIMA","MIKE","NOVEMBER",
	"OSCAR","PAPA","QUEBEC","ROMEO","SIERRA","TANGO","UNIFORM",
	"VICTOR","WHISKY","X-RAY","YANKEE","ZULU",
    };
    int index;


    printf("linear_search : \n");
    index = linearSearch(sorted_data, 26, "TANGO");
    printf("index = %d\n", index);
    printf("\n");

    printf("binary_search : \n");
    index = binarySearch(sorted_data, 26, "TANGO");
    printf("index = %d\n", index);
    printf("\n");

    printf("binary_search_recursive : \n");
    index = binarySearch_recursive(sorted_data, 0, 26, "TANGO");
    printf("index = %d\n", index);
    printf("\n");

    return 0;
}
Ejemplo n.º 6
0
int main(void){
	int array[25]={5,6,7,1,2,3,-10,56,100,-1};
	int location;
	int key=-20;
	location = linearSearch(key,array,10);
	printf("the number %d was found at : %d\n",key,location);
	selectionSort(array,10);
	printArray(array,10,10);
}
Ejemplo n.º 7
0
int main()
{
	int len = 8;
	int A[8] = {0, 1, 2, 3, 4, 5, 6, 7};
	printf("%d\n", linearSearch(A, len, 3));
	printf("%d\n", binarySearch(A, len, 4));

	return 0;
}
Ejemplo n.º 8
0
int linearSearch(int A[], int s, int i, int n){
    if( i == n )
        return -1;

    if( A[i] == s )
        return i;

    return linearSearch(A, s, ++i, n);
}
Ejemplo n.º 9
0
int main()
{
	int a[5] = {1,2,3,4,5};
	int check = linearSearch(a,5,6); 
	if (check)
		printf("found");
	else 
		printf("not_found");

}
Ejemplo n.º 10
0
int main(int argc, char* argv[]){

   // varible declarations
  int i=0,j=0,length=0,*array=NULL, temp=0,key=0,found=0;
  double arrayTime, nodeTime;
  Node* head=NULL;
  clock_t start,end;
  
  key = atoi(argv[1]);// change string to integer
  printf("%-15s%-15s\n","Linear search","Node Search");
 
  //loop for all the argumens
  for(i=2; i<argc; i++){
    FILE* input = fopen(argv[i],"r");
    if(input == NULL){
      printf("Unable to open %s\n",argv[i]);
    }

    else{
      fscanf(input,"%d",&length);
      array = (int *)malloc(length*sizeof(int));
      for(j=0;j<length;j++){
        fscanf(input,"%d",&temp);
        array[j] = temp;
        head = insert_end(head, temp);
      }
      //timing the algorith
      start = clock();
      found = linearSearch(array,length,key);
      end = clock();
      arrayTime = (double)(end-start)/CLOCKS_PER_SEC;
      //check if the search was found 
      if(found == 0){
        printf("number not found in linear search\n");
      }
      start = clock();
      found = nodeSearch(head, key);
      end = clock();
      nodeTime = (double)(end-start)/CLOCKS_PER_SEC;
      if(found == 0){
        printf("number not found in node search\n");
      }
      
    
      printf("%-15lf%-15lf\n",arrayTime,nodeTime);
      //free the malloced memory 
      free(array);
      free_node(head);
      head = NULL;
    }
    close(input);//close the input file
  }
 

}
Ejemplo n.º 11
0
void SelectionRaster::updateSelection(TRasterCM32P cm,
                                      const BlendParam &param) {
  // Make a hard copy of color indexes. We do so since we absolutely prefer
  // having them SORTED!
  std::vector<int> cIndexes = param.colorsIndexes;
  std::sort(cIndexes.begin(), cIndexes.end());

  unsigned int lx = cm->getLx(), ly = cm->getLy(), wrap = cm->getWrap();

  // Scan each cm pixel, looking if its ink or paint is in param's colorIndexes.
  cm->lock();
  TPixelCM32 *pix, *pixBegin = (TPixelCM32 *)cm->getRawData();

  SelectionData *selData = data();

  const int *v =
      &cIndexes[0];  // NOTE: cIndexes.size() > 0 due to external check.
  unsigned int vSize = cIndexes.size();
  unsigned int i, j;

  // NOTE: It seems that linear searches are definitely best for small color
  // indexes.
  if (vSize > 50) {
    for (i = 0; i < ly; ++i) {
      pix = pixBegin + i * wrap;
      for (j = 0; j < lx; ++j, ++pix, ++selData) {
        selData->m_selectedInk   = binarySearch(v, vSize, pix->getInk());
        selData->m_selectedPaint = binarySearch(v, vSize, pix->getPaint());
      }
    }
  } else {
    for (i = 0; i < ly; ++i) {
      pix = pixBegin + i * wrap;
      for (j = 0; j < lx; ++j, ++pix, ++selData) {
        selData->m_selectedInk   = linearSearch(v, vSize, pix->getInk());
        selData->m_selectedPaint = linearSearch(v, vSize, pix->getPaint());
      }
    }
  }

  cm->unlock();
}
Ejemplo n.º 12
0
void main(void)
{
	int * intArrays[COPIES], i, arraySize, value;
	clrscr();
	printf("This program sorts and searches integer values!\n");
	printf("please give me number of values you wish to deal with: ");
	scanf("%d", &arraySize);

	for(i = 0;i < COPIES; i++)
		intArrays[i] = (int *) malloc(sizeof(int) * arraySize);
	readValues(intArrays, arraySize);

	printf("Enter number to search for? (linear search): ");
	scanf("%d", &value);
	if (linearSearch(intArrays[0], arraySize, value) != -1)
		printf("Found !\n");
	else
		printf("Not Found!\n");
	getch();
	printValues(intArrays, arraySize);
	printf("\nSorting Array 1 using bubble....\n");
	bubble(intArrays[0], arraySize);
	printValues(intArrays, arraySize);

	printf("\nSorting Array 2 using selection....\n");
	selection(intArrays[1], arraySize);
	printValues(intArrays, arraySize);

	printf("\nSorting Array 3 using insertion....\n");
	insertion(intArrays[2], arraySize);
	printValues(intArrays, arraySize);


	printf("Enter number to search for? (binary search): ");
	scanf("%d", &value);
	if (linearSearch(intArrays[0], arraySize, value) != -1)
		printf("Found !\n");
	else
		printf("Not Found!\n");

	getch();
}
Ejemplo n.º 13
0
/*
 * Summary:     Adjusts the vote count based on a recent vote.
 * Parameters:  u32 index of the node that voted, u32 ballot of the node.
 * Return:      None.
 */
void
voteCount(u32 NODE_INDEX, u32 BALLOT)
{
  if (NODE_INDEX < 0)
    {
      logNormal("voteCount:  Invalid node index %d", NODE_INDEX);
      API_ASSERT_GREATER_EQUAL(NODE_INDEX, 0); // blinkcode!
    }

  if (BALLOT < 0)
    {
      logNormal("voteCount:  Invalid ballot %d", BALLOT);
      API_ASSERT_GREATER_EQUAL(BALLOT, 0); // blinkcode!
    }

  if (0 == BALLOT) // 0 is never a correct answer
    return; // But it's not worth blinkcoding over

  else if (BALLOT == VOTE_NODE_ARR[NODE_INDEX])
    return; // Ignore duplicate votes

  // Invalid vote if I've already voted (didn't flush from a new calculation)
  else if (0 != VOTE_NODE_ARR[NODE_INDEX])
    return;

  else if (0 == VOTE_NODE_ARR[NODE_INDEX]) // Haven't voted yet
    ++VOTE_COUNT; // This is the first vote received

  if (VOTE_COUNT > NODE_COUNT) // Someone voted multiple times
    {
      flush(); // Clean out memory
      voteCount(0, calculate(HOST_CALC)); // Recount our own vote
      return;
    }

  // look to see if the ballot is for an existing candidate
  u32 k = linearSearch(CANDIDATE_ARR, CANDIDATE_COUNT + 1, BALLOT);

  if (INVALID != k) // if so, give him a vote
    ++CANDIDATE_VOTES_ARR[k];

  else // otherwise the ballot is new to the candidate list
    { // so add it
      k = CANDIDATE_COUNT++; // Give him a vote
      CANDIDATE_ARR[k] = BALLOT; // Add the new candidate to the nominations list
      ++CANDIDATE_VOTES_ARR[k]; // Give the candidate a vote
    }

  VOTE_NODE_ARR[NODE_INDEX] = BALLOT; // record the node's ballot

  evalMajority(); //Reevaluate the majority with every different ballot

  return;
}
Ejemplo n.º 14
0
//Recursive Version of Linear Serach
//Returns the number if found
//returns -1 if not found
int linearSearch(int a[], int n, int key)
{
    if (n < 0 ) 
    {
          return -1;
    }
    if(key == a[n-1])
    {
           return n - 1;
    } 
    return linearSearch(a, n-1, key); 
}
Ejemplo n.º 15
0
int main(void)
{
  double testArray[] = {0, 3, 4, 2};
  int begin = 0, end = 3;
  double searchValue = 3;
  int index;

  index = linearSearch(testArray, begin, end, searchValue);

  printf("%d\n", index);

  return 0;
}
Ejemplo n.º 16
0
int main()
{
    int a[SIZE] = {9,4,5,1,7,78,22,15,96,45}, key, pos;
    printf("Enter the search key :\n");
    scanf("%d", &key);
    pos = linearSearch(a,key);
    if(pos == -1)
        printf("the search key is not in array\n");
    else
        printf("the search key %d is at location %d\n", key, pos);
    
    return 0;
}
Ejemplo n.º 17
0
//Main Function
int main() {
  //Memory-efficient array
  int n;
  scanf("%d",&n);
  int arr[n],key,x;
  
  //Key for element to search
  printf("Enter the value of the key");
  scanf("%d",&key);
  
  //Function call
  linearSearch(arr,n,key);
  return 0;
}
Ejemplo n.º 18
0
/*Linear Search with recursion*/
int linearSearch(const int array[], int length, int value) {
  
  //searching backwards from the size to 0 (Termination code) 
  if(length==0){
    return -1;
  }
  
  //if the element if found we return the position 
  else if (array[length-1]==value) {
    return length-1;
  }
  
  //else we keep searching (recursive code) 
  else{ 
    return linearSearch( array, length-1, value); 
  }
} 
Ejemplo n.º 19
0
int main() {
    int searchFor = 0;
    
    printf("What number would you like to search for?\n");
    scanf("%d", &searchFor);
    printf("Right-o, searching for %d!\n", searchFor);
    
    for (int i = 0; i < arraySize; i++) {
        printf("Index #%d: %d\n", i, primes[i]);
    }
    
    searchResult lSearchResult = linearSearch(&primes, arraySize, searchFor);
    
    printf("Linear search for %d completed. Found target value at index %d, in %d guesses.\n", searchFor, lSearchResult.index, lSearchResult.numberOfGuesses);
    
    return 0;
}
Ejemplo n.º 20
0
int main()
{
    // varaiables
    int arrList[] = {121, 103, 69, 87, 110, 12, 55, 47, 35, 63, 6, 79, 8, 95, 3, 130, 21, 1 };
    int value = 55;

    bool result = linearSearch(arrList, value);

    if (result == true)
    {
        printf("Number was found!\n");
    }
    else
    {
        printf("Number was NOT found!\n");
    }
    return 0;
}
int main()
{
    int a[100], i, n, sval,found=0;
    printf("Enter size of array: ");
    scanf("%d",&n);
    printf("enter element of array: ");
    for(i=1; i<=n; i++)
        scanf("%d",&a[i]);
    printf("Enter search value: ");
    scanf("%d",&sval);
    found = linearSearch(a,n,sval);
    if(found == 1)
    {
        printf("value found in %d index\n",index-1);
    }
    else
    {
        printf("value not found");
    }
    return 0;
}
void printMenu(){
	int ch,x,y;
	printf("\nMAIN MENU");
	printf("\n1.Linear Search for x");
	printf("\n2.Binary Search for x");
	printf("\n3.Number of repetitions for x");
	printf("\nEnter your choice ");
	scanf("%d", &ch);
	switch (ch){
		case 1:	printf("\nEnter the number you want to search ");
				scanf("%d", &x);
				begin = clock();
				linearSearch(A,x);
				end = clock();
				time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
				printf("\nRun Time %f", time_spent);
				break;
		case 2: printf("\nEnter the number you want to search ");
				scanf("%d", &x);
				begin = clock();
				binarySearch(A,x);
				end = clock();
				time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
				printf("\nRun time %f", time_spent);
				break;
		case 3: printf("\nEnter the number you want to search ");
				scanf("%d", &x);
				begin = clock();
				y = reps(A,x);
				end = clock();
				time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
				printf("\nNumber of repetitions for the number: %d", y);
				printf("\nRun time %f", time_spent);
				break;
		default: printf("\nInvalid option ");
				 break;
	}

}
Ejemplo n.º 23
0
int main() {
    int A[MAX], n, i, s;

    printf("Enter Number of Elements: ");
    scanf("%d", &n);

    printf("Enter %d Elements:\n", n);
    for(i=0; i<n; i++)
        scanf("%d", &A[i]);

    printf("Enter Element to Search: ");
    scanf("%d", &s);

    i = linearSearch(A, s, 0, n) ;

    if( i != -1 )
        printf("%d found at index %d\n", s, i+1);
    else
        printf("%d not found\n", s);

    return 0;
}
Ejemplo n.º 24
0
Exosystem* Data::search(Exoplanet& key, char sortingKey) const
{
	Exoplanet* result;
	if (sortingKey == 'N')
	{
		result = new Exoplanet(key);
		Exoplanet** temp = hashTable->search(result);
		if (temp == nullptr) result = nullptr;
		else result = *temp;
	}
	else if (isSortedOnKey == sortingKey)
	{
		result = binarySearch(key, *planets, sortingKey);
	}
	else
	{
		result = linearSearch(key, *planets, sortingKey);
	}

	if (result == nullptr) return nullptr;

	return result->getSystemPointer();
}
Ejemplo n.º 25
0
int main(){
	int list[10];
	int i,n,no,val;
	printf("Enter number of arrays\n");
	scanf("%d",&n);
	printf("Enter Numbers in an array:\n");
	for (i = 0; i < n; i++)
	{
		scanf("%d",&list[i]);
	}
	printf("Enter number to be Searched:\t");
	scanf("%d",&no);
	val=linearSearch(list,n,no);
	if (val!=-1)
	{
		/* 23code */
		printf("Item found at position: %d \n",val);
	}
	else{
		printf("Not Found\n");
	}
	return 0;

}
Ejemplo n.º 26
0
main()
{
int i=0,j=0,num,distinct
;
int a[10];
while(i<10)
{
distinct=0;
j=0;
while(j<10)
{
scanf("%d",&num);

if(linearSearch(a,(num%42),j))
{
distinct++;
}
a[j]=num%42;
j++;
}
printf("%d\n",distinct);
i++;
}
}
Ejemplo n.º 27
0
int main()
{
    //variable declrations
    int myArray[50], myArray2[] = {1, 2, 3, 4, 5}, myArray3[] = {1, 2, 3, 4, 5};
    int index, searchResults, key;


    //testing fillArray
    fillArray(myArray, 50, 1000);
    //testing printNperline()
    printf("Before sort printing 10 per line\n");
    printNperline(myArray, 50, 10);

    printf("\n");
    printf("Before sort printing 4 per line\n");
    printNperline(myArray, 50, 4);

    printf("\n");
    printf("Before sort printing 6 per line\n");
    printNperline(myArray, 50, 6);

    //testing bubble sort on myArray
    bubbleSort(myArray, 50);

    //printing myArray after sort
    printf("\n");
    printf("After sort printing 6 per line\n");
    printNperline(myArray, 50, 6);

    printf("\n");
    printf("After sort printing 15 per line\n");
    printNperline(myArray, 50, 15);

    printf("\n");
    printf("After sort printing 11 per line\n");
    printNperline(myArray, 50, 11);

    //testing linear search
    printf("\n");
    printf("Testing linear search for 82\n");
    key = 82;
    searchResults = linearSearch(myArray, 50, key);

    if(searchResults >= 0)
        printf("The key value %d was found in myArray at position %d\n", key, searchResults);
    else
        printf("The key value %d was not found in myArray\n", key);

    printf("\n");
    printf("Testing linear search for %d which is the last element in the array\n", myArray[49]);
    key = myArray[49];
    searchResults = linearSearch(myArray, 50, key);

    if(searchResults >= 0)
        printf("The key value %d was found in myArray at position %d\n", key, searchResults);
    else
        printf("The key value %d was not found in myArray\n", key);

    printf("\n");
    printf("Testing linear search for %d which is the first element in the array\n", myArray[0]);
    key = myArray[0];
    searchResults = linearSearch(myArray, 50, key);

    if(searchResults >= 0)
        printf("The key value %d was found in myArray at position %d\n", key, searchResults);
    else
        printf("The key value %d was not found in myArray\n", key);

    //testing shiftElements
    printf("\n");
    printf("Shifting the elements in the array right 6 elements\n");
    shiftElements(myArray, 50, 6);
    printNperline(myArray, 50, 10);

    printf("\n");
    printf("Shifting the elements in the array left 4 elements\n");
    shiftElements(myArray, 50, -4);
    printNperline(myArray, 50, 10);

}
Ejemplo n.º 28
0
int16_t linex_node_handler::locate() {
    pos = linearSearch();
    return pos;
}
Ejemplo n.º 29
0
Archivo: tnc.c Proyecto: 317070/scipy
/*
 * This routine is a bounds-constrained truncated-newton method.
 * the truncated-newton method is preconditioned by a limited-memory
 * quasi-newton method (this preconditioning strategy is developed
 * in this routine) with a further diagonal scaling
 * (see routine diagonalscaling).
 */
static tnc_rc tnc_minimize(int n, double x[],
  double *f, double gfull[], tnc_function *function, void *state,
  double xscale[], double xoffset[], double *fscale,
  double low[], double up[], tnc_message messages,
  int maxCGit, int maxnfeval, int *nfeval, int *niter, double eta, double
  stepmx, double accuracy, double fmin, double ftol, double xtol, double
  pgtol, double rescale, tnc_callback *callback)
{
  double fLastReset, difnew, epsmch, epsred, oldgtp,
    difold, oldf, xnorm, newscale,
    gnorm, ustpmax, fLastConstraint, spe, yrsr, yksk,
    *temp = NULL, *sk = NULL, *yk = NULL, *diagb = NULL, *sr = NULL,
    *yr = NULL, *oldg = NULL, *pk = NULL, *g = NULL;
  double alpha = 0.0; /* Default unused value */
  int i, icycle, oldnfeval, *pivot = NULL, frc;
  logical lreset, newcon, upd1, remcon;
  tnc_rc rc = TNC_ENOMEM; /* Default error */

  *niter = 0;

  /* Allocate temporary vectors */
  oldg = malloc(sizeof(*oldg)*n);
   if (oldg == NULL) goto cleanup;
  g = malloc(sizeof(*g)*n);
   if (g == NULL) goto cleanup;
  temp = malloc(sizeof(*temp)*n);
   if (temp == NULL) goto cleanup;
  diagb = malloc(sizeof(*diagb)*n);
   if (diagb == NULL) goto cleanup;
  pk = malloc(sizeof(*pk)*n);
   if (pk == NULL) goto cleanup;

  sk = malloc(sizeof(*sk)*n);
   if (sk == NULL) goto cleanup;
  yk = malloc(sizeof(*yk)*n);
   if (yk == NULL) goto cleanup;
  sr = malloc(sizeof(*sr)*n);
   if (sr == NULL) goto cleanup;
  yr = malloc(sizeof(*yr)*n);
   if (yr == NULL) goto cleanup;

  pivot = malloc(sizeof(*pivot)*n);
   if (pivot == NULL) goto cleanup;

  /* Initialize variables */
  epsmch = mchpr1();

  difnew = 0.0;
  epsred = 0.05;
  upd1 = TNC_TRUE;
  icycle = n - 1;
  newcon = TNC_TRUE;

  /* Uneeded initialisations */
  lreset = TNC_FALSE;
  yrsr = 0.0;
  yksk = 0.0;

  /* Initial scaling */
  scalex(n, x, xscale, xoffset);
  (*f) *= *fscale;

  /* initial pivot calculation */
  setConstraints(n, x, pivot, xscale, xoffset, low, up);

  dcopy1(n, gfull, g);
  scaleg(n, g, xscale, *fscale);

  /* Test the lagrange multipliers to see if they are non-negative. */
  for (i = 0; i < n; i++)
    if (-pivot[i] * g[i] < 0.0)
      pivot[i] = 0;

  project(n, g, pivot);

  /* Set initial values to other parameters */
  gnorm = dnrm21(n, g);

  fLastConstraint = *f; /* Value at last constraint */
  fLastReset = *f; /* Value at last reset */

  if (messages & TNC_MSG_ITER) fprintf(stderr,
    "  NIT   NF   F                       GTG\n");
  if (messages & TNC_MSG_ITER) printCurrentIteration(n, *f / *fscale, gfull,
    *niter, *nfeval, pivot);

  /* Set the diagonal of the approximate hessian to unity. */
  for (i = 0; i < n; i++) diagb[i] = 1.0;

  /* Start of main iterative loop */
  while(TNC_TRUE)
  {
    /* Local minimum test */
    if (dnrm21(n, g) <= pgtol * (*fscale))
    {
      /* |PG| == 0.0 => local minimum */
      dcopy1(n, gfull, g);
      project(n, g, pivot);
      if (messages & TNC_MSG_INFO) fprintf(stderr,
        "tnc: |pg| = %g -> local minimum\n", dnrm21(n, g) / (*fscale));
      rc = TNC_LOCALMINIMUM;
      break;
    }

    /* Terminate if more than maxnfeval evaluations have been made */
    if (*nfeval >= maxnfeval)
    {
      rc = TNC_MAXFUN;
      break;
    }

    /* Rescale function if necessary */
    newscale = dnrm21(n, g);
    if ((newscale > epsmch) && (fabs(log10(newscale)) > rescale))
    {
      newscale = 1.0/newscale;

      *f *= newscale;
      *fscale *= newscale;
      gnorm *= newscale;
      fLastConstraint *= newscale;
      fLastReset *= newscale;
      difnew *= newscale;

      for (i = 0; i < n; i++) g[i] *= newscale;
      for (i = 0; i < n; i++) diagb[i] = 1.0;

      upd1 = TNC_TRUE;
      icycle = n - 1;
      newcon = TNC_TRUE;

      if (messages & TNC_MSG_INFO) fprintf(stderr,
        "tnc: fscale = %g\n", *fscale);
    }

    dcopy1(n, x, temp);
    project(n, temp, pivot);
    xnorm = dnrm21(n, temp);
    oldnfeval = *nfeval;

    /* Compute the new search direction */
    frc = tnc_direction(pk, diagb, x, g, n, maxCGit, maxnfeval, nfeval,
      upd1, yksk, yrsr, sk, yk, sr, yr,
      lreset, function, state, xscale, xoffset, *fscale,
      pivot, accuracy, gnorm, xnorm, low, up);

    if (frc == -1)
    {
      rc = TNC_ENOMEM;
      break;
    }

    if (frc)
    {
      rc = TNC_USERABORT;
      break;
    }

    if (!newcon)
    {
      if (!lreset)
      {
        /* Compute the accumulated step and its corresponding gradient
          difference. */
        dxpy1(n, sk, sr);
        dxpy1(n, yk, yr);
        icycle++;
      }
      else
      {
        /* Initialize the sum of all the changes */
        dcopy1(n, sk, sr);
        dcopy1(n, yk, yr);
        fLastReset = *f;
        icycle = 1;
      }
    }

    dcopy1(n, g, oldg);
    oldf = *f;
    oldgtp = ddot1(n, pk, g);

    /* Maximum unconstrained step length */
    ustpmax = stepmx / (dnrm21(n, pk) + epsmch);

    /* Maximum constrained step length */
    spe = stepMax(ustpmax, n, x, pk, pivot, low, up, xscale, xoffset);

    if (spe > 0.0)
    {
      ls_rc lsrc;
      /* Set the initial step length */
      alpha = initialStep(*f, fmin / (*fscale), oldgtp, spe);

      /* Perform the linear search */
      lsrc = linearSearch(n, function, state, low, up,
        xscale, xoffset, *fscale, pivot,
        eta, ftol, spe, pk, x, f, &alpha, gfull, maxnfeval, nfeval);

      if (lsrc == LS_ENOMEM)
      {
        rc = TNC_ENOMEM;
        break;
      }

      if (lsrc == LS_USERABORT)
      {
        rc = TNC_USERABORT;
        break;
      }

      if (lsrc == LS_FAIL)
      {
        rc = TNC_LSFAIL;
        break;
      }

      /* If we went up to the maximum unconstrained step, increase it */
      if (alpha >= 0.9 * ustpmax)
      {
        stepmx *= 1e2;
        if (messages & TNC_MSG_INFO) fprintf(stderr,
          "tnc: stepmx = %g\n", stepmx);
      }

      /* If we went up to the maximum constrained step,
         a new constraint was encountered */
      if (alpha - spe >= -epsmch * 10.0)
      {
        newcon = TNC_TRUE;
      }
      else
      {
        /* Break if the linear search has failed to find a lower point */
        if (lsrc != LS_OK)
        {
          if (lsrc == LS_MAXFUN) rc = TNC_MAXFUN;
          else rc = TNC_LSFAIL;
          break;
        }
        newcon = TNC_FALSE;
      }
    }
    else
    {
      /* Maximum constrained step == 0.0 => new constraint */
      newcon = TNC_TRUE;
    }

    if (newcon)
    {
      if(!addConstraint(n, x, pk, pivot, low, up, xscale, xoffset))
      {
        if(*nfeval == oldnfeval)
        {
          rc = TNC_NOPROGRESS;
          break;
        }
      }

      fLastConstraint = *f;
    }

    (*niter)++;

    /* Invoke the callback function */
    if (callback)
    {
      unscalex(n, x, xscale, xoffset);
      callback(x, state);
      scalex(n, x, xscale, xoffset);
    }

    /* Set up parameters used in convergence and resetting tests */
    difold = difnew;
    difnew = oldf - *f;

    /* If this is the first iteration of a new cycle, compute the
       percentage reduction factor for the resetting test */
    if (icycle == 1)
    {
      if (difnew > difold * 2.0) epsred += epsred;
      if (difnew < difold * 0.5) epsred *= 0.5;
    }

    dcopy1(n, gfull, g);
    scaleg(n, g, xscale, *fscale);

    dcopy1(n, g, temp);
    project(n, temp, pivot);
    gnorm = dnrm21(n, temp);

    /* Reset pivot */
    remcon = removeConstraint(oldgtp, gnorm, pgtol * (*fscale), *f,
      fLastConstraint, g, pivot, n);

    /* If a constraint is removed */
    if (remcon)
    {
      /* Recalculate gnorm and reset fLastConstraint */
      dcopy1(n, g, temp);
      project(n, temp, pivot);
      gnorm = dnrm21(n, temp);
      fLastConstraint = *f;
    }

    if (!remcon && !newcon)
    {
      /* No constraint removed & no new constraint : tests for convergence */
      if (fabs(difnew) <= ftol * (*fscale))
      {
        if (messages & TNC_MSG_INFO) fprintf(stderr,
          "tnc: |fn-fn-1] = %g -> convergence\n", fabs(difnew) / (*fscale));
        rc = TNC_FCONVERGED;
        break;
      }
      if (alpha * dnrm21(n, pk) <= xtol)
      {
        if (messages & TNC_MSG_INFO) fprintf(stderr,
          "tnc: |xn-xn-1] = %g -> convergence\n", alpha * dnrm21(n, pk));
        rc = TNC_XCONVERGED;
        break;
      }
    }

    project(n, g, pivot);

    if (messages & TNC_MSG_ITER) printCurrentIteration(n, *f / *fscale, gfull,
      *niter, *nfeval, pivot);

    /* Compute the change in the iterates and the corresponding change in the
      gradients */
    if (!newcon)
    {
      for (i = 0; i < n; i++)
      {
        yk[i] = g[i] - oldg[i];
        sk[i] = alpha * pk[i];
      }

      /* Set up parameters used in updating the preconditioning strategy */
      yksk = ddot1(n, yk, sk);

      if (icycle == (n - 1) || difnew < epsred * (fLastReset - *f))
        lreset = TNC_TRUE;
      else
      {
        yrsr = ddot1(n, yr, sr);
        if (yrsr <= 0.0) lreset = TNC_TRUE;
        else lreset = TNC_FALSE;
      }
      upd1 = TNC_FALSE;
    }
  }

  if (messages & TNC_MSG_ITER) printCurrentIteration(n, *f / *fscale, gfull,
    *niter, *nfeval, pivot);

  /* Unscaling */
  unscalex(n, x, xscale, xoffset);
  coercex(n, x, low, up);
  (*f) /= *fscale;

cleanup:
  if (oldg) free(oldg);
  if (g) free(g);
  if (temp) free(temp);
  if (diagb) free(diagb);
  if (pk) free(pk);

  if (sk) free(sk);
  if (yk) free(yk);
  if (sr) free(sr);
  if (yr) free(yr);

  if (pivot) free(pivot);

  return rc;
}