int count_nodes(item* root){
    if(!root)
        return 0;
    if(!root->left && !root->right)
        return 1;
    return 1 + count_nodes(root->left) + count_nodes(root->right);
}
Пример #2
0
unsigned int redblacktree::count_nodes(const rbtnode *start)const{
  //Rekurencyjne zliczanie ilosci wezlow
  unsigned int counter = 0;

  if(start!=this->getsentinel()){
    counter = 1+ count_nodes(start->getleft()) + count_nodes(start->getright());
  }

  return counter;
}
Пример #3
0
void count_nodes(TreeNode *X, int *counter){

	if(X == NULL){
		return;
	}
	count_nodes(X->right_sibling, counter);
	//printf("%d ", X->item);
	(*counter) ++;
	count_nodes(X->first_child, counter);

}
Пример #4
0
static size_t
count_nodes(struct mtree_trie_node *u)
{
    size_t count;

    count = 0;
    if (u->left != NULL && u->left->bit > u->bit)
        count += count_nodes(u->left);
    if (u->right != NULL && u->right->bit > u->bit)
        count += count_nodes(u->right);
    return (count + 1);
}
Пример #5
0
void count_nodes_local(){
   uint16_t local_node_count=0;
   node_ptr start;
   start=get_root();
   local_node_count=count_nodes(start);
   printf("number of keys: %d\n",local_node_count);
}
int imbalanced_p(item* root){
    /*
     * If the tree is left side heavy, this returns -1
     * If the tree is right side heavy, this return 1
     * If balanced, returns 0
     */
    if(!root)
        return 0;
    int left  = count_nodes(root->left);
    int right = count_nodes(root->right);
    if(left > (right+1))
        return -1;
    if(right > (left+1))
        return 1;
    return 0;
}
Пример #7
0
/*
 * Count number of items in the tree.
 */
size_t
mtree_trie_count(struct mtree_trie *trie)
{

    assert(trie != NULL);

    return (trie->top->left == trie->top ? 0 : count_nodes(trie->top->left));
}
Пример #8
0
void get_avg_local(){
   uint16_t total;
   uint16_t count;
   uint16_t avg;
   total=get_total(get_root());
   count=count_nodes(get_root());
   avg=total/count;
   printf("the average is : %d\n",avg);
}
Пример #9
0
int tree::count_nodes(node* n)
{
	for (int i = 0; i < n->childs.size(); ++i)
	{
		++node_num;
		count_nodes(n->childs[i]);
	}
	return 1;
}
Пример #10
0
/*=================================================
 * count_nodes -- count descendent nodes
 *===============================================*/
static void
count_nodes (NODE node, INT gen, INT maxgen, INT * count)
{
	(*count)++;

	if (gen < maxgen) {
		NODE child;
		for (child = nchild(node); child; child = nsibling(child)) {
			count_nodes(child, gen+1, maxgen, count);
		}
	}
}
Пример #11
0
/*=========================================================
 * pedigree_draw_gedcom -- print out gedcom node tree
 * Created: 2001/01/27, Perry Rapp
 *=======================================================*/
void
pedigree_draw_gedcom (RECORD rec, INT gdvw, CANVASDATA canvas, BOOLEAN reuse)
{
	INT count=0, gen=0, row=canvas->rect->top;
	INT indent = get_indent();
	if (gdvw == GDVW_TEXT) {
		draw_gedcom_text(rec, canvas, reuse, indent);
		return;
	}
	count_nodes(nztop(rec), gen, Gens, &count);
	set_scroll_max(canvas, count);
	check_scroll_max(canvas);
	/* preorder traversal */
	trav_pre_print_nod(nztop(rec), &row, gen, indent, canvas, gdvw);
}
Пример #12
0
void display_list(_node *head) {
    int value = 1;
    _node *temp = head;
    if(head == NULL) {
        printf("nothing to display");
        return;
    } else {
        printf("displaying the list\n");
        while(head) {
		printf("value of node value %d = %d\n",value,head->value);
		head = head->next;
		value++;
        }
	int count = count_nodes(temp);
	printf(" number of nodes = %d\n",count);
        return;
    }
}
Пример #13
0
struct network * check_repeated_nodes(struct network *newlist,struct network *oldlist)
{
	#ifdef DEBUG
		printf("Entering function: check_repeated_nodes\n");
	#endif
	struct network * oldnode;
	struct network * newnode;
	struct network * checknode;
	//1 _WE GET THE ADDRESS OF THE NODE WITH THE SAME MAC	
	oldnode = oldlist;
	
	while (oldnode!= NULL)
	{
	
		//WE SEARCH BY MAC, "checknode" 
		checknode = search_mac(newlist,oldnode->info->mac);
		
		//IN CASE WE CAN'T FIND A REPEATED NODE => INSERT
		if(checknode==NULL)
		{
			newnode = create_node(oldnode->info, count_nodes(newlist) + 1);		
			newlist = insert_node(newnode,newlist);
			newlist = sort(newlist);
			//CHANGES WERE MADE
			data_changed = 1;
		}
		else
		{
			#ifdef DEBUG
			printf("Repeated Node, won't be inserted\n");
			#endif
		}
		oldnode = oldnode->next;
	}
	
	//4 _ RETURN THE LIST WITH THE NODES INSERTED
	#ifdef DEBUG
		printf("Exiting function: check_repeated_nodes\n");
	#endif	

	return newlist;
}
Пример #14
0
str_grid_node_data_t* str_grid_node_data_with_buffer(str_grid_t* grid, 
                                                     int num_components, 
                                                     void* buffer)
{
  ASSERT(num_components > 0);

  // Allocate storage.
  int num_patches = str_grid_num_patches(grid);
  size_t patches_size = sizeof(str_grid_patch_t*) * num_patches;
  size_t node_data_size = sizeof(str_grid_node_data_t) + patches_size;
  str_grid_node_data_t* node_data = polymec_malloc(node_data_size);
  node_data->grid = grid;
  node_data->nc = num_components;

  str_grid_get_extents(grid, &node_data->nx, &node_data->ny, &node_data->nz);
  node_data->patches = int_ptr_unordered_map_new();
  node_data->patch_offsets = polymec_malloc(sizeof(int) * (num_patches+1));
  node_data->buffer = NULL;

  // Now populate the patches (with NULL buffers).
  int px, py, pz;
  str_grid_get_patch_size(grid, &px, &py, &pz);
  node_data->patch_lx = 1.0 / node_data->nx;
  node_data->patch_ly = 1.0 / node_data->ny;
  node_data->patch_lz = 1.0 / node_data->nz;
  int pos = 0, i, j, k, l = 0;
  while (str_grid_next_patch(grid, &pos, &i, &j, &k))
  {
    int index = patch_index(node_data, i, j, k);
    int_ptr_unordered_map_insert_with_v_dtor(node_data->patches, index, 
      str_grid_patch_with_buffer(px+1, py+1, pz+1, num_components, 0, NULL),
      DTOR(str_grid_patch_free));
    ++l;
  }

  count_nodes(node_data);

  // Set the buffer.
  str_grid_node_data_set_buffer(node_data, buffer, false);

  return node_data;
}
Пример #15
0
/*
 * return a relative path from @from to @to
 * result should be freed
 */
