Ejemplo n.º 1
0
/* A function to print all prime factors of a given number n */
void primeFactors(Array *a, double number)
{	
	long n = round(number);

	int i = 2;
	if (n%i == 0)
		insertArray(a, i);
		
    while (n%i == 0)
        n = n/i;
 
    /* n must be odd at this point.  
     * So we can skip one element (Note i = i +2) */
    for ( i = 3; i <= sqrt(n); i = i+2)
    {
		if (n%i == 0)
			insertArray(a, i);
		
        /* While i divides n, print i and divide n */
        while (n%i == 0)
            n = n/i;
    }
 
    /* In case where n is a prime number and greater than 2 */
    if (n > 2)
		insertArray(a, n);
}
Ejemplo n.º 2
0
/**
	busca un rectángulo dentro del R-Tree.
*/
Dynamic_array* buscar(Nodo nodo, Rectangulo rect) {
	int i, j;
	
	Dynamic_array *rects; // arreglo dinámico de rectangulos
	initArray(rects, 1);
    
	// recorremos los MBR's del nodo
	for(i=0;i<=nodo.ultimo;i++) {
		// si el rectangulo se intersecta con un MBR
		if (interseccion(nodo.mbr[i].rect, rect)){
			// si es una hoja. retornar rectangulo;
			if (nodo.mbr[i].nodo_hijo == -1) {
				insertArray(rects, nodo.mbr[i].rect);
			// seguir en profundidad
			} else {
				// buscar en los hijos
				Nodo nodo_hijo = leer_nodo_en_disco(nodo.mbr[i].nodo_hijo);
				Dynamic_array *rects_hijos = buscar(nodo_hijo, rect);
				
				// se insertan en el grupo general
				for(j=0;j<rects_hijos->used;j++) {
					insertArray(rects, rects_hijos->array[j]);
				}
				
				// se libera la memoria.
				freeArray(rects_hijos);
			}	
		}
	}
	
	return rects;
}
Ejemplo n.º 3
0
	void process( array * base ) {
		if ( base->k >= MAXK ) {
			return;
		}

		// first, we use this array as the main array

		if ( base->t > 3 ) {
			array * subarray = getBestArray( base->k, base->v - 2, base->t - 2 );

			if ( subarray != NULL ) {
				array * arr = new array();
				arr->N = base->N + subarray->N;
				arr->k = base->k + 1;
				arr->v = base->v;
				arr->t = base->t;

				arr->type = 'C';
				arr->source = id;

				arr->ingredients.push_back( base );
				arr->ingredients.push_back( subarray );

				insertArray( arr );
			}
		}

		// we also need to try this array as the smaller array

		if ( ( base->t + 2) > MAXT || (base->v + 2 > MAXV) ) {
			return;
		}

		array * prev = getPreviousArray( base );

		fullSortTableType arrays;
		query( arrays, base->t + 2, base->t + 2, base->v + 2, base->v + 2, prev != NULL ? prev->k + 1 : 0, base->k );

		fullSortTableType::const_iterator superIt;
		for ( superIt = arrays.begin(); superIt != arrays.end(); superIt++ ) {
			array * superarray = *superIt;

			array * arr = new array();
			arr->N = base->N + superarray->N;
			arr->k = superarray->k + 1;
			arr->v = superarray->v;
			arr->t = superarray->t;

			arr->type = 'C';
			arr->source = id;
			
			arr->ingredients.push_back( superarray );
			arr->ingredients.push_back( base );

			insertArray( arr, &arrays );
		}
	}
Ejemplo n.º 4
0
void BPlusIndex::splitAddInner(IndexPage* page, Index* index, IndexPage* rightPage) {
	Logger* log = getLogger(NULL);

	//temporal arrays
	Index** tmpelements = (Index**)malloc(sizeof(Index*) * (BUCKET_MAX_ELEMENTS + 1));
	IndexPage** tmppointers = (IndexPage**)malloc(sizeof(IndexPage*) * (BUCKET_MAX_ELEMENTS + 2));

	initializeArray((void**)tmpelements, BUCKET_MAX_ELEMENTS);
	initializeArray((void**)tmppointers, BUCKET_MAX_ELEMENTS + 1);

	copyArray((void**)page->elements, (void**)tmpelements, 0, BUCKET_MAX_ELEMENTS - 1, 0);
	copyArray((void**)page->pointers, (void**)tmppointers, 0, BUCKET_MAX_ELEMENTS, 0);

	int posToInsert = findInsertPositionArray(tmpelements, index, page->size, BUCKET_MAX_ELEMENTS);

	insertArray((void**)tmpelements, index, posToInsert, BUCKET_MAX_ELEMENTS + 1);
	insertArray((void**)tmppointers, rightPage, posToInsert + 1, BUCKET_MAX_ELEMENTS + 2);

	// clean the previous "left"
	initializeArray((void**)page->elements, BUCKET_MAX_ELEMENTS);
	initializeArray((void**)page->pointers, BUCKET_MAX_ELEMENTS + 1);

	IndexPage* newRightPage = new IndexPage();
	int midPoint = (BUCKET_MAX_ELEMENTS / 2);
	copyArray((void**)tmpelements, (void**)page->elements, 0, midPoint, 0);
	copyArray((void**)tmppointers, (void**)page->pointers, 0, midPoint + 1, 0);

	page->size = (BUCKET_MAX_ELEMENTS / 2) + 1;
	copyArray((void**)tmpelements, (void**)newRightPage->elements, midPoint + 1, BUCKET_MAX_ELEMENTS, 0);
	copyArray((void**)tmppointers, (void**)newRightPage->pointers, midPoint + 2, BUCKET_MAX_ELEMENTS + 1, 1);

	newRightPage->size = (BUCKET_MAX_ELEMENTS / 2) + 1;
	refreshParentRelationship(newRightPage);

	// Promotion
	IndexPage* parentElement = page->parentElement;
	Index* element = newRightPage->elements[0];

	if (parentElement == NULL) {
		createRoot(element, page, newRightPage);
		parentElement = _head;
	} else {
		addElement(parentElement, element, newRightPage);
	}
	shiftLeftArray((void**)newRightPage->elements, 0, 1, BUCKET_MAX_ELEMENTS - 1);
	shiftLeftArray((void**)newRightPage->pointers, 0, 1, BUCKET_MAX_ELEMENTS);
	newRightPage->size--;

	refreshParentRelationship(parentElement);
	free(tmpelements);
	free(tmppointers);
}
Ejemplo n.º 5
0
/* Fibonacci Number */
void Fibonacci (Array *a, double number)
{
	long n = round(number);
	
	printf("The fibonacci numbers are 1, 1, 2...\n");
	
	int i = 1;
	if (n >= 1)
		insertArray(a, i);
	if (n >= 2)
		insertArray(a, i++);
	
	for(; i < n; i++)
		insertArray(a, a->array[i-1] + a->array[i-2]);
}
Ejemplo n.º 6
0
// Algorithm start
int main(int argc, char **argv)
{
    long int startPoint = 600851475143; // Starting point from project euler, you can change it
    Array primeFactors; // Our beautiful new Array for prime factors
    int maxPrimeFactor = 0; // Max, if founded.
    initArray(&primeFactors, 1); // Initialize empty array with size of one

    // Start the iteration
    while( startPoint > 1 )
    {
        for( int i = 2; i <= startPoint; i++)
        {
            if( startPoint % i == 0) // If startPoint is divisible by i
            {
                startPoint = (startPoint / i); // Actually divide the starting Point
                insertArray(&primeFactors, i); // Inser the value inside our Array
                if( primeFactors.array[i] > maxPrimeFactor) // check if is the Max around here
                {
                    maxPrimeFactor = primeFactors.array[i]; // If max, save it.
                }
            }
        }
    }
    freeArray(&primeFactors); // Release the ... memory
    return 0; // End of the algorithm
}
Ejemplo n.º 7
0
int XSetFontPath(Display* display, char** directories, int ndirs) {
    SET_X_SERVER_REQUEST(display, X_SetFontPath);
    char* path;
    size_t i;
    while (fontSearchPaths->length > 0) {
        // Clear the array and free the data
        free(removeArray(fontSearchPaths, 0, False));
    }
    if (directories == NULL || ndirs == 0) {
        // Reset the search path to the default for the compiled platform
        ndirs = ARRAY_LENGTH(DEFAULT_FONT_SEARCH_PATHS);
        directories = (char **) DEFAULT_FONT_SEARCH_PATHS;
    }
    for (i = 0; i < ndirs; i++) {
        if (checkFontPath(directories[i])) {
            path = strdup(directories[i]);
            if (path == NULL) {
                handleOutOfMemory(0, display, 0, 0);
            } else {
                insertArray(fontSearchPaths, path);
            }
        }
    }
    return updateFontCache() ? 1 : 0;
}
Ejemplo n.º 8
0
	void process() { 
		intSet::const_iterator it;
		for ( it = prime_powers.begin(); it != prime_powers.end(); it++ ) {
			int v = *it;
			if ( v < 3 )
				continue;
			if ( v > MAXV )
				break;

			int i = 2;
			bool toobig = false;
			while ( ! toobig ) {
				array * arr = new array();
				arr->N = i * i;
				arr->k = ipow( v, i );
				arr->v = v;
				arr->t = 3;

				if ( arr->k > MAXK ) {
					toobig = true;
				}

				arr->type = 'D';
				arr->source = id;

				printArray( arr );
				insertArray( arr );

				i++;
			}
		}
	}
