int main(){


int array[ARRAY_SIZE]={};
int i=0;
float seconds;
clock_t end ,start;

InitializeArray(array);
printf("Unsorted array\n\n");
DisplayArray(array);

HEAP heap = heapify(array,ARRAY_SIZE);

//for(i=0;i<ARRAY_SIZE;i++){printf("%d at %d \t",heap->hArray[i],i+1); }

start = clock();


HeapSort(heap,array);


end = clock();
seconds = (float)(end - start) / CLOCKS_PER_SEC;

//printf("\n\n");
printf("\nSorted array\n\n");
DisplayArray(array);
printf("\n\nTime taken for sort= %f sec\n",seconds);

return 0;
	
}
Ejemplo n.º 2
0
IntArray *Executor::CreateIntArray(const numeric::Width *width,
				   int array_length,
				   fe::ArrayInitializer *array_initializer) {
  IntArray *array = IntArray::Create(width, array_length);
  InitializeArray(array, array_initializer);
  return array;
}
Ejemplo n.º 3
0
//------------------------------------------------------------------------------
bool CvDatabaseUtility::PopulateArrayByExistence(int*& pArray, const char* szTypeTableName, const char* szDataTableName, const char* szTypeColumn, const char* szFilterColumn, const char* szFilterValue)
{
	InitializeArray(pArray, MaxRows(szTypeTableName), -1);

	std::string strKey = "_PABE_";
	strKey.append(szTypeTableName);
	strKey.append(szDataTableName);
	strKey.append(szFilterColumn);

	Database::Results* pResults = GetResults(strKey);
	if(pResults == NULL)
	{
		char szSQL[512];
		sprintf_s(szSQL, "select %s.ID from %s inner join %s on %s = %s.Type where %s = ?", szTypeTableName, szDataTableName, szTypeTableName, szTypeColumn, szTypeTableName, szFilterColumn);
		pResults = PrepareResults(strKey, szSQL);
		if(pResults == NULL)
			return false;
	}

	if(!pResults->Bind(1, szFilterValue, false))
	{
		CvAssertMsg(false, GetErrorMessage());
		return false;
	}

	int idx = 0;
	while(pResults->Step())
	{
		pArray[idx++] = pResults->GetInt(0);
	}

	pResults->Reset();

	return true;
}
Ejemplo n.º 4
0
int InitializeType(TYP *tp)
{   
	int nbytes;

    switch(tp->type) {
	case bt_byte:
			nbytes = initbyte();
			break;
    case bt_char:
    case bt_enum:
            nbytes = initchar();
            break;
    case bt_short:
            nbytes = initshort();
            break;
    case bt_pointer:
            if( tp->val_flag)
                nbytes = InitializeArray(tp);
            else
                nbytes = InitializePointer();
            break;
    case bt_long:
            nbytes = initlong();
            break;
    case bt_struct:
            nbytes = InitializeStructure(tp);
            break;
    default:
        error(ERR_NOINIT);
        nbytes = 0;
    }
    return nbytes;
}
Ejemplo n.º 5
0
Object *Executor::CreateMemoryObject(const numeric::Width *width,
				     int array_length,
				     fe::ArrayInitializer *array_initializer) {
  Object *obj = ArrayWrapper::NewIntArrayWrapper(thr_->GetVM(),
						 array_length, width);
  IntArray *memory = ArrayWrapper::GetIntArray(obj);
  InitializeArray(memory, array_initializer);
  return obj;
}
int main() {

	int Array[ARRAY_SIZE] ={};


	
	int j=0,k=1;
	int noElements;
	float seconds[30]={};
	clock_t end ,start;
	printf("\nSorting a %d Elements of Integers.following are the time in Each Trial\n",ARRAY_SIZE);
	printf("\nThreshold is %d in Each Trial\n",THRESHOLD);


while(j<30){

	InitializeArray(Array);
	//printf("\t\t::::::::::::::::Unsorted array:::::::::::::::::::\n\n");
	
	//DisplayArray(Array);	

	int last = sizeof(Array)/sizeof(Array[0])-1; 

	start = clock();

	//printf("Threshold = %d \n",threshold);
	quickInSort(Array, 0, last,THRESHOLD);

	end = clock();
	seconds[j] = (float)(end - start) / CLOCKS_PER_SEC;

	
	//printf("\t\t::::::::::::::::Sorted array:::::::::::::::::::\n\n");

	//DisplayArray(Array);


	printf("Time taken %d : run = %f\n",j,seconds[j]);
	j++;
	
	}

	float avgsum=0;
	int i;
	for(i=0;i<30;i++){
		avgsum += seconds[i];
	}

	float avg=avgsum/30;
	printf("avg Time taken for 30 runs = %f\n",avg);
	

	return 0;
}
int main() {

	int Array[ARRAY_SIZE] ;
	int j=0;
	int myInt;
	int noElements;
	float seconds[30]={};
	clock_t end ,start;
	
	printf("\nSorting %d Elemetns using merge Sort\n\n",ARRAY_SIZE);
	
	while(j<30){


		InitializeArray(Array);
		
		//printf("\t\t::::::::::::::::Unsorted array:::::::::::::::::::\n\n");
		//DisplayArray(Array);

		noElements = sizeof(Array)/sizeof(Array[0]); 
		start = clock();

		mergeSort(Array,noElements);

		end = clock();
		seconds[j] = (float)(end - start) / CLOCKS_PER_SEC;

		//printf("\t\t::::::::::::::::Sorted array:::::::::::::::::::\n\n");
		//DisplayArray(Array);


		
		printf("Time taken %d : run = %f sec\n",j,seconds[j]);
		j++;
		
	}

	float avgsum=0;
	int i;
	for(i=0;i<30;i++){
		avgsum += seconds[i];
	}

	float avg=avgsum/30;
	printf("avg Time taken for 30 runs = %f\n",avg);
		

	return 0;
}
Ejemplo n.º 8
0
/*main*/
int main(void) {
        enum state now;
        now = Any_state;
       
        int x=0;
        int ch=0;
       
        InitializeArray();/*init array*/
        ch=getchar();
        do{
          now=(katastaseis[now])(ch);
        }while ((ch=getchar())!=EOF);
       
        printf("/n");
        return 0;
 
}
int main() {

	printf("\nSorting %d Elemetns using merge Sort\n\n",ARRAY_SIZE);
	int Array[ARRAY_SIZE] ;

	InitializeArray(Array);
	

	printf("\t\t::::::::::::::::Unsorted array:::::::::::::::::::\n\n");
	
	DisplayArray(Array);

	printf("\n\n" );

	int noElements;

	noElements = sizeof(Array)/sizeof(Array[0]); 
	clock_t start = clock();

	mergeSort(Array,noElements);


	clock_t end = clock();
	float seconds = (float)(end - start) / CLOCKS_PER_SEC;
	
	printf("\t\t::::::::::::::::Sorted array:::::::::::::::::::\n\n");
	
	DisplayArray(Array);


	printf("\n\n\t\t::::::::::::::::Time taken - %f sec:::::::::::::::::::\n\n",seconds);
	

	
		

	return 0;
}
Ejemplo n.º 10
0
int main()
{
  //Some variables

  //Seed the random number generator (do only once!)
  srand(time(NULL));

  int * p = 0; //Pointer to DMA'd int
  p = (int *) malloc(sizeof(int));
  if(!p)
  {
    printf ("Memory Allocation Error.  Your computer sucks.");
    return -1;
  }
  //If I got here, I got memory
  *p = 42;
  printf("The answer to life, the universe and everything is %d\n",*p);

  //Give my memory back
  if (p) free(p);
  p = 0;

  //You can reuse pointers if you're cool (and careful!)
  //A pointer to int can point to an int, or an array of ints
  p = MakeArray(ARRAYSIZE);
  printf("Uninitialized array:\n");
  PrintArray(p,ARRAYSIZE);
  InitializeArray(p,ARRAYSIZE);
  printf("Initialized array:\n");
  PrintArray(p,ARRAYSIZE);

  //Put away your toys!
  if (p) free(p); //Free don't care how big it is.
  p = 0;

  return 0;
}
Ejemplo n.º 11
0
//------------------------------------------------------------------------------
bool CvDatabaseUtility::PopulateArrayByValue(int*& pArray, const char* szTypeTableName, const char* szDataTableName, const char* szTypeColumn, const char* szFilterColumn, const char* szFilterValue, const char* szValueColumn, int iDefaultValue /* = 0 */, int iMinArraySize /* = 0 */)
{
	int iSize = MaxRows(szTypeTableName);
	InitializeArray(pArray, (iSize<iMinArraySize)?iMinArraySize:iSize, iDefaultValue);

	std::string strKey = "_PABV_";
	strKey.append(szTypeTableName);
	strKey.append(szDataTableName);
	strKey.append(szFilterColumn);
	strKey.append(szValueColumn);

	Database::Results* pResults = GetResults(strKey);
	if(pResults == NULL)
	{
		char szSQL[512];
		sprintf_s(szSQL, "select %s.ID, %s from %s inner join %s on %s = %s.Type where %s = ?", szTypeTableName, szValueColumn, szDataTableName, szTypeTableName, szTypeColumn, szTypeTableName, szFilterColumn);
		pResults = PrepareResults(strKey, szSQL);
		if(pResults == NULL)
			return false;
	}

	if(!pResults->Bind(1, szFilterValue, false))
	{
		CvAssertMsg(false, GetErrorMessage());
		return false;
	}
	while(pResults->Step())
	{
		const int idx = pResults->GetInt(0);
		const int value = pResults->GetInt(1);
		pArray[idx] = value;
	}

	pResults->Reset();

	return true;
}
Ejemplo n.º 12
0
Archivo: nqueens.c Proyecto: alecwebb/c
int main()
{
//declare function variables
int i,k,j,l;
int n=0;
int pass=0;

double numArray[];
int minout[ARRAYLEN];
int maxout[ARRAYLEN];
double meanout[ARRAYLEN];
double ntimesn[ARRAYLEN];
double nfacout[ARRAYLEN];

double mean=0;
double sizesquare=0;
double nfactorial, nsq;

//seed the generator
srandom(RNG_SEED);

//introduction message
printf("Project 1, Created by: Alec Webb, Description: Solves the nqueens problem using permutations\n");
printf("---------------------------------------------------------------\n");

for(j=4; j<=ARRAYLEN; j++){ 			//start n loop
	int solutionFound=0;	//used to determine first run or not
	int nCounter=0;			//used to count number of runs for 10 solutions
	int pncount=0;				//used to calulate current number of runs for max min functions
	int current=0;				//for max min functions
	int minimum=0;			//for max min comparisons
	int maximum=0;			//for max min comparisons

	n=j;								//set size of array
	nsq=j; 							//set size for calculations

	for(k=0; k<LOOPTIME; k++){ 								//find 10 solutions
		pass=0; 															//to continue after a first match is found
		pncount = nCounter; 										//for maxmin calc
			while(pass==0)
			{
				InitializeArray(numArray, n);						//call initialize method
				randperm(numArray, n);							//call randperm function
				pass = checkboard(numArray, n);			//check the permutation
				nCounter++;												//total# of runs
			}
		current = nCounter-pncount;  							//for max min,current run time

		if(pncount==0)													//to account for a run that has not occured
		{																		//avoids min being set to 0
			minimum = maximum = current;
		}
		else
		{
			minimum = min(minimum, current);				//compare
			maximum = max(maximum, current);				//compare
		}

		solutionFound++; 											 //indicate first solution has been found
		if(solutionFound <=1)										//handles the first and only first solution
		{
		displayboard(numArray, n);								//print the solution found

		printf("---------------------------------------------------------------\n");
		printf(" ");
		for(i=0; i<n; i++){												//print the numerical solution found
			printf("%-3.0lf", numArray[i]);
		}
		printf(": Solution for board size %d\n", n);
		printf("---------------------------------------------------------------\n");
		}
}
//calculate and store relevent values
mean = nCounter/10;											//determine mean
sizesquare = nsquared(nsq,n);								//determine n^n
nfactorial = factorial(n);											//determine n!

//stores the values for printing
minout[j-4] = minimum;
maxout[j-4] = maximum;
meanout[j-4] = mean;
ntimesn[j-4] = sizesquare;
nfacout[j-4] = nfactorial;

}//end n loop

//the following prints out the results of the 10 runs for each n
printf("size      min        max         mean     size**size      size!\n");
printf("---------------------------------------------------------------\n");
for(l=0; l<NUMBEROFBOARDS; l++)
{
	printf("%4d %8d %10d %12.1e %12.1e %12.1e\n", (l+4), minout[l], maxout[l], meanout[l], ntimesn[l], nfacout[l]);
}
return 0;
}//end main
Ejemplo n.º 13
0
int main() {

    int xPos = (XGRID - 1)/2;
    int yPos = YGRID - 2;

    int xBull = 0;
    int yBull = 0;

    int WallArr[XGRID];
    InitializeArray(WallArr, 1, XGRID);

    int BulletCounter = XGRID * 2;

    char Player = 'X';
    char Wall = '#';
    char Bullet = '^';
    char PInput;

    printf("Controls:\n\nW: Shoot\nA: Left\nD: Right\nEnter: Execute Move(s)\n");
    printf("\nPress Enter to start.\n\n");
    getchar();

    system("cls");

    while (1) {
        DrawGrid(XGRID, YGRID, xPos, yPos, xBull, yBull, Player, Wall, Bullet, WallArr);
        printf("\n");

        if (SumArray(WallArr, XGRID) < 3) {
            printf("You Win!\n\n");
            break;
        } else if (BulletCounter < 1) {
            printf("You Lose!\n\n");
            break;
        }

        scanf("%c",&PInput);
        PInput = toupper(PInput);

        switch (PInput) {
        case 'W':
            xBull = xPos;
            ShootingGrid(XGRID, YGRID, xPos, yPos, xBull, yBull, Player, Wall, Bullet, WallArr);
            WallArr[xPos] = 0;
            BulletCounter--;
            break;
        case 'A':
            if (xPos > 1)
                xPos--;

            break;
        case 'D':
            if (xPos < XGRID - 2)
                xPos++;

            break;
        }

        system("cls");
    }

    return 0;
}
Ejemplo n.º 14
0
//===----------------------------------------------------------------------===//
// Allocate an array that is 2x of the current size, updating the mask (for
// rehash), resize threshold, and element count, and then rearrange all existing
// elements in the old array to their new locations
//
// This function will invalidate all pointers on the old hash table
// So do not call this until all states have been cleared
//===----------------------------------------------------------------------===//
void OAHashTable::Resize(HashEntry **entry_p_p) {
  // Make it an assertion to prevent potential bugs
  PELOTON_ASSERT(NeedsResize());

  LOG_DEBUG("Resizing hash-table from %llu buckets to %llu",
            (unsigned long long)num_buckets_,
            (unsigned long long)num_buckets_ << 1);

  // Double the size of the array
  num_buckets_ <<= 1;

  // Recompute bucket mask (same as in init())
  bucket_mask_ = num_buckets_ - 1;

  // The threshold for resizing also doubles
  resize_threshold_ <<= 1;

  // Allocate the new array
  char *new_buckets = static_cast<char *>(malloc(entry_size_ * num_buckets_));

  // Set it all to status code FREE
  InitializeArray(reinterpret_cast<HashEntry *>(new_buckets));

  // This is the pointer we are tracking
  // If it is not free, then during rehashing we will update its
  // value through the pointer to be the new location in the resized array
  HashEntry *entry_p = *entry_p_p;

  // We use this count to check end condition. This serves as a faster path than
  // iterating over all buckets in the array.
  uint64_t processed_count = 0;

  // This points to the current entry being processed
  char *current_entry_char_p = reinterpret_cast<char *>(buckets_);

  while (processed_count < num_valid_buckets_) {
    // This is meaningless - just to make compiler happy
    HashEntry *current_entry =
        reinterpret_cast<HashEntry *>(current_entry_char_p);

    // Ignore entries that are not occupied by a valid hash key and value
    if (!current_entry->IsFree()) {
      // We have processed one valid entry
      processed_count++;

      // The trick here is that we do not need to recompute the hash since it
      // stays the same as long as the key does not change
      // So just re-mask the hash value and get the index in the new array
      uint64_t new_index = current_entry->hash & bucket_mask_;

      // This is the pointer to the new entry
      char *new_entry_char_p = new_buckets + new_index * entry_size_;

      // Probe the array until we find a free entry
      while (!reinterpret_cast<HashEntry *>(new_entry_char_p)->IsFree()) {
        new_index++;
        new_entry_char_p += entry_size_;

        // If we have reached the end of the array just wrap back
        if (new_index == num_buckets_) {
          new_index = 0;
          new_entry_char_p = new_buckets;
        }
      }

      // If the current entry is not free and is what we are looking for,
      // then return in the argument the new location of that entry
      // the gist behind this is to track a certain key by its entry address
      // since we have guaranteed a given key has only one entry address
      // This should happen only once
      if (entry_p == current_entry) {
        *entry_p_p = reinterpret_cast<HashEntry *>(new_entry_char_p);
      }

      // Copy everything, including is_free flag, hash value and key-value
      // to the new free entry we just found
      PELOTON_MEMCPY(new_entry_char_p, current_entry_char_p, entry_size_);
    }

    // No matter we ignore an entry or not this has to be done
    current_entry_char_p += entry_size_;
  }

  // Free the old array after probing of all elements, and then update
  free(buckets_);
  buckets_ = reinterpret_cast<HashEntry *>(new_buckets);
}
int main() {

	
	
	int threshold=SIZE+5;

	int Array1[SIZE] ={};
	int Array2[SIZE] ={};
	

	
	int j=0;
	int noElements;
	float secondsI[TRIALS]={};
	float secondsQ[TRIALS]={};
	clock_t end ,start;

while(j<TRIALS){

	InitializeArray(Array1,SIZE);
	CopyArray(Array1,Array2,SIZE);
	//printf("Unsorted array\n\n");
	//DisplayArray(Array1,SIZE);	
	//DisplayArray(Array2,SIZE);
	int last = sizeof(Array1)/sizeof(Array1[0])-1; 

	if(j==0)printf("Threshold = %d \n",threshold);
	start = clock();
	//quickSort(Array, 0, last);
	quickInSort(Array1, 0, last,threshold);

	end = clock();
	secondsI[j] = (float)(end - start) / CLOCKS_PER_SEC;



	last = sizeof(Array2)/sizeof(Array2[0])-1; 
	threshold=threshold-10;
	start = clock();

	quickInSort(Array2, 0, last,threshold);

	end = clock();
	secondsQ[j] = (float)(end - start) / CLOCKS_PER_SEC;

	
	//printf("Sorted array\n\n");
	//DisplayArray(Array1,SIZE);
	//DisplayArray(Array2,SIZE);


	//printf("\n\n");
	j++;
	
	}

	float avgsumI=0;
	float avgsumQ=0;
	int i;
	for(i=0;i<TRIALS;i++){
		avgsumI += secondsI[i];
	}
	for(i=0;i<TRIALS;i++){
		avgsumQ += secondsQ[i];
	}

	float avgI=avgsumI/TRIALS;
	float avgQ=avgsumQ/TRIALS;
	printf("using QuickInSort algo with bigger threshold than size Avg Time taken for %d runs = %f sec\n",TRIALS,avgI);
	printf("using QuickInSort algo with lower threshold than size(without Insertion sort) Avg Time taken for %d runs = %f sec\n",TRIALS,avgQ);
	


	
	

	return 0;
}