char *
relative_path_to(char *from, char *to, int *err)
{
	int from_nodes, common;
	char *to_absolute, *from_absolute;
	char *up, *common_target_path, *relative_path;

	*err          = 0;
	up            = NULL;
	to_absolute   = NULL;
	from_absolute = NULL;
	relative_path = NULL;

	if (strnlen(to, MAX_NAME_LEN)   == MAX_NAME_LEN ||
	    strnlen(from, MAX_NAME_LEN) == MAX_NAME_LEN) {
		EPRINTF("invalid input; max path length is %d\n",
			MAX_NAME_LEN);
		*err = -ENAMETOOLONG;
		return NULL;
	}

	to_absolute = realpath(to, NULL);
	if (!to_absolute) {
		EPRINTF("failed to get absolute path of %s\n", to);
		*err = -errno;
		goto out;
	}

	from_absolute = realpath(from, NULL);
	if (!from_absolute) {
		EPRINTF("failed to get absolute path of %s\n", from);
		*err = -errno;
		goto out;
	}

	if (strnlen(to_absolute, MAX_NAME_LEN)   == MAX_NAME_LEN ||
	    strnlen(from_absolute, MAX_NAME_LEN) == MAX_NAME_LEN) {
		EPRINTF("invalid input; max path length is %d\n",
			MAX_NAME_LEN);
		*err = -ENAMETOOLONG;
		goto out;
	}

	/* count nodes in source path */
	from_nodes = count_nodes(from_absolute);

	/* count nodes in common */
	common = count_common_nodes(to_absolute + 1, from_absolute + 1);
	if (common < 0) {
		EPRINTF("failed to count common nodes of %s and %s: %d\n",
			to_absolute, from_absolute, common);
		*err = common;
		goto out;
	}

	/* move up to common node */
	up = up_nodes(from_nodes - common - 1);
	if (!up) {
		EPRINTF("failed to allocate relative path for %s: %d\n",
			from_absolute, -ENOMEM);
		*err = -ENOMEM;
		goto out;
	}

	/* get path from common node to target */
	common_target_path = node_offset(to_absolute, common + 1);
	if (!common_target_path) {
		EPRINTF("failed to find common target path to %s: %d\n",
			to_absolute, -EINVAL);
		*err = -EINVAL;
		goto out;
	}

	/* get relative path */
	if (asprintf(&relative_path, "%s%s", up, common_target_path) == -1) {
		EPRINTF("failed to construct final path %s%s: %d\n",
			up, common_target_path, -ENOMEM);
		relative_path = NULL;
		*err = -ENOMEM;
		goto out;
	}

out:
	sfree(up);
	sfree(to_absolute);
	sfree(from_absolute);

	return relative_path;
}
Пример #16
0
int dt_node_count(decision_tree *dt) {
    return count_nodes(dt->root);
}
Пример #17
0
int main(void){
	int counts[31];
	for(int i = 0; i < 31; i++){
	  counts[i] = 0;
	}
	int len;
	int month;
	int day;
	int year;
	char filename[STR_LEN]; 
	char analysis[5];
	LIST *data = list_create();
	printf("Please enter file name containing data to analyze: \n");
	scanf("%s", filename);
	FILE *data_file = fopen(filename, "r");
	if(data_file == NULL){
		fprintf(stderr, "There was an error opening the file.  Make sure it exists.\n");
		exit(0);
	}
	
	printf("How would you like the data to be analyzed?\n Enter \"day\" to analyze the rides per hour in a given day.\n Enter \"month\" to analyze the rides per day in a given month.\n Enter \"year\" to analyze the rides per month in a given year.\n");
	scanf("%s", analysis);
        if(!(strcmp(analysis, "month")==0)){
	    if(!(strcmp(analysis, "day")==0)){
	        if(!(strcmp(analysis, "year")==0)){
		  fprintf(stderr, "Invalid Entry\n");
		  exit(0);
		}
            }
	}
	if(!strcmp(analysis, "day")){
	len = 24;
	printf("Please enter the month (i.e. 02 for February), day (i.e. 15), and year (i.e. 2013) below\n");
	printf("Please enter the month:\n");
	scanf("%i", &month);
	if(month < 0 || month > 12){
	  fprintf(stderr, "Invalid Entry\n");
	  exit(0);
	}
	printf("Please enter the day:\n");
	scanf("%i", &day);
	if(day < 0 || day > 31){
	  fprintf(stderr, "Invalid Entry\n");
	  exit(0);
	}
	printf("Please enter the year:\n");
	scanf("%i", &year);
	if(year < 0 || year > 2099){
	  fprintf(stderr, "Invalid Entry\n");
	  exit(0);
	}
	read_by_day(data_file, data, month, day, year);
  	count_nodes(data, counts, len);
	make_hist(counts, len, month, day, year);
}
  
  if(!strcmp(analysis, "month")){
	printf("Please enter the month (i.e. 02 for February), day (i.e. 15), and year (i.e. 2013) below\n");
	printf("Please enter the month:\n");
	scanf("%i", &month);
	if(month < 0 || month > 12){
	  fprintf(stderr, "Invalid Entry\n");
	  exit(0);
	}
	printf("Please enter the year:\n");
	scanf("%i", &year);
	if(year < 0 || year > 2099){
	  fprintf(stderr, "Invalid Entry\n");
	  exit(0);
	}
	//setting value for months with 31 days
	if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
		len = 31;
	}
	//setting value for months with 30 days
	else if (month == 4 || month == 6 || month == 9 || month == 11){
		len = 30;
	}
	//setting value for February in a leap year
	else if (month == 2 && year%4 == 0){
		len = 29;
	}
	//setting value for non-leap year February
	else{
		len = 28;
	}
	read_by_month(data_file, data, month, year);
  	count_nodes(data, counts, len);
	make_hist(counts, len, month, day, year);
}
  
  if(!strcmp(analysis, "year")){
	len = 12;
	printf("Please enter the year:\n");
	scanf("%i", &year);
	if(year < 0 || year > 2099){
	  fprintf(stderr, "Invalid Entry\n");
	  exit(0);
	}
	read_by_year(data_file, data, year);
	count_nodes(data, counts, len);
	make_hist(counts, len, month, day, year);
  }
  list_free(data);
  return 0;
}
Пример #18
0
int main(int argc, char *argv[]){

	char c;
	int n=0, m=0;

	init();

	FILE *fp=NULL;
	fp=fopen(argv[1],"r");			//Anoigma tou arxeiou
	if(fp==NULL){                           //Elegxos an to arxeio anoikse kanonika, alliws termatismos..
            printf("\nProblem opening file. Program terminated...\n");
            return -1;
        }		

//Diavasma xaraktira kai antistoixi leitourgia analoga me auton (Provlepsi gia grammi sxoliwn kai gia telos arxeiou)
	c=fgetc(fp);
	do{
		if(c=='V' || c=='v'){
			m++;
			creatVoltList(fp);
		}
		else if(c=='I' || c=='i'){
			creatAmberList(fp);
		}
		else if(c=='R' || c=='r'){
			creatResistanceList(fp);
		}
		else if(c=='C' || c=='c'){
			creatCapacitorList(fp);
		}
		else if(c=='L' || c=='l'){
                        m++;
			creatInductorList(fp);
		}
		else if(c=='D' || c=='d'){
			creatDiodeList(fp);
		}
		else if(c=='M' || c=='m'){
			creatMOSList(fp);
		}
		else if(c=='B' || c=='b'){
			creatBJTList(fp);
		}
		else if(c=='%'){ 
			c=fgetc(fp);
			while(c!='\n'&&(c!=EOF)){c=fgetc(fp);}/*MOVE TO NEXT LINE*/
		}
                else if(c=='.'){
			analysis(fp);
		}
		else{
			
		}
		if(c!=EOF){c=fgetc(fp);}
	}while(!feof(fp));

	fclose(fp);

        if(ground==0)
        {
	     printf("No ground node! Program terminated!");
             return -1;
        }
        else
        { 
             printVoltList(rootV);
             printAmperList(rootI);
             printResistanceList(rootR); 
             printCapacitorList(rootC);
             printInductorList(rootL);
             printDiodeList(rootD);
             printMosList(rootM);
             printBjttList(rootB);
       }
 
	n=count_nodes();
	printf("\n m=%d , n=%d \n\n", m, n);

	int size=0;
 
	size = (n-1)+m;

    if(sparse_option == 0){     
	gsl_matrix* pinakasA = gsl_matrix_calloc(size,size);
	gsl_vector* pinakasB = gsl_vector_calloc(size);
	
        fill_matrix_A(pinakasA, pinakasB, n);
	fill_matrix_B(pinakasB);
       
   	printf(" O pinakas A einai o: \n");
        print2DMatrix(pinakasA, size); 		
    	printf("\n O pinakas B einai o: \n");
    	print1DMatrix(pinakasB,size);
 
    	printf("\n");
        
        if(use_lu==1){
	    if(found_iter==1){
                call_bi_cg(pinakasA, pinakasB, size);
            } 
            else{
                luDecomp(pinakasA, pinakasB, size);
	    }
        }
        else if (use_cholesky==1){
            if (found_iter==1){
                 call_cg(pinakasA, pinakasB, size);
            }
            else{
                choleskyDecomp(pinakasA, pinakasB, size);
            }
        }
    }
    else {
	int i;

	cs* pinakasA_sparse = cs_spalloc(size,size,4*sparse_elements,1,1);

	double* pinakasB_sparse = (double *)calloc(size,sizeof(double));
	double* pinakasX_sparse = (double *)calloc(size,sizeof(double));	
	
	fill_sparse_matrix_A(pinakasA_sparse, pinakasB_sparse,n);
	cs* pinakasC_sparse = cs_compress(pinakasA_sparse);
	cs_spfree(pinakasA_sparse);
	cs_dupl(pinakasC_sparse);

 	if(use_lu==1){
	    if(found_iter==1){
                call_bi_cg_sparse(pinakasC_sparse, pinakasB_sparse, pinakasX_sparse, size);
            } 
            else{
                luDecomp_sparse(pinakasC_sparse, pinakasB_sparse, pinakasX_sparse, size);
	    }
        }
        else if (use_cholesky==1){
            if (found_iter==1){
                 call_cg_sparse(pinakasC_sparse, pinakasB_sparse, pinakasX_sparse, size);
            }
            else{
                choleskyDecomp_sparse(pinakasC_sparse, pinakasB_sparse, pinakasX_sparse, size);
            }
        }   
    }
    return 0;
}
Пример #19
0
int main()
{
	t_node *head;
	t_node *n1;
	t_node *n2;
	int *i1;
	int *i2;
	int *i3;
	int i;
	int j;
	int k;
	char *c1;
	char *c2;
	char *c3;
	char a;
	char b;
	char c;

	head = (t_node*)xmalloc(10*sizeof(t_node));
	
	/*new_node*/
	n1 = new_node("one\n", NULL);
	my_str(n1->elem);/*prints one*/
	n1->elem = NULL;
	free(n1);
	n1 = new_node(NULL, NULL);
	if(!n1->elem)
		my_str("create NULL node ok\n");
	else
		my_str("create NULL node FAIL!\n");
	free(n1);
	n1 = new_node("a", NULL);
	n2 = new_node("b", n1);
	my_str(n2->elem);
	my_str((n2->next)->elem);/*prints ba*/
	my_char('\n');
	my_str("---------------------------------------------------------------------\n");

	/*add_node*/
	add_node(n1, &head);
	my_str((*head).elem);/*prints a*/
	my_char('\n');
	add_node(n2, &head);
	my_str((*head).elem);/*prints b*/
	my_char('\n');
	add_node(NULL, &head);
	if(strcmp((*head).elem, n2->elem) == 0)
		my_str("add NULL ok\n");
	else
		my_str("add NULL FAIL!\n");
	add_node(new_node(NULL, NULL), &head);
	if(strcmp((*head).elem, n2->elem) == 0)
		my_str("add NULL node ok\n");
	else
		my_str("add NULL node FAIL!\n");
	add_node(new_node("something", NULL), NULL);/*if this line doesn't segfault then we're good!*/
	my_str("---------------------------------------------------------------------\n");

	/*traversals*/
	empty_list(&head);
	i = 3;
	i1 = &i;
	add_node(new_node(i1, NULL), &head);
	j = 2;
	i2 = &j;
	add_node(new_node(i2, NULL), &head);
	k = 1;
	i3 = &k;
	add_node(new_node(i3, NULL), &head);
	traverse_int(head);/*prints 1 2 3 */
	my_char('\n');
	head->next->elem = NULL;
	traverse_int(head);/*prints 1 NULL 3*/
	my_char('\n');
	traverse_int(NULL);/*prints The list is empty!*/

	empty_list(&head);
	c = 'c';
	c1 = &c;
	add_node(new_node(c1, NULL), &head);
	b = 'b';
	c2 = &b;
	add_node(new_node(c2, NULL), &head);
	a = 'a';
	c3 = &a;
	add_node(new_node(c3, NULL), &head);
	traverse_char(head);/*prints a b c */
	my_char('\n');
	head->elem = NULL;
	traverse_char(head);/*prints NULL b c*/
	my_char('\n');
	traverse_char(NULL);/*prints The list is empty!*/

	empty_list(&head);
	add_node(new_node("third", NULL), &head);
	add_node(new_node("second", NULL), &head);
	add_node(new_node("first", NULL), &head);
	traverse_string(head);/*prints first second third */
	my_char('\n');
	head->next->next->elem = NULL;
	traverse_string(head);/*prints first second NULL*/
	my_char('\n');
	traverse_string(NULL);/*prints The list is empty!*/
	empty_list(&head);
	my_str("---------------------------------------------------------------------\n");

	/*add_elem*/
	add_elem("a", &head);
	add_elem("b", &head);
	add_elem("c", &head);
	my_str(head->elem);/*prints c*/
	my_char('\n');
	add_elem(NULL, &head);
	if(strcmp(head->elem, "c") == 0)
		my_str("add NULL elem ok\n");
	else
		my_str("add NULL elem FAIL!\n");	
	my_str("---------------------------------------------------------------------\n");
	
	/*append*/
	append(new_node("z", NULL), &head);
	traverse_string(head);/*prints c b a z*/
	my_char('\n');
	append(NULL, &head);
	traverse_string(head);/*prints c b a z*/
	my_char('\n');
	append(new_node("stuff", NULL), NULL);/*if this line doesn't segfault then we're good!*/
	my_str("---------------------------------------------------------------------\n");

	/*add_node_at*/
	add_node_at(new_node("d", NULL), &head, 0);
	traverse_string(head);/*prints d c b a z*/
	my_char('\n');
	add_node_at(new_node("y", NULL), &head, 42);
	traverse_string(head);/*prints d c b a z y*/
	my_char('\n');
	add_node_at(new_node("0", NULL), &head, 4);
	traverse_string(head);/*prints d c b a 0 z y*/
	my_char('\n');
	add_node_at(NULL, &head, 2);
	traverse_string(head);/*prints d c b a 0 z y*/
	my_char('\n');
	add_node_at(new_node(NULL, NULL), &head, 1);
	traverse_string(head);/*prints d c b a 0 z y*/
	my_char('\n');
	add_node_at(new_node("something", NULL), NULL, 7);/*if this line doesn't segfault then we're good!*/
	my_str("---------------------------------------------------------------------\n");

	/*remove_node*/
	my_str(remove_node(&head));/*prints d*/
	my_str(": ");
	traverse_string(head);
	my_char('\n');
	if(!remove_node(NULL))
		my_str("remove node from NULL ok\n");
	else
		my_str("remove node from NULL FAIL!\n");
	my_str("---------------------------------------------------------------------\n");

	/*remove_node_at*/
	my_str(remove_node_at(&head, 0));/*prints c*/
	my_str(": ");
	traverse_string(head);
	my_char('\n');
	my_str(remove_node_at(&head, 42));/*prints y*/
	my_str(": ");
	traverse_string(head);
	my_char('\n');
	my_str(remove_node_at(&head, 2));/*prints 0*/
	my_str(": ");
	traverse_string(head);
	my_char('\n');
	if(!remove_node_at(NULL, 100))
		my_str("remove node from NULL ok\n");
	else
		my_str("remove node from NULL FAIL!\n");
	my_str("---------------------------------------------------------------------\n");

	/*remove_last*/
	my_str(remove_last(&head));/*prints z*/
	my_str(": ");
	traverse_string(head);
	my_char('\n');
	if(!remove_last(NULL))
		my_str("remove last from NULL ok\n");
	else
		my_str("remove last from NULL FAIL!\n");
	my_str("---------------------------------------------------------------------\n");

	/*count_nodes*/
	my_int(count_nodes(head));/*prints 2*/
	my_char('\n');
	my_int(count_nodes(NULL));/*prints 0*/
	my_char('\n');
	my_str("---------------------------------------------------------------------\n");

	/*node_at*/
	my_str((node_at(head, 1))->elem);/*prints a*/
	my_char('\n');
	my_str((node_at(head, 0))->elem);/*prints b*/
	my_char('\n');
	my_str((node_at(head, 42))->elem);/*prints a*/
	my_char('\n');
	if(!node_at(NULL, 12))
		my_str("node at with NULL ok\n");
	else
		my_str("node at with NULL FAIL!\n");
	my_str("---------------------------------------------------------------------\n");

	/*elem_at*/
	my_str(elem_at(head, 0));/*prints b*/
	my_char('\n');
	my_str(elem_at(head, 1));/*prints a*/
	my_char('\n');
	my_str(elem_at(head, 42));/*prints a*/
	my_char('\n');
	if(!elem_at(NULL, 3))
		my_str("elem at with NULL ok\n");
	else
		my_str("elem at with NULL FAIL!\n");
	my_str("---------------------------------------------------------------------\n");

	/*empty_list*/
	my_int(count_nodes(head));/*prints 2*/
	my_char('\n');
	empty_list(&head);
	my_int(count_nodes(head));/*prints 0*/
	my_char('\n');
	empty_list(NULL);/*if this doesn't segfault then we're good!*/
	my_str("---------------------------------------------------------------------\n");
	
	free(head);

	return 0;
}
Пример #20
0
int main(int argc, char *argv[]){

	struct timeval  start_time, end_time; /* structs for timer     */
	struct timezone zone;
	long int sec = 0, usec = 0; /* sec & microsec for the timer    */
	
	long int time_total_sec = 0;
     double time_total_msec = 0;
     long int time_total_usec = 0;

	int numTrans, pid, numItems, item, count, i , j;
	FILE *f_input, *f_utility, *f_output;
	int sizeDB;
	
	double minshare;
	int MV = 0;
	int ML = 0;
	int tempML = 0;
	
	if(argc != 7){
		fprintf(stderr, "Usage: %s transactionDB utilityTable outputFile min_util MAXITEMS MAXCANDIDATES\n", argv[0]);	
		exit(0);
	}
	
	f_input = fopen(argv[1], "r");
	f_utility = fopen(argv[2], "r");
	f_output = fopen(argv[3], "w");
	minshare = atof(argv[4]);
	MAXITEMS = atoi(argv[5]);
	MAXITEMSETS = atoi(argv[6]);
	
	if((f_input == NULL) || (f_utility == NULL) || (f_output == NULL)){
	    fprintf( stdout, "ERROR[%s]: Can't open %s or %s or %s\n", argv[0], argv[1], argv[2], argv[3] );
	    fprintf( stderr, "ERROR[%s]: Can't open %s or %s or %s\n", argv[0], argv[1], argv[2], argv[3] );
	    fprintf( stderr, "ERROR[%s]: Can't open %s or %s or %s\n", argv[0], argv[1], argv[2], argv[3] );
    		exit( 0 );
	}
	
	TreeNode *rootCk;
	rootCk = create_new_node(ROOT);

	TreeNode *rootRc;
	rootRc = create_new_node(ROOT);
	
	TreeNode *rootF;	//the tree for frequent itemsets
	rootF = create_new_node(ROOT);
	
	TreeNode *setRc[MAXITEMSETS + 1];
	TreeNode *setCk[MAXITEMSETS + 1];
	TreeNode *setF[MAXITEMSETS + 1];
	
	int sizeRc = 0;
	int sizeCk = 0;
	int sizeF = 0;
	
	double utility[MAXITEMS + 1];
	double TutilItem[MAXITEMS + 1];
	int items[MAXITEMS + 1];
	double lmv[MAXITEMS + 1];

	double TutilDB = 0;
	float cost;
	
	for(i = 1; i <= MAXITEMS; i ++){
		utility[i] = 0;
		TutilItem[i] = 0;
		items[i] = 0;
		lmv[i] = 0;
	}

	printf("===== %s %s %s %f =====\n\n", argv[0], argv[1], argv[2], minshare);
	
     //record the time for the first db scan
     if(gettimeofday(&start_time, &zone) == -1){
       fprintf(stderr, "gettimeofday error\n");
     }
    	
    	fscanf(f_utility, "%d ", &numItems); 
	for(i = 1; i <= numItems; i ++){
	
		fscanf(f_utility, "%d %f ", &item, &cost);
		utility[item] = cost;
	}
	
	fscanf(f_input, "%d ", &numTrans);
	double transUtil = 0;
	//read the whole db once to get candidate 1-itemsets
	for(i = 1; i <= numTrans; i ++){
	
		fscanf(f_input, "%d ", &pid);
		fscanf(f_input, "%d ", &numItems);
		//printf("\n%d %d ", pid, numItems);
		for(j = 1; j <= numItems; j ++){
			fscanf(f_input, "%d %d ", &item, &count);
			//printf("item %d count %d ", item, count);
			transUtil += count * utility[item];
			items[item] = 1;
			if(count > MV){
				MV = count;
			}
			tempML ++;

			//printf("\nitem: %d count: %d", item, count);
			lmv[item] += count;
		}
		for(j = 1; j <= MAXITEMS; j ++){
			if(items[j] == 1){
				TutilItem[j] += transUtil;
				items[j] = 0;
			}
		}
		if(tempML > ML){
			ML = tempML;
		}
		TutilDB += transUtil;
		transUtil = 0;
		tempML = 0;
	}
	sizeDB = numTrans;
	
	if(gettimeofday(&end_time, &zone) == 0){
      	if(end_time.tv_usec >= start_time.tv_usec){
      		sec  = end_time.tv_sec - start_time.tv_sec;
      		usec = end_time.tv_usec - start_time.tv_usec;
      	}else{
      		sec  = end_time.tv_sec - start_time.tv_sec - 1;
      		usec = end_time.tv_usec - start_time.tv_usec + 1000000;
      	}
      	time_total_sec += sec;
      	time_total_usec += usec;
      	
      	fprintf(stdout, "\n[FUM] Total runtime for first db scan is %ld sec. %.3f msec\n", sec, usec/1000.0);
      	f_output = fopen( argv[3], "a" );
      	fprintf(f_output, "\n[FUM] Total runtime for first db scan is %ld sec. %.3f msec\n", sec, usec/1000.0);
      	fclose( f_output );
      }
	
	if(DEBUG){
		for(i = 1; i <= MAXITEMS; i ++){
			printf("\nutil item (%d): %f", i, utility[i]);
		}
		printf("\n");
		for(i = 1; i <= MAXITEMS; i ++){
			printf("\nitem (%d) has Tutil: %f", i, TutilItem[i]);
		}
		printf("\n\nTutilDB: %f Min_Lutil: %f\n", TutilDB, MIN_LUTIL(TutilDB, minshare));
		printf("\nMV: %d ML: %d", MV, ML);
	}

	int isolated_itemsets[MAXITEMS + 1];
	int size = 0;
	
	//get candidate 1-itemsets
	for(i = 1; i <= MAXITEMS; i ++){
		if(utility[i] > 0){
			if(TutilItem[i] >= MIN_LUTIL(TutilDB, minshare)){

				Itemset I;
				init_itemset(&I);
				I.itemset[i] = 1;
				double lutil = (lmv[i] * utility[i]);
				insert(I.itemset, rootRc, 1, &sizeRc, i, setRc, lutil);
				free_itemset(&I);
			}
			else{
				isolated_itemsets[size] = i;
				size ++;
			}
		}
	}

	//int k_prime = 1; //needed for other version of critical function
	int c;
	for(c = 0; c < sizeRc; c ++){
		TreeNode *X = setRc[c];

		if(X->lutil >= MIN_LUTIL(TutilDB, minshare)){

			Itemset I;
			to_itemset(&I, X);
			insert(I.itemset, rootF, 1, &sizeF, 1, setF, X->lutil);
			free_itemset(&I);
		}
		//printf("\nCF: %f", CF(X->lutil, 1, MV, ML, k_prime));
		//if(CF(X->lutil, 1, MV, ML, k_prime) < MIN_LUTIL(TutilDB, minshare)){
		if(TutilItem[X->item] < MIN_LUTIL(TutilDB, minshare)){
			
			remove_itemset(X, setRc, c);
		}
	}
	adjust_set(setRc, &sizeRc);
	if(PRT_CNT){
		printf("\n\nIteration (%d)", 0);
		printf("\n|Ck| = %d", sizeCk);
		printf("\n|Rc| = %d", sizeRc);
		printf("\n|Fk| = %d", sizeF);
	}

	int k;
	int counterF = 0;
	boolean stop = false;
	int num_false_positives[MAXITEMSETS + 1];
	int sizeFP = 0;
	
	//record the time for mining
	if(gettimeofday(&start_time, &zone) == -1){
		fprintf(stderr, "gettimeofday error\n");
	}
	for(k = 1; sizeRc > 0 && stop == false; k ++){
	
		//apriori join + apriori prune
		generate(rootRc, setRc, sizeRc, setCk, &sizeCk, rootCk, k); 

		if(PRT_MEM){
			printf("\n\nIteration (%d)", k);
			int mem_counterCk = 0;
			count_nodes(rootCk, &mem_counterCk);
			printf("\nNode Count = [%d]", mem_counterCk);
			printf("\nNode Size = [%ld bytes]", sizeof(TreeNode));
			printf("\nMemory space required for candidate tree = %ld bytes", mem_counterCk * sizeof(TreeNode));
		}

		if(sizeCk > 0){

			double TransUtil;
			rewind(f_input);
			fscanf(f_input, "%d ", &numTrans);
			for(i = 1; i <= numTrans; i ++){

				fscanf(f_input, "%d ", &pid);
				fscanf(f_input, "%d ", &numItems);

				Transaction T;
				init_transaction(&T);
				for(j = 1; j <= numItems; j ++){

					fscanf(f_input, "%d %d ", &item, &count);
					if(is_isolated_item(item, isolated_itemsets, size) == false){
						T.itemset[item] += count;
						T.total_count += (count * utility[item]);
					}
				}
				TransUtil = T.total_count;
		
				for(j = 0; j < sizeCk; j ++){
					TreeNode *X = setCk[j];
					boolean in_transaction = true;
					double Lutil = 0;
					while(is_root(X) == false && in_transaction == true){ //first check if itemset in transaction
			
						if(T.itemset[X->item] == 0){
							in_transaction = false;
						}
						Lutil += (T.itemset[X->item] * utility[X->item]);
						X = X->parent;
					}
					if(in_transaction){
						TreeNode *last_node = setCk[j];
						last_node->lutil += Lutil;
						last_node->CF += TransUtil;
					}
				}
				free_transaction(&T);
			}
			if(PRT_CNT){
				printf("\n\nIteration (%d)", k);
				printf("\n|Ck| = %d", sizeCk);
			}
			if(PRT_FALSE_POS){
				num_false_positives[k] = sizeCk;
				sizeFP ++;
			}
			for(c = 0; c < sizeCk; c ++){
				TreeNode *X = setCk[c];
				//print_itemset(X);
				//printf(" lutil: %f minlutil: %f\n", X->lutil, MIN_LUTIL(TutilDB, minshare));
				if(X->lutil >= MIN_LUTIL(TutilDB, minshare)){

					counterF ++;
					Itemset I;
					to_itemset(&I, X);
					insert(I.itemset, rootF, 1, &sizeF, 1, setF, X->lutil);
					free_itemset(&I);
				}
				if(X->CF < MIN_LUTIL(TutilDB, minshare)){
				//if(CF(X->lutil, 1, MV, ML, k_prime) < MIN_LUTIL(TutilDB, minshare)){
					remove_itemset(X, setCk, c);
				}
			}
			adjust_set(setCk, &sizeCk);
			copy_tree(rootCk, setCk, &sizeCk, rootRc, setRc, &sizeRc);
			if(PRT_CNT){
				printf("\n|Rc| = %d", sizeRc);
				printf("\n|Fk| = %d", counterF);
			}
			if(PRT_FALSE_POS){
				num_false_positives[k] -= counterF;
				printf("\nFalse Positives Iteration (%d): %d", k, num_false_positives[k]);
			}
		}
		else{
			stop = true;
		}	
		counterF = 0;
	}
	if(gettimeofday(&end_time, &zone) == 0){
	 	if(end_time.tv_usec >= start_time.tv_usec){
	 		sec  = end_time.tv_sec - start_time.tv_sec;
	 		usec = end_time.tv_usec - start_time.tv_usec;
	 	}else{
	 		sec  = end_time.tv_sec - start_time.tv_sec - 1;
	 		usec = end_time.tv_usec - start_time.tv_usec + 1000000;
	 	}
      	time_total_sec += sec;
      	time_total_usec += usec;
      	
	 	fprintf(stdout, "\n[FUM] Total runtime for mining is %ld sec. %.3f msec\n", sec, usec/1000.0);
	 	f_output = fopen( argv[3], "a" );
	 	fprintf(f_output, "\n[FUM] Total runtime for mining is %ld sec. %.3f msec\n", sec, usec/1000.0);
	 	fclose( f_output );
 	}
	
	f_output = fopen(argv[3], "a");
	if(PRT_FALSE_POS){
		int total_FP = 0;
		for(k = 1; k <= sizeFP; k ++){
			total_FP += num_false_positives[k];
		}
		printf("\nTotal False Positives: %d", total_FP);
	}
	if(PRT_FP){
		printf("\n\nFound (%d) ShFrequent Itemsets:", sizeF);
		fprintf(f_output, "\n\nFound (%d) ShFrequent Itemsets:", sizeF);
		print_frequent_itemset(setF, sizeF, f_output);
	}
	if(PRT_MEM){
		int mem_counterF = 0;
		count_nodes(rootF, &mem_counterF);
		printf("\n\nNode Count = [%d]", mem_counterF);
		printf("\nNode Size = [%ld bytes]", sizeof(TreeNode));
		printf("\nMemory space required for frequent itemset tree = %ld bytes", mem_counterF * sizeof(TreeNode));
	}
	
	time_total_msec = time_total_usec / 1000.0;
  	if(time_total_msec >= 1000){
  		time_total_sec += floor(time_total_msec/1000);
  		time_total_msec = time_total_usec % 1000;
  	}
  	
  	//printf("\ntime sec: %ld time msec: %.3lf time usec: %ld", time_total_sec, time_total_msec, time_total_usec);

	fprintf(stdout, "\n\n[FUM] Total (aggregate) runtime is %ld sec. %.3lf msec\n", time_total_sec, time_total_msec);
	fprintf(f_output, "\n\n[FUM] Total (aggregate) runtime is %ld sec. %.3lf msec\n", time_total_sec, time_total_msec);
	
	free_tree(setRc, &sizeRc);
	free_tree(setCk, &sizeCk);
	free_tree(setF, &sizeF);
	fclose(f_input);
	fclose(f_output);
	fclose(f_utility);
	printf("\n\nProcessing Complete\n");
	return 0;
}
Пример #21
0
tree::tree(FILE* f)
{
	node_num = 0;
	Root = new node;
	if (!f) {printf("Err: can't read from file\n"); exit(1);}
	char c = fgetc(f);
	while (c != '>' && !feof(f)) c = fgetc(f);
	if (c == '>')
	{
		fscanf(f,"%d", &num);
	}
	else
	{
		return;
	}
	while (c != '(' && !feof(f)) {c = fgetc(f);}
	Root->childs.erase(Root->childs.begin(), Root->childs.end());
	if (!feof(f)) add_subtree(f, Root);
	else {printf("Last tree readed\n"); return;}
	c = fgetc(f);
	if (c == ';') 
	{
//		printf("SUCCESS; %lu\n", Root->childs.size());
	}
	else {printf("ERR: ; ?\n"), exit(1);}

	printf("OK\n");
	DeleteNullEdges(Root);
	SetClades(Root);
	FixClades(Root);
//	printf("OK1\n");

	if (Root->childs.size() == 2)
	{
		if (Root->childs[0]->edge > 0 && Root->childs[1]->edge > 0)
		{
			if (Root->childs[0]->childs.size() > 0)
			{
				for (int i = 0; i < Root->childs[0]->childs.size(); ++i)
				{
					Root->childs[0]->childs[i]->parent = Root;
					Root->childs.push_back(Root->childs[0]->childs[i]);
				}
				Root->childs.erase(Root->childs.begin());
			}
			else if (Root->childs[1]->childs.size() > 0)
			{
				node n = *Root->childs[1];
				Root->childs.erase(Root->childs.begin()+1);
				for (int i = 0; i < Root->childs[1]->childs.size(); ++i)
				{
					n.childs[i]->parent = Root;	
					Root->childs.push_back(n.childs[i]);					
				}
			}
		}
	}
	count_nodes(Root);
//	printf("Root childs size %lu\n", Root->childs.size());
	Tree2Newick("test");
//	int i;
//	for (i = 0; i < Root->childs.size(); ++i)
//	{
//		printf("%lu;\n", Root->childs[i]->clade.size());
//	}
}
Пример #22
0
void linkedlist_to_file(char *path,struct network *list){
	#ifdef DEBUG
	printf("Entering function: linkedlist_to_file\n");
	#endif

	/* check if the file is well opened*/
	if ((file = fopen(path, "w")) == NULL){
		printf("It's impossible to open the file\n");
		printf("Maybe the filename could be wrong. Check it!\n");
		#ifdef DEBUG
		printf("Exiting function: linkedlist_to_file\n\n");
		#endif
		return ;
	}
	/* auxiliary structure to work with*/
	network aux = list;

	/** NUMBER OF NODES**/ /* SIZE=4*/
	int number_of_nodes=count_nodes(list);
	int *number_of_nodes_ptr = &number_of_nodes;
	#ifdef DEBUG
	printf("Function returns %d\n",number_of_nodes);
	#endif
	fwrite(number_of_nodes_ptr,sizeof(int),1,file);

	/*Copy Nodes*/
	while(aux!=NULL)
	{

		#ifdef DEBUG
		printf("   Writting node to file ...");
		#endif

		size=0;

		/** MAC**/
		size=sizeof(aux->info->mac[0]);
		for(i = 0; i < MAC_SIZE; i++)
		{
			fwrite(&aux->info->mac[i],size,1,file);
		}
		/** ESSID SIZE**/ /* SIZE=4*/
		size = strlen(aux->info->essid);
		int *size_ptr = &size;
		fwrite(size_ptr,sizeof(int),1,file);

		/** ESSID**/ /* SIZE specified before*/
		fwrite(aux->info->essid,size,1,file);

		/** MODE**/
		size=sizeof(enum network_mode);
		fwrite(&aux->info->mode,size,1,file);

		/** CHANNEL**/  /* SIZE specified before */
		size=sizeof(int);
		fwrite(&aux->info->channel,size,1,file);

		/** ENCRYPTED**/  /* SIZE specified before */
		size=sizeof(unsigned short);
		fwrite(&aux->info->encrypted,size,1,file);

		/** QUALITY **/
		size=sizeof(unsigned int);
		for(j=0 ; j< 2 ; j++)
		{
			fwrite(&aux->info->quality[j],size,1,file);
		}
		#ifdef DEBUG
		printf(" Done\n");;
		#endif
		aux = aux->next;
	}
	//All data is saved
	data_changed=0;

	if (fclose(file) != 0){
		#ifdef DEBUG
		printf(" Closing the file\n");
		#endif
		printf("[ERROR]: It's impossible to close the file\n");
		printf(" Maybe the file is wrong. Check it!\n");
		return ;
	}
}
Пример #23
0
struct network * file_to_linkedlist(char *path)
{
	#ifdef DEBUG
	printf(" Entering file_to_linkedlist\n");
	#endif
	