Ejemplo n.º 9
0
/*
    Insert an item to the list at a specified position. We insert before the item at "index".
    ie. The inserted item will go into the "index" location and the other elements will be moved up.
 */
PUBLIC int ejsInsertItem(Ejs *ejs, EjsArray *ap, int index, EjsAny *item)
{
    if (insertArray(ejs, ap, index, item) == 0) {
        /* Should never fail - only for memory errors */
        return -1;
    }
    return index;
}
Ejemplo n.º 10
0
void
UART1_Handler(void) {
    // Acknowledge that interrupt is processed.
    uart->ICR |= 0x50UL;

    while((uart->FR & (1 << 4)) == 0) {
        insertArray(&uartData, (uint8_t)uart->DR);
    }
}
Ejemplo n.º 11
0
void BPlusIndexP::splitAddLeaf(IndexPage* page, Index* index) {
	Logger* log = getLogger(NULL);

	//temporal arrays
	Index** tmpelements = (Index**)malloc(sizeof(Index*) * (BUCKET_MAX_ELEMENTS + 1));
	//IndexPage** tmppointers = (IndexPage**)malloc(sizeof(IndexPage*) * (BUCKET_MAX_ELEMENTS + 2));

	initializeArray((void**)tmpelements, BUCKET_MAX_ELEMENTS);
	copyArray((void**)page->elements, (void**)tmpelements, 0, BUCKET_MAX_ELEMENTS - 1, 0);

	int posToInsert = findInsertPositionArray(tmpelements, index, page->size, BUCKET_MAX_ELEMENTS);

	insertArray((void**)tmpelements, index, posToInsert, BUCKET_MAX_ELEMENTS + 1);

	// clean the previous "left"
	initializeArray((void**)page->elements, BUCKET_MAX_ELEMENTS);

	IndexPage* rightPage = new IndexPage();
	int midPoint = (BUCKET_MAX_ELEMENTS / 2);
	copyArray((void**)tmpelements, (void**)page->elements, 0, midPoint, 0);
	page->size = (BUCKET_MAX_ELEMENTS / 2) + 1;
	// Clean up the elements moved to the rightPage
	for (int x = page->size; x < BUCKET_MAX_ELEMENTS; x++) {
		page->elements[x] = NULL;
		page->pointers[x + 1] = NULL;
	}
	// cleans the last one
	page->pointers[BUCKET_MAX_ELEMENTS] = NULL;
	refreshParentRelationship(page);

	//copyArray((void**)tmppointers, (void**)page->pointers, 0, midPoint + 1, 0);
	copyArray((void**)tmpelements, (void**)rightPage->elements, midPoint + 1, BUCKET_MAX_ELEMENTS, 0);
	rightPage->size = (BUCKET_MAX_ELEMENTS / 2) + 1;
	refreshParentRelationship(rightPage);
	//copyArray((void**)tmppointers, (void**)rightPage->pointers, midPoint + 2, BUCKET_MAX_ELEMENTS + 2, 0);

	// Promotion
	IndexPage* parentElement = page->parentElement;
	Index* copyElement = new Index(*rightPage->elements[0]);
	if (parentElement == NULL) {
		createRoot(copyElement, page, rightPage);
	} else {
		addElement(parentElement, copyElement, rightPage);
	}
	parentElement = rightPage->parentElement;

	free(tmpelements);
	refreshParentRelationship(parentElement);

	persistPage(page);
	persistPage(rightPage);
	persistPage(page->parentElement);
}
Ejemplo n.º 12
0
	void process() { 
		for ( int t = 3; t <= MAXT; t++ ) {
 			for ( int v = t; v <= MAXV; v++ ) {
				array * arr = new array();
				arr->N = 1;
				arr->k = v;
				arr->v = v;
				arr->t = t;

				arr->type = 'D';
				arr->source = id;

				printArray( arr );
				insertArray( arr );
			}
		}
	}
Ejemplo n.º 13
0
/*
  Go through each unique source of the packets waiting on arp_req
  and send a ICMP host unreachable message.
*/
void notify_sources_badreq(struct sr_instance *sr, struct sr_arpreq *arp_req){
  /*For each packet waiting on arp_req, determine unique sources and send them a ICMP.  Have to read packet to find source*/
  /*Go through each packet and for each unique source, send TCMP to say host unreachable*/
    struct sr_packet *packet = arp_req->packets;
    Array sources;
    initArray(&a, 1);
    while (packet){
        uint8_t source[ETHER_ADDR_LEN] = get_ether_source(packet);
        /*Check to make sure we haven't sent to this source yet*/
        if (!array_contains(sources, source)){
          send_host_runreachable(source, packet->buf);
          insertArray(&sources, source);
        }
        free(&source);
        packet = packet->next;
    }
    freeArray(&sources);
}
Ejemplo n.º 14
0
	void process( array * base ) {
		if ( base->k >= MAXK )
			return;
		if ( base->t != 3 )
			return;

 		array * arr = new array();
		arr->N = base->N + 1;
		arr->k = base->k + base->v - 2;
		arr->v = base->v;
		arr->t = base->t;

		arr->type = 'C';
		arr->source = id;

		arr->ingredients.push_back( base );

		insertArray( arr );
	}
Ejemplo n.º 15
0
/*	checkPrime: determine if the given number is prime;
if prime, add it to the prime Array and return 1;
if not, return 0.
arguments: number (long long)
returns: integer 0 (false) or 1 (true)	*/
int checkPrime(long long number)
{
	int isPrime = 1;	// flag (0 = false, 1 = true)
	long long sq = 0;			// store square root
	sq = (long long)(sqrt(number) + 0.5);	// get square root of number
	if (number == 1) return 0;	// not a prime; prevent false negatives
								//  these quick checks cut processing time a little
	if (number > 3 && (number % 2 == 0 || number % 3 == 0)) return 0;
	//  loop through the array:
	for (unsigned int i = 0; i < prime.used; i++)
	{
		if (prime.array[i] > sq) break;  // stopping at square root of the number saves a whole lot of time
		if (number % prime.array[i] == 0) {
			isPrime = 0; 	// divisible by another prime
			break;			// don't check any more
		}
	}
	// if prime, add to array
	if (isPrime) insertArray(&prime, number);
	return isPrime;			// return the flag
}
Ejemplo n.º 16
0
	void process() { 
		intSet::const_iterator it;
		for ( it = primes.begin(); it != primes.end(); it++ ) {
			int v = *it;
			if ( v > MAXV )
				break;

			if ( v == 11 || v >= 17 ) {
				array * arr = new array();
				arr->N = 6;
				arr->k = v * v;
				arr->v = v;
				arr->t = 4;

				arr->type = 'D';
				arr->source = id;

				printArray( arr );
				insertArray( arr );
			}
		}
	}