	struct ap_scan_info *node_info;
	struct network * node;
	int bytes_read;
	int listsize; // SIZE OF THE LIST (BYTES)
	
	node = NULL;
	network mainlist = NULL;

	//STEP 1_ CHECK IF THE GIVEN FILE ALREADY EXISTS
	//1.1 THE FILE DOES NOT EXIST -> RECALL THE FUNCTION
	if (file_check(path)==0)
	{
		printf(" File %s does not exist.\n",path);
		printf(" Perharps you wrote a wrong path.\n");
	}
	//1.2 THE FILE DOES EXIST -> THE PROCCESS PROCEEDS
	else if (file_check(path)==1)
	{
		file = fopen(path, "r");
		#ifdef DEBUG
		printf(" Opening the file %s\n",path);
		#endif
		//STEP 2_ LOOK HOW MANY NODES THE LIST HAS
		bytes_read = fread(&listsize,sizeof(int),1,file);

		//STEP 3_ CREATE AND INSERT (list_size) number of NODES

		for(i = 0; i < listsize ; i++)
		{
			node_info = (struct ap_scan_info*)malloc(sizeof(struct
			ap_scan_info));

			//3.1 READ THE  FIELD "mac"
			for (j =0 ; j < MAC_SIZE ; j++)
			{
				bytes_read = fread(&(node_info->mac[j]),sizeof(char),1,file);
			}

			//3.2 READ THE FIELD "essid"
			bytes_read = fread(&size,sizeof(int),1,file);
			node_info -> essid = (char*)calloc((sizeof(char)*size + 1),size);
			bytes_read = fread(node_info -> essid,sizeof(char),size,file);

			//3.3 READ THE FIELD enum network_mode mode;
			size=sizeof(enum network_mode);
			fread(&node_info->mode,size,1,file);


			//3.4 READ THE FIELD channel;
			//bytes_read = fread(&size,sizeof(int),1,file);
			bytes_read = fread(&(node_info -> channel),sizeof(int),1,file);

			//3.5 READ THE FIELD encrypted
			bytes_read = fread(&(node_info -> encrypted),sizeof(unsigned
			short),1,file); //ONLY READS 1 BYTE

			//3.6 READ THE FIELD quality
			for(k = 0 ; k < 2 ; k++)
			{
				bytes_read = fread(&(node_info -> quality[k]),sizeof(unsigned
				int),1,file);
			}

			//3.7 CREATE NODE
			node = create_node(node_info, count_nodes(mainlist) + 1);
			free(node_info);

			//3.8 INSERT NODE
			mainlist = insert_node(node , mainlist);

			//3.9 SORT THE NEW LIST
			mainlist = sort(mainlist);
		}
		if (fclose(file)!=0)
		{
			#ifdef DEBUG
			printf(" Closing the file\n");
			#endif
			printf("[ERROR]: It's impossible to close the file\n");
		}
	}
	//1.3 UNNEXPECTED ERROR -> END
	else printf(" Unexpected Error.\n");