Ejemplo n.º 17
0
Bool initFontStorage() {
    size_t fontCount = 0;
    DIR* fontDirectory;
    struct dirent* entry;
    fontSearchPaths = malloc(sizeof(Array));
    if (fontSearchPaths == NULL) {
        return False;
    }
    if (!initArray(fontSearchPaths, ARRAY_LENGTH(DEFAULT_FONT_SEARCH_PATHS))) {
        return False;
    }
    for (size_t i = 0; i < ARRAY_LENGTH(DEFAULT_FONT_SEARCH_PATHS); i++) {
        const char *path = DEFAULT_FONT_SEARCH_PATHS[i];
        if (checkFontPath(path)) {
            fontDirectory = opendir(path);
            if (fontDirectory == NULL) continue;
            path = strdup(path);
            if (path == NULL) return False;
            insertArray(fontSearchPaths, (char*) path);
            // Count the font files in the directory
            while ((entry = readdir(fontDirectory)) != NULL) {
                if (strncmp(&entry->d_name[strlen(entry->d_name) - 4], ".ttf", 4) == 0) {
                    fontCount++;
                }
            }
            closedir(fontDirectory);
        }
    }
    fontCache = malloc(sizeof(Array));
    if (fontCache == NULL) {
        return False;
    }
    if (!initArray(fontCache, fontCount)) {
        return False;
    }
    return updateFontCache();
}
Ejemplo n.º 18
0
void validate_yolo_recall(char *cfgfile, char *weightfile, char *val_images, char *out_dir, float th, int log, int draw)
{

	network net = parse_network_cfg(cfgfile);
	if(weightfile){
		load_weights(&net, weightfile);
	}
	set_batch_network(&net, 1);
	fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net.learning_rate, net.momentum, net.decay);
	srand(time(0));

	//create output directory if it does not exist
	struct stat st= {0};
	if(stat(out_dir,&st)==-1){
		fprintf(stderr,"Creating output directory\n");
		mkdir(out_dir,0700);
	}

	char *base = out_dir;
	list *plist = get_paths(val_images);
	char **paths = (char **)list_to_array(plist);

	layer l = net.layers[net.n-1];
	int classes = l.classes;
	int square = l.sqrt;
	//int side = l.side;
	int rows = l.rows;
	int cols = l.cols;

	int j, k;
	FILE **fps = calloc(classes, sizeof(FILE *));
	for(j = 0; j < classes; ++j){
		char buff[1024];
		snprintf(buff, 1024, "%s%s.txt", base, voc_names[j]);
		fps[j] = fopen(buff, "w");
	}
	box *boxes = calloc(rows*cols*l.n, sizeof(box));
	float **probs = calloc(rows*cols*l.n, sizeof(float *));
	for(j = 0; j < rows*cols*l.n; ++j) probs[j] = calloc(classes, sizeof(float *));

	int m = plist->size;
	int i=0;

	float thresh = th;
	float iou_thresh[11] = {0.0,0.05,0.1,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.5};
	float nms = 0.1;

	int total = 0;
	int correct[11] = {0,0,0,0,0,0,0,0,0,0,0};
	int proposals = 0;
	float avg_iou = 0;
	Vector id_found;
	Vector id_invalid;
	initArray(&id_found,5);
	initArray(&id_invalid,5);

	for(i = 0; i < m; ++i){
		char * image_path = strtok(paths[i]," ");
        char * label_path = strtok(NULL," ");

		image orig = load_image(image_path, 0, 0,net.c);
		image color;
		if(draw)
			color = load_image(image_path, 0, 0, 3);
		image sized = resize_image(orig, net.w, net.h);
		//char *id = basecfg(path);
		float *predictions = network_predict(net, sized.data);
		convert_detections(predictions, classes, l.n, square, rows, cols, 1, 1, thresh, probs, boxes, 0);
		if (nms) do_nms(boxes, probs, rows*cols*l.n, 1, nms);



		int num_labels = 0;
		box_label *truth = read_boxes(label_path, &num_labels);
		int old_p = proposals;
		for(k = 0; k < rows*cols*l.n; ++k){
			if(probs[k][0] > thresh){
				++proposals;
			}
		}

		if(old_p!=proposals){
			if(log){
				char filename[256];
				sprintf(filename, "%s/%d.txt", base,i);
				printf("log in file %s\n",filename);
				FILE * out = fopen(filename, "w");
				fprintf(out,"W\tH\tX\tY\n");
				for(k=0; k<rows*cols*l.n; ++k){
					if(probs[k][0] > thresh){
						fprintf(out, "%f\t%f\t%f\t%f\n",boxes[k].w,boxes[k].h,boxes[k].x,boxes[k].y);
					}
				}
				fclose(out);
			}
			if(draw){
				draw_detections(color, l.rows*l.cols*l.n, thresh, boxes, probs, voc_names, voc_labels, CLASSNUM);

				show_image(color, "predictions");

				#ifdef OPENCV
				cvWaitKey(0);
				//cvDestroyAllWindows();
				#endif
			}
		}
		for (j = 0; j < num_labels; ++j) {
			++total;

			while(id_found.used <= truth[j].id){
				insertArray(&id_invalid,0);
				insertArray(&id_found,0);
			}
							
			if(truth[j].classe > CLASSNUM-1)
				id_invalid.array[truth[j].id]=1;

			box t = {truth[j].x, truth[j].y, truth[j].w, truth[j].h};
			float best_iou = 0;
			for(k = 0; k < rows*cols*l.n; ++k){
				float iou = box_iou(boxes[k], t);
				//find overlapping prediction
				if(iou > best_iou){
					//find the predicted class
					float best_score = thresh;
					int best_class_index = -1;
					for(int c=0; c<CLASSNUM; c++){
						if(probs[k][c]>best_score){
							best_score = probs[k][c];
							best_class_index = c;
						}
					}
					//check if it's good or not
					if(best_class_index == truth[j].classe)
						best_iou = iou;
				}
			}
			avg_iou += best_iou;
			for(int k=0; k<11; k++){
				if(best_iou > iou_thresh[k]){
					id_found.array[truth[j].id]=1;
					++correct[k];
				}
			}
		}
		if(i%10==0){
			printf("\033[2J");
			printf("\033[1;1H");
			printf("#img\tPred\tTP\ttot\tRPs/Img\tAvg-IOU\tRecall\tPrecision\n");
			printf("%5d\t%5d\t%5d\t%5d\t%.2f\t%.2f%%\t%.2f%%\t%.2f%%\n", i, proposals, correct[10], total, (float)proposals/(i+1), avg_iou*100/total, 100.*correct[10]/total, 100.*correct[10]/proposals);
			printf("IOU_th\tTP\tFP\tRecall\tPrecision\n");
			for(int k=0; k<11; k++){
				printf("%.2f%%\t%5d\t%5d\t%.2f%%\t%.2f%%\t\n", iou_thresh[k], correct[k], proposals-correct[k], 100.*correct[k]/total, 100.*correct[k]/proposals);
			}
			int found=0;
			int invalid = 0;
			for(int i=0; i<id_found.used; i++){
				if(id_invalid.array[i]!=1)
					found+=id_found.array[i];
				invalid+=id_invalid.array[i];
			}
			printf("Founded: %d/%d\t%d\n", found, id_found.used-invalid,invalid);
		}
		//free(id);
		free_image(orig);
		free_image(sized);
	}
	for(j = 0; j < classes; ++j){
		fprintf(fps[j],"IOU_th;TP;FP;Recall;Precision\n");
		for(int k=0; k<11; k++){
			fprintf(fps[j],"%.2f%%;%5d;%5d;%.2f%%;%.2f%%;\n", iou_thresh[k], correct[k], proposals-correct[k], 100.*correct[k]/total, 100.*correct[k]/proposals);
		}
		fprintf(fps[j], "\n\nFounded;Total;\n");
		int found=0;
		int invalid = 0;
		for(int i=0; i<id_found.used; i++){
			if(id_invalid.array[i]!=1)
					found+=id_found.array[i];
			invalid+=id_invalid.array[i];
		}
		fprintf(fps[j], "%d;%d;\n", found, id_found.used-invalid);
		fclose(fps[j]);
	}
	freeArray(&id_found);
}
Ejemplo n.º 19
0
Bool updateFontCache() {
    size_t i, entryNameLen;
    size_t fontCacheIndex = 0;
    DIR* fontDirectory;
    struct dirent* entry;
    char pathBuffer[512];
    for (i = 0; i < fontSearchPaths->length; i++) {
        char* fontDirPath = fontSearchPaths->array[i];
        fontDirectory = opendir(fontDirPath);
        if (fontDirectory == NULL) {
            free(removeArray(fontSearchPaths, i, False));
            i--;
            continue;
        }
        while ((entry = readdir(fontDirectory)) != NULL) {
            // We add all missing fonts to the cache, swapping their position to the front.
            // We can be sure, that the fonts with an index lower than fontCacheIndex are valid.
            entryNameLen = strlen(entry->d_name);
            if (entryNameLen > 4 && strncmp(&entry->d_name[entryNameLen - 4], ".ttf", 4) == 0) {
                ssize_t index = findInArrayNCmp(fontCache, entry->d_name,
                                                fontCacheIndex, &fontCacheEntryFileNameCmp);
                
                if (index == -1) {
                    snprintf(pathBuffer, 512, "%s/%s", fontDirPath, entry->d_name);
                    TTF_Font* font = TTF_OpenFont(pathBuffer, FONT_SIZE);
                    if (font == NULL) continue;
                    FontCacheEntry* fontCacheEntry = malloc(sizeof(FontCacheEntry));
                    if (fontCacheEntry == NULL) {
                        TTF_CloseFont(font);
                        closedir(fontDirectory);
                        return False;
                    }
                    fontCacheEntry->filePath = strdup(pathBuffer);
                    fontCacheEntry->XLFName = getFontXLFDName(font);
                    if (fontCacheEntry->filePath == NULL ||  fontCacheEntry->XLFName == NULL) {
                        if (fontCacheEntry->filePath != NULL) free(fontCacheEntry->filePath);
                        if (fontCacheEntry->XLFName != NULL) free(fontCacheEntry->XLFName);
                        free(fontCacheEntry);
                        TTF_CloseFont(font);
                        closedir(fontDirectory);
                        return False;
                    }
                    if (!insertArray(fontCache, fontCacheEntry)) {
                        free(fontCacheEntry->filePath);
                        free(fontCacheEntry->XLFName);
                        free(fontCacheEntry);
                        TTF_CloseFont(font);
                        closedir(fontDirectory);
                        return False;
                    }
                    index = fontCache->length - 1;
                }
                if (index != fontCacheIndex) {
                    swapArray(fontCache, (size_t) index, fontCacheIndex);
                }
                fontCacheIndex++;
            }
        }
        closedir(fontDirectory);
    }
    while (fontCache->length > fontCacheIndex) {
        // Remove all invalid cache entries
        FontCacheEntry* cacheEntry = removeArray(fontCache, fontCache->length - 1, True);
        free(cacheEntry->filePath);
        free(cacheEntry->XLFName);
        free(cacheEntry);
    }
    return True;
}
Ejemplo n.º 20
0
	void process2( array * base ) {
		int M2 = base->k;
		int M1 = base->v;

		int t = base->t + 1;
		for ( int v = t; v <= MAXV; v++ ) {
			bool toobig = false;

			array * array3 = getBestArray( M2, v, t );
			if ( array3 == NULL )
				continue;

			fullSortTableType arrays;
			query( arrays, t, t, v, v, 0, -1 );

			int M0;
			int lastM0 = 0;

			fullSortTableType::iterator it;
			for ( it = arrays.begin(); it != arrays.end(); it++ ) {
				array * array1 = *it;

				M0 = array1->k / M1;

				if ( M0 == lastM0 )
					continue;

				lastM0 = M0;

				__int64 lNewK = (__int64) M0 * (__int64) M2;
				if ( lNewK > INT_MAX  ) {
					//std::cout << "Avoided overflow of k." << std::endl;
					break;
				}
				int k = (int) lNewK;

				array * arr = new array();

				__int64 lN = (__int64) array1->N * (__int64) base->N + (__int64) array3->N;
				if ( lN > INT_MAX  ) {
					//std::cout << "Avoided overflow of N." << std::endl;
					break;
				}
				arr->N = (int) lN;
				arr->k = k;
				arr->v = v;
				arr->t = t;

				arr->type = 'C';
				arr->source = id;

				arr->ingredients.push_back( array1 );
				arr->ingredients.push_back( base );
				arr->ingredients.push_back( cleanCopy( array3 ) );

				std::string value;
				int_to_string( M0, value );
				arr->parameters[ "M0" ] = value;

				int_to_string( M1, value );
				arr->parameters[ "M1" ] = value;

				int_to_string( M2, value );
				arr->parameters[ "M2" ] = value;

				int_to_string( 2, value );
				arr->parameters[ "base" ] = value;

				insertArray( arr, &arrays );

				if ( k >= MAXK )
					break;
			}

			deleteIfRule( array3 );
		}
	}
Ejemplo n.º 21
0
static int32_t solve_FALM(struct Struct_FALM *s, struct Struct_FGM *p_in)
{
	// calculating alpha
	real_t alpha = s->opt->rho;

	// Dynamc Arrays for ds and pf
	struct Array ds_array, pf_array;
	initArray(&ds_array, 100);
	initArray(&pf_array, 100);

	// Declaration and initialization of other necessary variables
	real_t pf = s->opt->eps_pf + 1;
	uint32_t niter_feasible_ds = 0;
	uint32_t niter_feasible_pf = 0;
	uint32_t last_eps_ds = 0;
	uint32_t niter = 1;
	uint32_t niter_inner = 0;
	real_t dual_value_new = 0.0;
	real_t dual_value_diff = s->opt->eps_ds + 1;
	s->res->exitflag = 1;
	s->res->out->exitflag_inner = 1;
	s->res->out->num_exceeded_max_niter_inner = 0;
	// new:
	real_t theta = 1.0;
	real_t theta_new = 0.0;
	real_t beta = 0.0;
	real_t S = theta;

	// Clock
	clock_t tic, toc, tic_in, toc_in;
	tic = clock();

	// solve inner problem first time
	// with: c_in = c + A'*y1 - A'*y2 = c + A'(y1-y2) = c + A'(lambda-lambda2)
	// NOTE: As long as lambda = lambda2 = y1 = y2 0, c_in = c
	vector_sub(s->prob->c,s->rho_At_b,p_in->c,N);
	vector_copy(s->prob->z0,p_in->z0,N); // Initialize z0

	tic_in = clock();
	niter_inner += FGM(p_in);
	toc_in = clock();

	s->res->out->time_tot_inner = (real_t)(toc_in-tic_in);
	s->time_inner_y = (real_t)(toc_in-tic_in);
	if(p_in->exitflag == 2){
		s->res->out->exitflag_inner = 2;
		s->res->out->num_exceeded_max_niter_inner++;
	}
	vector_copy(p_in->zopt,s->z,N);
	vector_copy(p_in->zopt,s->z_ds,N);
	mtx_vec_mul(s->prob->A,s->z_ds,s->A_z_ds,M,N); // used in dual_obj
	vector_copy(s->z,s->summ,N);
	vector_scalar_mul(s->summ,(theta/S),s->summ,N);

	// find the value of the dual function (Lagrangian) first time
	real_t dual_value = dual_obj(s);

	/* ##################################################################################
			START WHILE-LOOP
	################################################################################## */

	while (dual_value_diff > s->opt->eps_ds || pf > s->opt->eps_pf)
	{

		if (niter > s->opt->maxiter_outer){
			//printf("reached maximum number of iterations in FALM\n");
			niter_feasible_ds--;
			niter_feasible_pf--;
			s->res->exitflag = 2;
			break;
		}
		if (dual_value_diff < s->opt->eps_ds){
			niter_feasible_ds++;
			last_eps_ds = 1;
		}
		else{
			last_eps_ds = 0;
		}
		if (pf < s->opt->eps_pf)
			niter_feasible_pf++;

		/* *********************************************************************
				Finding the next lambda
		********************************************************************* */

		// lambda += alpha * (A*z - b)
		// NOTE: re-use the 'lambda' vector instead of creating 'lambda_new'

		mtx_vec_mul(s->prob->A,s->z,s->A_z,M,N); 	// A*z

		// lambda = y1 + alpha*(A*z-b_ub_hat)
		vector_sub(s->A_z,s->prob->b,s->temp3_dim_M,M);	// ANS - b
		vector_scalar_mul(s->temp3_dim_M,alpha,s->temp3_dim_M,M);	// ANS * alpha
		vector_add(s->temp3_dim_M,s->y1,s->lambda,M);	// lambda = y1 + ANS
		// NOTE: No projection


	    /* *********************************************************************
				Finding the next y
		********************************************************************* */

		// y = lambda + beta * (lambda-lambda_old)

		// calculating beta
		theta_new = 0.5 * (1.0 + sqrt(1.0 + 4.0*(theta*theta)));
		beta = (theta-1.0)/theta_new;

		// y1
		vector_sub(s->lambda,s->lambda_old,s->temp2_dim_M,M); // lambda - lambda_old
		vector_scalar_mul(s->temp2_dim_M,beta,s->temp2_dim_M,M); // ANS * beta
		vector_add(s->lambda,s->temp2_dim_M,s->y1,M); 	// y1 = ANS + lambda


		/* *********************************************************************
				Solving the inner problem
		********************************************************************* */

		// First calculate the new c (c_hat) for the inner problem,
		// c_hat = p_in->c = c + A' * (y1_new - y2_new)

		vector_copy(s->prob->c,p_in->c,N);

		// p_in->c = c + A' * y1
		mtx_vec_mul(s->prob->A_t,s->y1,s->temp1_dim_N,N,M); // A' * y1
		vector_add(p_in->c,s->temp1_dim_N,p_in->c,N);	// p_in->c = ANS + c
		vector_sub(p_in->c,s->rho_At_b,p_in->c,N);	// - rho *A'*b

		// Compute the new optimal z (s->z) from the inner problem
		vector_copy(s->z, p_in->z0, N); // Warm start

		tic_in = clock();
		niter_inner += FGM(p_in);
		toc_in = clock();
		s->res->out->time_tot_inner += (real_t)(toc_in-tic_in);
		s->time_inner_y += (real_t)(toc_in-tic_in);
		if(p_in->exitflag == 2){
			s->res->out->exitflag_inner = 2;
			s->res->out->num_exceeded_max_niter_inner++;
		}
		vector_copy(p_in->zopt,s->z,N);

		/* *********************************************************************
				Finding dual_value_diff
		********************************************************************* */

		// calculate the difference between the new and previousdual function value (ds)
		// NOTE: must calculate the 'inner problem' one more time, with lambda instead of y

		vector_copy(s->prob->c,p_in->c,N);


		// p_in->c = c + A' * lambda
		mtx_vec_mul(s->prob->A_t,s->lambda,s->temp1_dim_N,N,M); // A' * lambda
		vector_add(p_in->c,s->temp1_dim_N,p_in->c,N);	// p_in->c = ANS + c
		vector_sub(p_in->c,s->rho_At_b,p_in->c,N);	// - rho *A'*b


		 // Finding new z_ds
		vector_copy(s->z_ds, p_in->z0, N); // Warm start
		tic_in = clock();
		niter_inner += FGM(p_in);
		toc_in = clock();
		s->res->out->time_tot_inner += (real_t)(toc_in-tic_in);

		if(p_in->exitflag == 2){
			s->res->out->exitflag_inner = 2;
			s->res->out->num_exceeded_max_niter_inner++;
		}
		vector_copy(p_in->zopt,s->z_ds,N);
		mtx_vec_mul(s->prob->A,s->z_ds,s->A_z_ds,M,N); // used in dual_obj

		// Calculate dual_value_new
		dual_value_new = dual_obj(s);	// z_ds is used in this function
		dual_value_diff = abs_2(dual_value_new - dual_value);
		dual_value = dual_value_new;

		/* *********************************************************************
				Finding pf
		********************************************************************* */

		// pf = norm2(  max([A*z_pf - b_ub_hat ; -A*z_pf + b_lb_hat]) , 0)  )
		// NOTE: Algorithm 3 (last) => we use z_pf = z_ds
		// 		 Algorithm 4 (average) => we use z_pf = z_avg = summ_k / (niter+1)

		if (s->opt->algorithm == 7) {
		// *** LAST z in stopping criteria ***

			vector_sub(s->A_z_ds,s->prob->b,s->pf_vec,M); // (A*z) - b_ub_hat
			// NOTE: No projection

		}
		else if (s->opt->algorithm == 8) {
		// *** AVERAGE z in pf stopping criteria ***

			// Calculating z_avg
			S = S + theta_new;
			vector_scalar_mul(s->z,theta_new,s->temp1_dim_N,N); // S * theta_new
			vector_add(s->summ,s->temp1_dim_N,s->summ,N); // summ += ANS
			vector_scalar_mul(s->summ,1.0/S,s->z_avg,N); //z_avg = summ / S
			mtx_vec_mul(s->prob->A,s->z_avg,s->temp2_dim_M,M,N); // A * z_pf = A * z_avg

			vector_sub(s->temp2_dim_M,s->prob->b,s->pf_vec,M); // (A*z) - b
			// NOTE: No projection

		}
		else {
			ERROR("Choose algorithm 7 or 8 when running FALM()\n");
    		return -1;
		}

	    // Take the norm
	    pf = vector_norm_2(s->pf_vec, s->info->pf_vec_length); // norm2

		// store the result of the stopping criteria
		insertArray(&ds_array, dual_value_diff);
		insertArray(&pf_array, pf);

		/* *********************************************************************
			 			Update the variables
		********************************************************************* */

		vector_copy(s->lambda,s->lambda_old,M);
		//vector_copy(s->lambda2,s->lambda2_old,M);
		theta = theta_new;
		niter++;

	} 	/* #### END WHILE-LOOP #### */


	/* *********************************************************************
				 		Setting the result
	********************************************************************* */

	// Clock
	toc = clock();
	s->res->out->time = (real_t)(toc - tic) / CLOCKS_PER_SEC;
	s->res->out->time_tot_inner /=  CLOCKS_PER_SEC;
	s->time_inner_y /=  CLOCKS_PER_SEC;
	//printf("time inner y: %f\n", s->time_inner_y);

	if (s->opt->algorithm == 7) {
		s->res->zopt = s->z_ds;
		s->res->fopt = obj(s->z_ds, s->prob->H, s->prob->c, s->temp1_dim_N);
	}
	else if (s->opt->algorithm == 8) {
		s->res->zopt = s->z_avg;
		s->res->fopt = obj(s->z_avg, s->prob->H, s->prob->c, s->temp1_dim_N);
	}
	else {
		ERROR("Choose algorithm 7 or 8 when running FALM()\n");
		return -1;
	}

	s->res->lambda1 = s->lambda;
	//s->res->lambda2 = s->lambda2;
	s->res->out->iterations = --niter;
	s->res->out->iterations_inner_tot = niter_inner;
	s->res->out->niter_feasible_ds = ++niter_feasible_ds;
	s->res->out->niter_feasible_pf = ++niter_feasible_pf;

	if (last_eps_ds == 1)
		s->res->out->flag_last_satisfied = 2;
	else
		s->res->out->flag_last_satisfied = 1;

	// Copy ds_vector and pf_vector
	s->res->out->ds_vector = (real_t *)realloc(s->res->out->ds_vector, (niter) * sizeof(real_t));
	s->res->out->pf_vector = (real_t *)realloc(s->res->out->pf_vector, (niter) * sizeof(real_t));
	vector_copy(ds_array.array,s->res->out->ds_vector,niter);
	vector_copy(pf_array.array,s->res->out->pf_vector,niter);
	freeArray(&ds_array);
	freeArray(&pf_array);

	return 0;
}
Ejemplo n.º 22
0
int main() {
	//Two booleans are used when taking calculating the runtime
	int clockOn = 0;
	int totalClockOn = 1;
	//Variables used in calculating runtime
	clock_t start, clockBeforeRead, clockAfterRead, clockAfterLowPass,
			clockAfterHighPass, clockAfterDer, clockAfterSquare, clockAfterMWI,
			clockAfterIdentifyPeaks, end;
	double cpuTimeUsed;
	double timeReadData = 0;
	double timeLowPass = 0;
	double timeHighPass = 0;
	double timeDerivative = 0;
	double timeSquare = 0;
	double timeMWindowInt = 0;
	double timeIdentifyPeaks = 0;

	//The file to read from
	static const char filename[] = "ECG.txt";
	FILE *file = fopen(filename, "r");

	//Arrays and a variable to keep track of the values after each filter
	int input[13] = { 0 };
	int afterLowpass[33] = { 0 };
	int afterHighpass[5] = { 0 };
	int afterDerivative = 0;
	int afterSquare[30] = { 0 };
	int afterWindowIntegration[3] = { 0 };

	int value;
	int counter = 0;

	if (totalClockOn) {
		start = clock();
	}
	//The loops runs as long as it has not reached the end of the file
	while (!feof(file)) {
		if (clockOn) {
			clockBeforeRead = clock();
		}
		counter++;
		//The nex value is saved in the variable "value"
		value = getNextData(file);
		insertArray(input, 13, value);
		/*if (clockOn) {
		 clockAfterRead = clock();
		 timeReadData =+ ((double) ((clockAfterRead - clockBeforeRead)) / CLOCKS_PER_SEC ) * 1000;
		 }*/
		lowPass(input, afterLowpass);
		/*if (clockOn) {
		 clockAfterLowPass = clock();
		 timeLowPass =+ ((double) ((clockAfterLowPass - clockAfterRead)) / CLOCKS_PER_SEC ) * 1000;
		 }*/
		highPass(afterLowpass, afterHighpass);
		/*if (clockOn) {
		 clockAfterHighPass = clock();
		 timeHighPass =+ ((double) ((clockAfterHighPass - clockAfterLowPass)) / CLOCKS_PER_SEC ) * 1000;
		 }*/
		afterDerivative = derivative(afterHighpass);
		/*if (clockOn) {
		 clockAfterDer = clock();
		 timeDerivative =+ ((double) ((clockAfterDer - clockAfterHighPass)) / CLOCKS_PER_SEC ) * 1000;
		 }*/
		square(afterDerivative, afterSquare);
		/*if (clockOn) {
		 clockAfterSquare = clock();
		 timeSquare =+ ((double) ((clockAfterSquare - clockAfterDer)) / CLOCKS_PER_SEC ) * 1000;
		 }*/
		mWindowIntegration(afterSquare, afterWindowIntegration);
		if (clockOn) {
			clockAfterMWI = clock();
			timeMWindowInt = +((double) ((clockAfterMWI - clockBeforeRead))
					/ CLOCKS_PER_SEC) * 1000;
		}
		identifyPeaks(afterWindowIntegration);
		if (clockOn) {
			clockAfterIdentifyPeaks = clock();
			timeIdentifyPeaks = +((double) ((clockAfterIdentifyPeaks
					- clockAfterMWI)) / CLOCKS_PER_SEC) * 1000;
		}
	}
	if (totalClockOn) {
		end = clock();
		cpuTimeUsed = ((double) ((end - start)) / CLOCKS_PER_SEC) * 1000;
		printf("Total cpu time: %f milliseconds\n", cpuTimeUsed);
	}
	if (clockOn) {
		//printf("Average time read data: %f nanoseconds\nAverage time Low Pass filter: %f nanoseconds\nAverage time High Pass filter: %f nanoseconds\n", timeReadData, timeLowPass, timeHighPass);
		//printf("Average time derivative filter: %f nanoseconds\nAverage time square filter: %f nanoseconds\nAverage time moving window integration filter: %f nanoseconds\n",timeDerivative, timeSquare, timeMWindowInt);
		printf("Time to apply filters: %f milliseconds\n", timeMWindowInt);
		printf("Time to identify peaks: %f milliseconds\n", timeIdentifyPeaks);
	}
	return 0;

}
Ejemplo n.º 23
0
	void process1( array * base, array * a3in = NULL, fullSortTableType * vulnerable = NULL ) {
		array * prev = getPreviousArray( base );
		int min = (prev != NULL) ? (prev->k + 1) : base->v;
		int k = base->k;
		int range = k - min;

		int M0, M1, M2;

		fullSortTableType arrays;
		if ( a3in ) {
			arrays.insert( a3in );
		} else {
			query( arrays, base->t, base->t, base->v, base->v, 0, -1 );
		}

		for ( M1 = base->t - 1; (M1 <= MAXV) && (M1 < k); M1++ ) {
			if ( (k % M1) < range ) {
                M0 = k / M1;

				if ( M0 <= 1 )
					continue;

				fullSortTableType::iterator it;
				for ( it = arrays.begin(); it != arrays.end(); it++ ) {
					array * array3 = *it;

					M2 = array3->k;
					array * array2 = getBestArray( M2, M1, base->t - 1 );

					if ( array2 == NULL )
						continue;

					__int64 lNewK = (__int64) M0 * (__int64) M2;
					if ( lNewK > INT_MAX  ) {
						//std::cout << "Avoided overflow of k." << std::endl;
						break;
					}
					int newK = (int) lNewK;

					array * arr = new array();

					__int64 lN = (__int64) base->N * (__int64) array2->N + (__int64) array3->N;
					if ( lN > INT_MAX  ) {
						//std::cout << "Avoided overflow of N." << std::endl;
						break;
					}
					arr->N = (int) lN;
					arr->k = newK;
					arr->v = base->v;
					arr->t = base->t;

					arr->type = 'C';
					arr->source = id;

					arr->ingredients.push_back( base );
					arr->ingredients.push_back( array2 );
					arr->ingredients.push_back( array3 );

					std::string value;
					int_to_string( M0, value );
					arr->parameters[ "M0" ] = value;

					int_to_string( M1, value );
					arr->parameters[ "M1" ] = value;

					int_to_string( M2, value );
					arr->parameters[ "M2" ] = value;

					int_to_string( (a3in != NULL ) ? 3 : 1, value );
					arr->parameters[ "base" ] = value;

					insertArray( arr, ( a3in != NULL ) ? vulnerable : &arrays );

					if ( newK >= MAXK )
						break;
				}
			}
		}
	}