	#ifdef DEBUG
	printf(" Exiting file_to_linkedlist\n");
	#endif

	return mainlist;
}
Пример #24
0
// this is a private function that recursively prunes nodes top-down
// and only accepts a pruning if it increases the prediction score of the
// validation data
// returns the number of nodes successfully pruned
int prune_node(decision_tree *dt, dt_node *node, data_set *validation_data) {
    // the score with both subtrees still attached
    float primary_score = dt_score(dt, validation_data);

    // save subtrees so that we can restore them if classification score
    // didn't improve
    dt_node *left = node->left;
    dt_node *right = node->right;
    int right_prune_count = 0;
    int left_prune_count = 0;

    if(left != NULL) {
        node->left = NULL;

        // score the decision tree with the missing subtree
        float left_prune_score = dt_score(dt, validation_data);
        if(left_prune_score >= primary_score) {
            // found a good prune!
            left_prune_count = count_nodes(left);
            float diff = left_prune_score - primary_score;
            if(diff > 0.0002 || left_prune_count > 10) {
                printf("Improved score by %.4f, dropped %d nodes\n",
                        diff, left_prune_count);
            }
            // throw away the subtree now that we don't need it
            dt_free_node(left);
        }
        else {
            // prune was no good, so restore the subtree and recurse
            node->left = left;
            left_prune_count = prune_node(dt, node->left, validation_data);
        }
    }

    if(right != NULL) {
        // basically the same as above, but for the right subtree
        node->right = NULL;

        float right_prune_score = dt_score(dt, validation_data);
        if(right_prune_score >= primary_score) {
            right_prune_count = count_nodes(right);
            float diff = right_prune_score - primary_score;
            if(diff > 0.0002 || right_prune_count > 10) {
                printf("Improved score by %.4f, dropped %d nodes\n",
                        diff, right_prune_count);
            }
            dt_free_node(right);
        }
        else {
            node->right = right;
            right_prune_count = prune_node(dt, node->right, validation_data);
        }
    }

    // need to see if we're a leaf now
    if(node->left == NULL && node->right == NULL) {
        node->prediction_value = guess_node_class(dt, node);
        node->is_leaf = 1;
    }

    return left_prune_count + right_prune_count;
}
Пример #25
0
static int
put_tree_into_comb(struct ged *gedp, struct rt_comb_internal *comb, struct directory *dp, const char *old_name, const char *new_name, const char *imstr)
{
    int i;
    int done;
    char *line;
    char *ptr;
    char relation;
    char *name;
    struct rt_tree_array *rt_tree_array;
    struct line_list *llp;
    int node_count = 0;
    int tree_index = 0;
    union tree *tp;
    matp_t matrix;
    struct bu_vls vls = BU_VLS_INIT_ZERO;
    char *str;

    if (imstr == (char *)NULL)
	return GED_ERROR;

    BU_LIST_INIT(&HeadLines.l);

    /* duplicate the immutable str (from argv) for strtok style mutation */
    str = bu_strdup(imstr);

    /* break str into lines */
    line = str;
    ptr = strchr(str, '\n');
    if (ptr != NULL)
	*ptr = '\0';

    while (line != (char *)NULL) {
	int n;

	bu_vls_strcpy(&vls, line);

	if ((n = count_nodes(gedp, bu_vls_addr(&vls))) < 0) {
	    bu_vls_free(&vls);
	    bu_list_free(&HeadLines.l);
	    bu_free(str, "dealloc bu_strdup str");
	    return GED_ERROR;
	} else if (n > 0) {
	    BU_ALLOC(llp, struct line_list);
	    BU_LIST_INSERT(&HeadLines.l, &llp->l);
	    llp->line = line;

	    node_count += n;
	} /* else blank line */

	if (ptr != NULL && *(ptr+1) != '\0') {
	    /* leap frog past EOS */
	    line = ptr + 1;

	    ptr = strchr(line, '\n');
	    if (ptr != NULL)
		*ptr = '\0';
	} else {
	    line = NULL;
	}
    }
    bu_vls_free(&vls);

    /* build tree list */
    if (node_count)
	rt_tree_array = (struct rt_tree_array *)bu_calloc(node_count, sizeof(struct rt_tree_array), "tree list");
    else
	rt_tree_array = (struct rt_tree_array *)NULL;

    for (BU_LIST_FOR (llp, line_list, &HeadLines.l)) {
	done = 0;
	ptr = strtok(llp->line, _delims);
	while (!done) {
	    if (!ptr)
		break;

	    /* First non-white is the relation operator */
	    relation = (*ptr);
	    if (relation == '\0')
		break;

	    /* Next must be the member name */
	    ptr = strtok((char *)NULL, _delims);
	    if (ptr == (char *)NULL) {
		bu_list_free(&HeadLines.l);
		if (rt_tree_array)
		    bu_free((char *)rt_tree_array, "red: tree list");
		bu_log("no name specified\n");
		bu_free(str, "dealloc bu_strdup str");
		return GED_ERROR;
	    }
	    name = ptr;

	    /* Eliminate trailing white space from name */
	    i = (int)strlen(ptr);
	    while (isspace((int)name[--i]))
		name[i] = '\0';

	    /* Check for existence of member */
	    if ((db_lookup(gedp->ged_wdbp->dbip, name, LOOKUP_QUIET)) == RT_DIR_NULL)
		bu_log("\tWARNING: ' %s ' does not exist\n", name);

	    /* get matrix */
	    ptr = strtok((char *)NULL, _delims);
	    if (ptr == (char *)NULL) {
		matrix = (matp_t)NULL;
		done = 1;
	    } else if (*ptr == 'u' ||
		       (*ptr == '-' && *(ptr+1) == '\0') ||
		       (*ptr == '+' && *(ptr+1) == '\0')) {
		/* assume another relational operator */
		matrix = (matp_t)NULL;
	    } else {
		int k;

		matrix = (matp_t)bu_calloc(16, sizeof(fastf_t), "red: matrix");
		matrix[0] = atof(ptr);
		for (k = 1; k < 16; k++) {
		    ptr = strtok((char *)NULL, _delims);
		    if (!ptr) {
			bu_log("incomplete matrix for member %s - No changes made\n", name);
			bu_free((char *)matrix, "red: matrix");
			if (rt_tree_array)
			    bu_free((char *)rt_tree_array, "red: tree list");
			bu_list_free(&HeadLines.l);
			bu_free(str, "dealloc bu_strdup str");
			return GED_ERROR;
		    }
		    matrix[k] = atof(ptr);
		}
		if (bn_mat_is_identity(matrix)) {
		    bu_free((char *)matrix, "red: matrix");
		    matrix = (matp_t)NULL;
		}

		ptr = strtok((char *)NULL, _delims);
		if (ptr == (char *)NULL)
		    done = 1;
	    }

	    /* Add it to the combination */
	    switch (relation) {
		case '+':
		    rt_tree_array[tree_index].tl_op = OP_INTERSECT;
		    break;
		case '-':
		    rt_tree_array[tree_index].tl_op = OP_SUBTRACT;
		    break;
		default:
		    if (relation != 'u') {
			bu_log("unrecognized relation (assume UNION)\n");
		    }
		    rt_tree_array[tree_index].tl_op = OP_UNION;
		    break;
	    }

	    BU_ALLOC(tp, union tree);
	    RT_TREE_INIT(tp);
	    rt_tree_array[tree_index].tl_tree = tp;
	    tp->tr_l.tl_op = OP_DB_LEAF;
	    tp->tr_l.tl_name = bu_strdup(name);
	    tp->tr_l.tl_mat = matrix;
	    tree_index++;
	}
    }

    bu_list_free(&HeadLines.l);
    i = make_tree(gedp, comb, dp, node_count, old_name, new_name, rt_tree_array, tree_index);

    bu_free(str, "dealloc bu_strdup str");

    return i;
}
Пример #26
0
// private function, returns a count of all children of the specified node plus
// the node itself (children + 1)
int count_nodes(dt_node *node) {
    if(node == NULL) {
        return 0;
    }
    return 1 + count_nodes(node->left) + count_nodes(node->right);
}