Ejemplo n.º 24
0
	void process( array * base ) {
		if ( base->k * 2 >= MAXK ) {
			return;
		}

		if ( base->t != 3 ) {
			return;
		}

		// first, try this array is the main array
		array * subarray = getBestArray( base->k, base->v, 2 );

		int l = 2;
		bool toobig = false;

		if ( subarray != NULL ) {
			while ( !toobig ) {	
				array * leftover = getBestArray( l, base->v, 3 );

				if ( leftover != NULL ) {
					int pdcan = PDCAN( l, base->v );

					array * arr = new array();
					arr->N = base->N + pdcan * subarray->N + leftover->N;
					arr->k = base->k * l;
					arr->v = base->v;
					arr->t = 3;

					arr->type = 'C';
					arr->source = id;

					arr->ingredients.push_back( base );
					arr->ingredients.push_back( cleanCopy(subarray) );
					arr->ingredients.push_back( leftover );

					std::string value;
					int_to_string( l, value );
					arr->parameters[ "l" ] = value;

					int_to_string( pdcan, value );
					arr->parameters[ "pdcan" ] = value;

					insertArray( arr );
				}

				if ( (l * base->k) >= MAXK ) {
					toobig = true;
				}

				l++;				
			}

			deleteIfRule(subarray);
		}		

		// then, try it as the leftover array
		array * prev = getPreviousArray( base );

		int minL = prev != NULL ? prev->k + 1 : 2;

		fullSortTableType arrays;
		query( arrays, 3, 3, base->v, base->v, 0, (MAXK / l) * 3 );

		// TODO: step through PDCANs

		bool end = false;

		int pdV = PDCAN_v( base->v );

		l = pdV;
		while ( !end ) {
			l *= pdV;

			if ( l < minL )
				continue;

			if ( l >= base->k ) {
				l = base->k;
				end = true;
			}
			
			int deadV = 2;

			fullSortTableType::const_iterator superIt;
			for ( superIt = arrays.begin(); superIt != arrays.end(); superIt++ ) {
				array * superarray = *superIt;
					
				if ( superarray->v <= deadV ) {
					continue;
				}

				array * subarray = getBestArray( superarray->k, superarray->v, 2 );

				if ( subarray != NULL ) {
					int pdcan = PDCAN( l, base->v );

					array * arr = new array();
					arr->N = superarray->N + pdcan * subarray->N + base->N;
					arr->k = superarray->k * l;
					arr->v = superarray->v;
					arr->t = 3;

					arr->type = 'C';
					arr->source = id;

					arr->ingredients.push_back( superarray );
					arr->ingredients.push_back( subarray );
					arr->ingredients.push_back( base );

					std::string value;
					int_to_string( l, value );
					arr->parameters[ "l" ] = value;

					int_to_string( pdcan, value );
					arr->parameters[ "pdcan" ] = value;

					insertArray( arr, &arrays );

					if ( arr->k >= MAXK ) {
                        deadV = arr->v;
					}
				}

			}
		}	
	}
Ejemplo n.º 25
0
int main(int argc, char** argv)
{
	long long number = 0;	// input number (long long)
	long long sqroot = 0;	// square root of input number (long long)

	int checkForPrime = 0;		// input - skip prime number checking if 0
	int printAllNumbers = 0;	// input - print out all numbers, not just factors

	int isPrime = 0;
	initArray(&prime, 10);  // initially 10 spaces for prime numbers
	insertArray(&prime, 2);

	// INPUT loop: keep asking for positive integer until we get one
	do {
		number = getLongLong("Enter a positive integer: ");
	} while (number < 1);

	// INPUT: ask user whether to check for prime numbers
	checkForPrime = (int)getLongLong("Check for Prime Numbers? ");

	// INPUT: ask user whether to print only factors, all numbers, or all primes
	if (checkForPrime)
		printAllNumbers = (int)getLongLong("Print What (0 = Only Factors, 1 = All Numbers, 2 = Factors + Primes) ?");
	else
		printAllNumbers = (int)getLongLong("Print What (0 = Only Factors, 1 = All Numbers) ?");

	// calculate and print square root of the number (no need to exceed this)
	sqroot = (long long)(sqrt(number) + 0.5);
	printf("Square Root (rounded down): %lld\n\n", sqroot);

	// print header:
	printf("Number                          Prime  Other Factor\n");
	printf("==============================  =====  ==============================\n");

	begin = clock();	// store start time in order to time execution
						// begin factor calculation loop
	for (long long factor = 1; factor < sqroot; factor++)
	{
		/*	Call function to check if factor is prime:
		Current implementation requires checking all numbers;
		Possible future improvement. 	*/
		if (checkForPrime) isPrime = checkPrime(factor);

		// if factor is a factor of number:
		if (number % factor == 0) {
			printf("%30lld  %5s  %30lld\n", factor, (isPrime ? "Y" : ""), number / factor);
			// otherwise, if we're printing all numbers, or just primes:
		}
		else if (printAllNumbers > 0) {
			if (printAllNumbers == 1 || (printAllNumbers == 2 && isPrime))
				printf("%30lld  %5s\n", factor, (isPrime ? "Y" : ""));
		}
	}

	end = clock();	// set end time, calculate execution time & print:
	time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
	printf("\nExecution time: %f s\n\n", time_spent);

	freeArray(&prime);	// clear & free the prime array:

	return 0;	// return without error
}
Ejemplo n.º 26
0
int main(int argc, char *argv[]){
  //#define FACTOR 2
  //#define NUM_POINTS 10000
  //#define TOWER_RANGE 0.004
  //File name

  //Input arg 1: tower range in degrees
  //Input arg 2: tower proximity multiplication factor
  //Input arg 3: number of points to generate
  //Input arg 4: name of file to write to

  if (argc != 5){
    printf("Incorrect number of arguments. Should be exactly 4.\n possiblepoints <tower radius> <factor> <numPoints> <outfile>\n");
    exit(-1);
  }

  double towerRange = atof(argv[1]);
  int factor = atoi(argv[2]);
  int numPointsToGenerate = atoi(argv[3]);
  char * fileName = argv[4];


  //printf("size of towers: %ld", sizeof(towers));
  printf("Tower range: %f", towerRange);

  int endOfArray = sizeof(towers)/sizeof(double);
  // Latitude
  double minLatitude = towers[0];
  for (int i= 0 ; i < endOfArray - 1 ; i+=2){
    if (towers[i] < minLatitude)
      minLatitude = towers[i];
  }

  double maxLatitude = towers[0];
  for (int i= 0 ; i < endOfArray - 1 ; i+=2){
    if (towers[i] > maxLatitude)
      maxLatitude = towers[i];
  }

  double height = maxLatitude-minLatitude;

  // Longitude
  double minLongitude = towers[1];
  for (int i= 1 ; i < endOfArray ; i+=2){
    if (towers[i] < minLongitude)
      minLongitude = towers[i];
  }

  double maxLongitude = towers[1];
  for (int i= 1 ; i < endOfArray ; i+=2){
    if (towers[i] > maxLongitude)
      maxLongitude = towers[i];
  }

  double width = maxLongitude - minLongitude;


  int yDimension = 1000; //latitude
  int xDimension = 1000*width/height; //longitude
  double degreesperindex = height/yDimension;

  Array pointsToPickFrom;
  initArray(&pointsToPickFrom, xDimension*yDimension*2);


  int counter = 0;
  for (int i = 0 ; i < xDimension ; i++){
      for (int j = 0 ; j < yDimension ; j++){
          insertArray(&pointsToPickFrom, j);
          insertArray(&pointsToPickFrom, i);
          counter = counter + 2;
          //if (j == 0)
          //    printf("%d", counter);
      }
  }

  /* Output for debugging */
  /*
  #ifdef DEBUGGING
  for (int i = 0 ; i < xDimension*yDimension*2 ; i+=2){
    printf("point: %d %d \n" , pointsToPickFrom.array[i], pointsToPickFrom[i+1]);
  }
  #endif
  */

  //run for-loop for x, for y where for each i,j you check: let z = how many towers
  //are within rangesearch((i,j), towers, distance, 'euclidean')
  //add (i,j) to list of points z*factor nr of times
  for (int i = 0 ; i < xDimension ; i++){ //long
    for (int j = 0 ; j < yDimension ; j++){ //lat
      double actualLongitude = minLongitude + degreesperindex*i;
      double actualLatitude = minLatitude + degreesperindex*j;
      int towersInRange = numTowersInRange(actualLatitude, actualLongitude, towerRange);

      // add point towers in range many times to array
      for (int k = 0 ; k < towersInRange*factor ; k++){
        //printf("Point (%d, %d) in range of tower!", i, j);
        insertArray(&pointsToPickFrom, j);
        insertArray(&pointsToPickFrom, i);
      }
    }
  }



  //for (int i = 0; i< pointsToPickFrom.used-1 ; i+=2){
      // if (pointsToPickFrom.array[i] == 0 && i > 1){
      //   break;
      // }

   //   printf("possible point: (%d, %d)\n",pointsToPickFrom.array[i], pointsToPickFrom.array[i+1] );
  //}


  FILE * output;
  output = fopen(fileName, "w");
  if (!output){
    printf("Couldn't open file.\n");
    exit(-1);
  }
  srand(time(NULL));
  for (int i = 0 ; i < numPointsToGenerate ; i++){

    double randomFactor = (double)rand() / (double)RAND_MAX;
    long selectedIndex = randomFactor * pointsToPickFrom.used;

    #ifdef DEBUGGING
      printf("Random index: %ld\n", selectedIndex);
    #endif

    if (selectedIndex > pointsToPickFrom.used)
      printf("Selected index was too big!/n");

     if (selectedIndex % 2 != 0)
       selectedIndex--;

    int latitudeIndex = pointsToPickFrom.array[selectedIndex];
    int longitudeIndex = pointsToPickFrom.array[selectedIndex+1];
    double actualLatitude = minLatitude + latitudeIndex*degreesperindex;
    double actualLongitude = minLongitude + longitudeIndex*degreesperindex;


    fprintf( output, "%f %f\n", actualLongitude, actualLatitude);
  }
  fclose(output);


  printf("number of accumulated points: %d\n", (int)pointsToPickFrom.used/2);
  printf("grid width: %d grid height: %d\n", xDimension, yDimension);
  printf("Last index of default points: %d\n", xDimension*yDimension*2);
  printf("Number of non-default points: %ld\n", pointsToPickFrom.used/2 - xDimension*yDimension);
}
Ejemplo n.º 27
0
int theParsingMonster(int *count, char **arr, int bFlag) {

	if (*count == 1 && bFlag == 1) {
		if (DEBUG) printf("At least supply some args ...\n"); //!REMOVE!
		error(bFlag);
		return 0;
	}

	int temp = 1;
	int currentBlock;
	
	if (bFlag == 1) currentBlock = 1;
	 	else currentBlock = 0;
	 	
	int state = 0;
	int currentBlockPos = 0;
	int commandSniffer = -1;
	
	Array Employees;
	Array Guests;
	initArray(&Employees, 10);
	initArray(&Guests, 10);
	
	
/* The final element of one argv block is 0 (termination symbol)
   The final block of argc is 0 as well (termination block) */
   
 /* Vector Map will link i with vectorMap[i]:
 	 i:
 	 0: T
 	 1: K
 	 2: E
 	 3: G
 	 4: A
 	 5: L
 	 6: R
 	 7: B
 	 8: log.name
 	 
 	 vectorMap[i]:
 	 0: not set
 	 other value j: the position j on the argv array */
   
   int vectorMap[9];
   int iter = 0;
   while (iter<9) {
   	vectorMap[iter]=0;  
   	++iter;
   }
   
	
	while (temp <= *count) 
	{
		//if (DEBUG) debugVectorMap(vectorMap, arr);
		//if (DEBUG)	printf("arr[currentBlock][currentBlockPos] is %d\n", arr[currentBlock][currentBlockPos]);
		switch(state)
		{
			case 0 :
			//   if (DEBUG)	printf("Entering State 0\n");
				if (arr[currentBlock][currentBlockPos] != '-') {
				    if (DEBUG) printf("A symbol '-' expected!\n"); //!REMOVE!
				    error(bFlag);
				    freeArray(&Employees);
				    freeArray(&Guests); 
				    return 0;
				    }	 
				 
				state=1;				
				
				//printf("%d\n", *count);
				//printf("%d\n", temp);
				
				++currentBlockPos;
				--temp;
				break;
				
			case 1 :
			 //  if (DEBUG) printf("Entering State 1\n");
				if (arr[currentBlock][currentBlockPos] == 0) {
					if (DEBUG) printf("Missing command after '-' !\n"); //!REMOVE!
				   error(bFlag);
				   freeArray(&Employees);
				   freeArray(&Guests); 
				   return 0;
				}
				
				if (arr[currentBlock][currentBlockPos+1] != 0) {
					if (DEBUG) printf("Two symboled command! Maybe space missed?\n"); //!REMOVE!
				   error(bFlag);
				   freeArray(&Employees);
				   freeArray(&Guests);  
				   return 0;
				}
				
				if (currentBlock + 1 == *count) {
					if (DEBUG) printf("Too less arguments, bye!\n"); //!REMOVE!
				   error(bFlag);
				   freeArray(&Employees);
				   freeArray(&Guests); 
				   return 0;
				}
				
			   switch(arr[currentBlock][currentBlockPos]) 
			   {
			   	
			   	case 'T' : 
			   	   commandSniffer=0;
			   		break;
			   	case 'K' :
			   		commandSniffer=1;
			   		break;
			   	case 'S' :
			   		commandSniffer=2;
			   		break;
			   	case 'R' :
			   	   commandSniffer=3;
			   		break;
			   	case 'I' :	
			   		commandSniffer=4;
			   		break;
			   	case 'E' :
			   	   commandSniffer=6;
			   	   insertArray(&Employees, currentBlock+1);
			   		break;
			   	case 'G' :
			   		commandSniffer=7;
			   		insertArray(&Guests, currentBlock+1);		 
			   		break;			   	
			   	default:
			   		if (DEBUG) printf("Unknown Command!\n"); //!REMOVE!
						error(bFlag);
						freeArray(&Employees);
				      freeArray(&Guests); 
						return 0;
			   }			   
			   				   	   
			  // if (conflictCheck(commandSniffer, vectorMap, bFlag) == 0) return 0;
			   
			   if ((commandSniffer == 0)  || (commandSniffer == 2) || (commandSniffer == 3) || 
			       (commandSniffer == 4))
			   {
			   	vectorMap[commandSniffer] = -1;
			   	state = 3;
			   }
			   else
			   {
			   	vectorMap[commandSniffer] = currentBlock+1;
			   	if ((commandSniffer == 6) || (commandSniffer == 7)) 
			   		vectorMap[commandSniffer] = -1;
			   	state = 2;
			   	//if (commandSniffer == 7) state = 5;
			   }
			   	
			   ++currentBlock;
			   currentBlockPos = 0;			   
			   break;
			   
			case 2 : 
				//if (DEBUG) printf("Entering State 2\n");
				if (currentBlock + 1 == *count) {
				  // if (DEBUG) debugVectorMap(vectorMap, arr);
				   //if (DEBUG)	printf("argv[9] %s\n", arr[9]);
					if (DEBUG) printf("Too less arguments (maybe file name is missing?), bye!\n"); //!REMOVE!
				   error(bFlag);
				   freeArray(&Employees);
				   freeArray(&Guests); 
				   return 0;
				}
				
				++currentBlock;
				state = 3;
				break;
			
			case 3 :
			 //  if (DEBUG) printf("Entering State 3\n");
		//		printf("%c\n", arr[currentBlock][currentBlockPos]);
				if (arr[currentBlock][currentBlockPos] == '-') 						
					state=0;
				else 
					state=4;
					
				--temp;
				break;
				
			case 4:
			//   if (DEBUG) printf("Entering State 4\n");
				if (currentBlock + 1 != *count) {
					if (DEBUG) printf("Arguments after the file? Try again ..\n"); //!REMOVE!
				   error(bFlag);
				   freeArray(&Employees);
				   freeArray(&Guests); 
				   return 0;
				}
				
				vectorMap[5] = currentBlock;
				break;
			
		/*	case 5: //NO NEEDED ANYMORE! DELETE PENDING!
			//   if (DEBUG) printf("Entering State 5\n");
						
			   if (currentBlock+1 != *count) {
					if (DEBUG) printf("Arguments after the -B batch file? Try again ..\n"); //!REMOVE!
				   error(bFlag);
				   freeArray(&Employees);
				   freeArray(&Guests); 
				   return 0;
				}
				break;	*/
				
			default :
				if (DEBUG) printf("Erroneus State ...\n"); //!REMOVE!
			   error(bFlag);
			   freeArray(&Employees);
				freeArray(&Guests); 
			   return 0;
		}
		
		++temp;
	}
		
	// if (DEBUG) debugVectorMap(vectorMap, arr);
	
	// Some debug functions (to be REMOVED)
	
	/*	int temp1 = 0;
		for (temp1; temp1 < Employees.used; ++temp1)
			printf("Employee number %d: %s\n", temp1+1, arr[Employees.array[temp1]]);
		temp1 = 0;
		for (temp1; temp1 < Guests.used; ++temp1)
			printf("Guest number %d: %s\n", temp1+1, arr[Guests.array[temp1]]); */
			
	// End of debug functions
	
	if (logicSanitation(vectorMap, arr, bFlag) == 0) {
		freeArray(&Employees);
		freeArray(&Guests); 
		return 0;	
	}
	
	if (finalSanitation(vectorMap, arr, bFlag, &Employees, &Guests) == 0) {
		freeArray(&Employees);
		freeArray(&Guests); 
		return 0;
	}
	//if (DEBUG) debugVectorMap(vectorMap, arr);
	
	//Now some case dividing calls (depends from the flag triggered)
	
	if (vectorMap[2] == -1) {
		freeArray(&Employees);
		freeArray(&Guests); 
		passToCoreS(vectorMap, arr, bFlag);      // launch the program with option -S
		}
	else 
		if (vectorMap[0] == -1) {
			passToCoreT(vectorMap, arr, &Employees, &Guests, bFlag);   // launch the program with option -T
		}
	   else
	   	if (vectorMap[3] == -1) {
	   		passToCoreR(vectorMap, arr, &Employees, &Guests, bFlag);  // launch the program with option -R
	   	}
	   	else
	   		passToCoreI(vectorMap, arr, &Employees, &Guests, bFlag);  //launch the program with option -I

	freeArray(&Employees);
	freeArray(&Guests); 		
	return 1;
	
}