int main() {
    int nU, nX, nY; // Довжина універсалу, множин X, Y
    printf("Введіть універсальну множину");
    int* universal = inputSet(nU);
    printf("\nВведіть множину Х");
    int* x = inputSet(nX, universal, nU);
    printf("\nВведіть множину У");
    int *y = inputSet(nY, universal, nU);

    printf("\nОтримані множини:");
    printSet(universal, nU);
    printSet(x, nX);
    printSet(y, nY);

    printUnion(x, nX, y, nY);
    printIntersect(x, nX, y, nY);
    printDiff(x, nX, y, nY);
    printDiff(y, nY, x, nX);
    printInverse(x, nX, universal, nU);
    printInverse(y, nY, universal, nU);
    printLinearMultiply(x, nX, y, nY);

    free(universal);
    free(x);
    free(y);
}
void AKMTTask::print() {
	std::cout << "\t\tTask " << _id << " (costs " << _cost;
	if (this->isFork()) {
		std::cout << "; forks Thread " << _forkedThread->id();
	} else if (this->isJoin()) {
		std::cout << "; joins Thread " << _joinedThread->id(); 
	}
	std::cout << "; pred: "; printSet(_predecessors);
	std::cout << "; succ: "; printSet(_successors);
	std::cout << "; state: " << this->stateString() << ");\n";
}
Esempio n. 3
0
/** Print the contents of a @a NonTerminal
	@param nonTerminal The @a NonTerminal to print
*/
static void printNonTerminal(NonTerminal *nonTerminal) {
	/* For verbosity level 2, only print the rules containing conflicts. */
	if (option.verbose == 2 && !termContainsConflict(&nonTerminal->term))
		return;
	fprintf(printRuleOutput, "%s ", nonTerminal->token->text);
	fputs(":\n", printRuleOutput);
	printSet("First-set", nonTerminal->term.first);
	printSet("Contains-set", nonTerminal->term.contains);
	printSet("Follow-set", nonTerminal->term.follow);
	indent = 1;
	printTerm(&nonTerminal->term);
	fputs(";\n\n", printRuleOutput);
}
Esempio n. 4
0
int main()
{
    char buffer[80];
    int i, index;
    Set set1, set2, set3;

    i = 0;  
    while ( (scanf("%s",buffer)) != EOF )
    {
        strcpy(names[i],buffer);
        i++;
    }
    printf("The initial data is:\n");
    print(names,i);
    bubbleSort(names,i);
    printf("\n\nThe sorted data is:\n");
    print(names,i);

    clearSet(set1);
    clearSet(set2);
    clearSet(set3);

    printf("Adding Warner, Faulk and Pace to set1:\n");
    addName2Set(set1,"Warner");
    addName2Set(set1,"Faulk");
    addName2Set(set1,"Pace");
    printf("Set1 = ");
    printSet(set1);

    printf("Adding Snider, Robinson and Koufax to set2:\n");
    addName2Set(set2,"Snider");
    addName2Set(set2,"Robinson");
    addName2Set(set2,"Koufax");
    printf("Set2 = ");
    printSet(set2);

    setUnion(set1, set2, set3);
    printf("The union of sets 1 and 2 is: ");
    printSet(set3);
    
    printf("The intersection of sets 3 and 2 is: ");
    setIntersection(set3, set2, set3);
    printSet(set3);

    printf("Deleting Snider from set3:\n");
    deleteNameFromSet(set3,"Snider");    
    printf("Set3 = ");
    printSet(set3);
}
Esempio n. 5
0
/** Print the parts of an @a Alternative
	@param alternative The @a Alternative to print

	Note: actions are printed only as {...}
*/
static void printAlternative(Alternative *alternative) {
	GrammarPart *grammarPart;
	int i;
	
	for (i = 0; i < listSize(alternative->parts); i++) {
		grammarPart = (GrammarPart *) listIndex(alternative->parts, i);
		printIndent();
		switch (grammarPart->subtype) {
			case PART_ACTION:
				fputs("{...}", printRuleOutput);
				break;
			case PART_TERMINAL:
			case PART_LITERAL:
				fputs(grammarPart->token->text, printRuleOutput);
				break;
			case PART_NONTERMINAL:
			case PART_UNDETERMINED:
				fputs(grammarPart->token->text, printRuleOutput);
				break;
			case PART_TERM:
				fputs("[\n", printRuleOutput);
				/* Only print the sets for repeating terms */
				if (!(grammarPart->uTerm.repeats.subtype == FIXED && grammarPart->uTerm.repeats.number == 1)) {
					printSet("First-set", grammarPart->uTerm.first);
					printSet("Contains-set", grammarPart->uTerm.contains);
					printSet("Follow-set", grammarPart->uTerm.follow);
				}
				indent++;
				if (grammarPart->uTerm.flags & TERM_WHILE) {
					printIndent();
					fprintf(printRuleOutput, "%%while %s\n", grammarPart->uTerm.expression->text);
				}
				if (grammarPart->uTerm.flags & TERM_PERSISTENT) {
					printIndent();
					fputs("%persistent\n", printRuleOutput);
				}
				printTerm(&grammarPart->uTerm);
				indent--;
				printIndent();
				fputc(']', printRuleOutput);
				printRepeats(grammarPart->uTerm.repeats);
				break;
			default:
				PANIC();
		}
		fputc('\n', printRuleOutput);
	}
}
Esempio n. 6
0
/** Print the alternatives of a @a Term
	@param term The @a Term to print
*/
static void printTerm(Term *term) {
	int i;
	Alternative *alternative;
	for (i = 0; i < listSize(term->rule); i++) {
		alternative = (Alternative *) listIndex(term->rule, i);
		if (listSize(term->rule) != 1)
			printSet("Alternative on", alternative->first);
		if (alternative->flags & ALTERNATIVE_PREFER) {
			printIndent();
			fputs("%prefer\n", printRuleOutput);
		}
		if (alternative->flags & ALTERNATIVE_AVOID) {
			printIndent();
			fputs("%avoid\n", printRuleOutput);
		}
		if (alternative->flags & ALTERNATIVE_IF) {
			printIndent();
			fprintf(printRuleOutput, "%%if %s\n", alternative->expression->text);
		}
		if (alternative->flags & ALTERNATIVE_DEFAULT && listSize(term->rule) != 1) {
			printIndent();
			fputs("%default\n", printRuleOutput);
		}
	
		printAlternative(alternative);
		if (i < listSize(term->rule) - 1) {
			indent--;
			printIndent();
			fputs("|\n", printRuleOutput);
			indent++;
		}
	}
}
Esempio n. 7
0
// returns a vector of vectors of 3 cards
vector<vector<Card>> SetGame::findAllSets(vector<Card> &cards, bool print)
{
	if (cards.size() < 3)
		throw new argumentException();

	int numCards = cards.size();
	vector<vector<Card>> sets;

	// for any two cards, only one other card will make it a set
	for (int first = 0; first < numCards - 2; first++)
	{
		for (int second = 1 + first; second < numCards - 1; second++)
		{
			for (int third = 1 + second; third < numCards; third++)
			{
				vector<Card> set({ cards[first], cards[second], cards[third] });
				if (isASet(set))
				{
					sets.push_back(set);
					if (print) printSet(set);
				}
			}
		}
	}
	if (print) 
		printf("\nFound %i sets!\n", sets.size());
	return sets;
}
Esempio n. 8
0
QSet<Node*>* Node::eClosure(QSet<Node*>* allSoFar, QSet<Node*>* previous, int direction)
{
  
  if(previous == NULL)
  {
    previous = new QSet<Node*>();
  }

  /* Base case */
  if ((*allSoFar) == (*previous)) 
  {
    return allSoFar;
  }

  if(VERBOSE)
  {
    printf("\n\n==============\n\n");
    printf("All so far:\n");
    printSet(allSoFar);
    printf("\n");
  }

  QSet<Node*>* one_step_eps = new QSet<Node*>();

  QMutableSetIterator<Node*> i(*allSoFar);
  while(i.hasNext())
  {
    // one_step_eps->unite(*i.next()->connections->value("@"));
    Node* node = i.next();
    if (node->connections->contains("@"))
    {
      one_step_eps->unite(*node->connections->value("@"));
    }
  }

  one_step_eps->unite(*allSoFar);

  if(VERBOSE)
  {
    printf("After closure:\n");
    printSet(one_step_eps);
    printf("\n");
  }

  return eClosure(one_step_eps, allSoFar, direction);
}
Esempio n. 9
0
int main(int argc, char **argv)
{
	int inputs;					/* Number of inputs into the neural network */

	getCommandLine(&inputs, argc, argv);
	printHeader(inputs);
	printSet(inputs);
}
Esempio n. 10
0
            void printInstructions(bool sets=false)
            {
                for(auto i : instructions)
                    cout << i.str() << endl;

                if(branchOn)
                    cout << " branchOn: " << branchOn << endl;;

                if(sets)
                {
                    printSet("dead", m.dead);
                    printSet("used", m.used);
                    printSet("alive", m.alive);
                    if(m.dead.size() || m.used.size() || m.alive.size())
                        cout << endl;
                }
            }
Esempio n. 11
0
int main()
{
    init();
    genMaze1();
    //genMaze2();
    printMaze();
    printSet();
    return 0;
}
Esempio n. 12
0
int main  ( int argc, char **argv )
{
  int density;        /* Density of the data set to generate */
  double maxRadius;   /* Maximum radius of the data set to generate */

  getCommandLine ( &density, &maxRadius, argc, argv );
  printHeader    ( density, maxRadius );
  printSet       ( density, maxRadius );
  return 0; 
}
int main(void)
{ printf("%s%u","\nБрой предмети: ",N);
  printf("%s%u","\nМаксимално допустимо общо тегло: ",M);
  calculate();
  printf("\nТаблица F[i][j]: ");
  printTable();
  printf("\n%s%u","Максимална постигната стойност: ",F[N][M]);
  printf("\nВземете предметите с номера: "); printSet();
  return 0;
}
Esempio n. 14
0
void RBBITableBuilder::printPosSets(RBBINode *n) {
    if (n==NULL) {
        return;
    }
    n->printNode();
    RBBIDebugPrintf("         Nullable:  %s\n", n->fNullable?"TRUE":"FALSE");

    RBBIDebugPrintf("         firstpos:  ");
    printSet(n->fFirstPosSet);

    RBBIDebugPrintf("         lastpos:   ");
    printSet(n->fLastPosSet);

    RBBIDebugPrintf("         followpos: ");
    printSet(n->fFollowPos);

    printPosSets(n->fLeftChild);
    printPosSets(n->fRightChild);
}
Esempio n. 15
0
static vector<bitset<MAX> > parseBitsets(vector<string> input,
                                         int num_obs, int num_ats) {
    vector<bitset<MAX> > in(input.size());
    transform(input.begin(), input.end(), in.begin(), [](string &s) {
        reverse(s.begin(), s.end());
        bitset<MAX> b(s);
        return b;
    });
    for (auto b : in)
        printSet(b, num_ats);
    return in;
}
Esempio n. 16
0
int main(void){
    const int SIZE = 5;
    int S1[5];
    int S3[5];

    int min1;
    int min2;

    srand (time(NULL));

    fillSet(S1, SIZE);
    printSet(S1, SIZE);

    fillSet(S3, SIZE);
    printSet(S3, SIZE);

    min1 = minOfSet(S1, SIZE);
    min2 = minOfSet(S3, SIZE);

    printf("Sum of minimal values is %d\n", min1 + min2);
}
Esempio n. 17
0
int main() {
	std::set<int> mySet = {1,4,7,6};
	std::string mystream=sprintSet(mySet);
	std::cout <<mystream <<std::endl;
	
	printSet( std::cout, mySet );
	//~ std::string mystring = strout.str();
	//~ char const * c_str = mystring.c_str();

	//double d;
	//strout >> d;
	return 0;
}
int main() {
	Forest someForest = {{0}, {0}};
	Forest * f = &someForest;
	makeSet(f, 1);
	makeSet(f, 2);
	makeSet(f, 3);
	printf("are 1 and 3 in the same set? %s\n", findSet(f, 1) == findSet(f, 3) ? "yes" : "no");
	printf("makeUnion(f, 1, 3)\n");
	makeUnion(f, 1, 3);
	printf("are 1 and 3 in the same set? %s\n", findSet(f, 1) == findSet(f, 3) ? "yes" : "no");
	printSet(f);
	return 0;
}
Esempio n. 19
0
// Prints all the permutations
void Permutations::print() const
{
    int i = 1;
    for(NodePtr tmp = myPerms; tmp != NULL; tmp = tmp->next)
    {

        cout << i <<": ";
        printSet(tmp->setPtr, tmp->setSize);
        i++;
        cout << endl;
    }

}
int main()
{
	int size;
	UnionSet* unionSet;
	ElementType data[] = {110, 245, 895, 658, 321, 852, 147, 458, 469, 159, 347, 28};

	size = 12;
	printf("\n\t====== test for union set by depth ======\n");
	//printf("\n\t=== the initial array is as follows ===\n");
	//printArray(data, depth); 
	
	printf("\n\t=== the init union set are as follows ===\n");
	unionSet = initUnionSet(size, data); // initialize the union set over
	printSet(unionSet, size);
	
	printf("\n\t=== after union(0, 1) + union(2, 3) + union(4, 5) + union(6, 7) + union(8, 9) + union(10 ,11) ===\n");
	setUnion(unionSet, 0, 1);
	setUnion(unionSet, 2, 3);
	setUnion(unionSet, 4, 5);
	setUnion(unionSet, 6, 7);
	setUnion(unionSet, 8, 9);	
	setUnion(unionSet, 10, 11);	
	printSet(unionSet, size);

	printf("\n\t=== after union(1, 3) + union(5, 7) + union(9, 11) ===\n");
	setUnion(unionSet, 1, 3);
	setUnion(unionSet, 5, 7);
	setUnion(unionSet, 9, 11);
	printSet(unionSet, size);  
	
	printf("\n\t=== after union(3, 7) + union(7, 11) ===\n");
	setUnion(unionSet, 3, 7);
	setUnion(unionSet, 7, 11);	
	printSet(unionSet, size); 

	return 0;
}
Esempio n. 21
0
/*
 * ======================================================================
 * MEMBER FUNCTIONS: QmvList
 * ======================================================================
 */
QmvList::QmvList(QmvEditor * editor)
        : QListView(editor), editor(editor)
{
    viewport()->setBackgroundMode( PaletteBackground );
    setResizePolicy( QScrollView::Manual );
    
    if (editor->shuttleClass())
    {
        qDebug("qmvlist:classname=%s",  editor->shuttleClass()->relationName().latin1());
        addColumn( tr( editor->shuttleClass()->relationTitle() ) );
        QString ctlabel;
        ctlabel.sprintf("%d rows",editor->shuttleClass()->count());
        addColumn( tr( ctlabel) );
        
    } else {
        addColumn( "No Class Selected" );
        addColumn( "0 Rows" );
    }
    tuplemenu = new QPopupMenu(this, "item menu");
    tuplemenu->insertItem("Item Menu");
    tuplemenu->insertSeparator();
    tuplemenu->insertItem("&New", this, SLOT(itemInsert()));
    tuplemenu->insertItem("&Copy", this, SLOT(itemCopy()));
    tuplemenu->insertItem("&Delete", this, SLOT(itemRemove()));

    relationmenu = new QPopupMenu(this, "relation menu");
    relationmenu->insertItem("Relation Menu");
    relationmenu->insertSeparator();
    relationmenu->insertItem("&Print", this, SLOT(printSet()));
    relationmenu->insertItem("&Export", this, SLOT(exportSet()));
    
    
    QToolTip::add( header(), "Click for codes Utilites-Menu");
    
    connect( header(), SIGNAL( sizeChange( int, int, int ) ),
	     this, SLOT( updateEditorSize() ) );
    disconnect( header(), SIGNAL( clicked( int ) ),
		this, SLOT( changeSortColumn( int ) ) );
    connect( this, SIGNAL( pressed( QListViewItem *, const QPoint &, int ) ),
	     this, SLOT( itemPressed( QListViewItem *, const QPoint &, int ) ) );
    connect( this, SIGNAL( rightButtonPressed( QListViewItem *, const QPoint &, int ) ),
	     this, SLOT( itemMenu( QListViewItem *, const QPoint &, int ) ) );
    connect( header(), SIGNAL( clicked( int ) ),
	     this, SLOT( currentSetMenu() ) );
    connect( this, SIGNAL( doubleClicked( QListViewItem * ) ),
	     this, SLOT( toggleOpen( QListViewItem * ) ) );
    setSorting( -1 );
    setHScrollBarMode( AlwaysOff );
}
Esempio n. 22
0
void printPowerset (int n)
{
    int stack[10],k;
    stack[0]=0; /* 0 is not considered as part of the set */
    k = 0;
    while(1){
        if (stack[k]<n){
            stack[k+1] = stack[k] + 1;
            k++;
        }
        else{
            stack[k-1]++;
            k--;
        }
        if (k==0)
            break;
        printSet(stack,k);
    }
    return;
}
std::vector<std::string> asferencodestr::getNextSet(std::vector<std::string> enchoro_vec, int i)
{
	std::vector<std::string> subset;
	int n=enchoro_vec.size();
	//compute next subset in the power set
	std::bitset<100> setbitmap(i);
	int indx=0;
	for(size_t t = 0; t < setbitmap.size(); t++)
	{
		if(setbitmap.test(t))
		{
			subset.push_back(enchoro_vec[indx]);
		}
		indx++;
	}
	cout<<"getNextSet(): enchoro_vec.size() = "<<enchoro_vec.size()<<endl;
	cout<<"getNextSet(): subset: "<<printSet(subset)<<endl;
	cout<<"getNextSet(): subset size ="<<subset.size()<<endl;
	return subset;
}
void testPowerSetRecursive() {
    cout << endl;
    cout << "Test powerSetRecursive():" << endl;
    cout << "=========================" << endl;

    set<char> s;

    s.insert('a');
    s.insert('b');
    s.insert('c');
    s.insert('d');
    s.insert('e');

    cout << "s = ";
    printSet(s);

    set<set<char>> p = powerSetRecursive(s);
    cout << "powerSetRecursive(s) = " << p.size()
         << " subsets:" << endl;
    printPowerSet(p);
}
void generateEmscriptenMetadata(std::ostream& o,
                                Module& wasm,
                                std::unordered_map<Address, Address> segmentsByAddress,
                                Address staticBump,
                                std::vector<Name> const& initializerFunctions) {
  o << ";; METADATA: { ";
  // find asmConst calls, and emit their metadata
  AsmConstWalker walker(wasm, segmentsByAddress);
  walker.walkModule(&wasm);
  // print
  o << "\"asmConsts\": {";
  bool first = true;
  for (auto& pair : walker.sigsForCode) {
    auto& code = pair.first;
    auto& sigs = pair.second;
    if (first) first = false;
    else o << ",";
    o << '"' << walker.ids[code] << "\": [\"" << code << "\", ";
    printSet(o, sigs);
    o << "]";
  }
  o << "}";
  o << ",";
  o << "\"staticBump\": " << staticBump << ", ";

  o << "\"initializers\": [";
  first = true;
  for (const auto& func : initializerFunctions) {
    if (first) first = false;
    else o << ", ";
    o << "\"" << func.c_str() << "\"";
  }
  o << "]";

  o << " }\n";
}
Esempio n. 26
0
int main() {
	int i, num, cNum;
	char temp1[257], temp2[257], classString[12], buffer[80], call[80], test[80], next[80];
	stack s;
	Set dset;
	initStack(&s);

	DBRecord **students;

	scanf("%d", &num);
	printf("%d \n", num);

    students = (DBRecord **) malloc(num * sizeof(DBRecord *));

	for(i = 0; i < num; i++) {
		students[i] = (DBRecord *) malloc (sizeof(DBRecord));
		students[i]->bitID = i;
		scanf("%s %s %s %d %s %f %d", temp1, temp2, students[i]->idNum, &students[i]->age, classString, &students[i]->gpa, &students[i]->expectedGrad);

		//  allocate space for character strings, and copy the strings */
		students[i]->lName = (char *) malloc(strlen(temp1) + 1);
		strcpy(students[i]->lName, temp1);
		students[i]->fName = (char *) malloc(strlen(temp2) + 1);
		strcpy(students[i]->fName, temp2);

		// set the year field from the strings of Class values
		if( (strcmp(classString,"firstYear")) == 0 )
			students[i]->year = firstYear;

		else if( (strcmp(classString,"sophmore")) == 0 )
			students[i]->year = sophomore;

		else if( (strcmp(classString,"junior")) == 0 )
			students[i]->year = junior;

		else if( (strcmp(classString,"senior")) == 0 )
			students[i]->year = senior;

		else if( (strcmp(classString,"grad")) == 0 )
			students[i]->year = grad;

		else
			assert(0);

	}
	printf("Done scanning \n");

	while (scanf("%s", buffer) != EOF) {
		if (strcmp(buffer, "create") == 0) {
			clearSet(dset);
			scanf("%s", call);
			scanf("%s", test);

			if (strcmp(call, "lastName") == 0) {
				scanf("%s", next);
				if (strcmp(test, "=") == 0) {
					for(i = 0; i < num; i++) {
						if (strcmp(students[i]->lName, next) == 0)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, "<") == 0) {
					for(i = 0; i < num; i++) {
						if (strcmp(students[i]->lName, next) < 0)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, ">") == 0) {
					for(i = 0; i < num; i++) {
						if (strcmp(students[i]->lName, next) > 0)
							add2Set(dset, students[i]->bitID);
					}
				}
			}
			if (strcmp(call, "firstName") == 0) {
				scanf("%s", next);
				if (strcmp(test, "=") == 0) {
					for(i = 0; i < num; i++) {
						if (strcmp(students[i]->fName, next) == 0)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, "<") == 0) {
					for(i = 0; i < num; i++) {
						if (strcmp(students[i]->fName, next) < 0)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, ">") == 0) {
					for(i = 0; i < num; i++) {
						if (strcmp(students[i]->fName, next) > 0)
							add2Set(dset, students[i]->bitID);
					}
				}
			}
			if (strcmp(call, "idNum") == 0) {
				scanf("%s", next);
				if (strcmp(test, "=") == 0) {
					for(i = 0; i < num; i++) {
						if (strcmp(students[i]->idNum, next) == 0)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, "<") == 0) {
					for(i = 0; i < num; i++) {
						if (strcmp(students[i]->idNum, next) < 0)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, ">") == 0) {
					for(i = 0; i < num; i++) {
						if (strcmp(students[i]->idNum, next) > 0)
							add2Set(dset, students[i]->bitID);
					}
				}
			}
			if (strcmp(call, "age") == 0) {
				scanf("%d", &cNum);
				if (strcmp(test, "=") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->age == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, "<") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->age == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, ">") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->age == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
			}
			if (strcmp(call, "year") == 0) {
				scanf("%d", &cNum);
				if (strcmp(test, "=") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->year == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, "<") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->year == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, ">") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->year == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
			}
			if (strcmp(call, "gpa") == 0) {
				scanf("%d", &cNum);
				if (strcmp(test, "=") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->gpa == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, "<") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->gpa == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, ">") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->gpa == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
			}
			if (strcmp(call, "expectedGrad") == 0) {
				scanf("%d", &cNum);
				if (strcmp(test, "=") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->expectedGrad == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, "<") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->expectedGrad == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
				if (strcmp(test, ">") == 0) {
					for(i = 0; i < num; i++) {
						if(students[i]->expectedGrad == cNum)
							add2Set(dset, students[i]->bitID);
					}
				}
			}
			push(&s, dset);
			printf("Created & Pushed Set \n");
		}
		if (strcmp(buffer, "union")) {
			Set uset1, uset2, urset;
			memcpy(uset2, pop(&s), 10 * sizeof(unsigned int));
			memcpy(uset1, pop(&s), 10 * sizeof(unsigned int));
			setUnion(uset1, uset2, urset);
			push(&s, urset);
			printf("Pushed Set \n");
		}
		if (strcmp(buffer, "intersection")) {
			Set iset1, iset2, irset;
			memcpy(iset2, pop(&s), 10 * sizeof(unsigned int));
			memcpy(iset1, pop(&s), 10 * sizeof(unsigned int));
			setIntersection(iset1, iset2, irset);
			push(&s, irset);
			printf("Pushed Set \n");
		}
		if (strcmp(buffer, "print")) {
			Set pset;
			memcpy(pset, pop(&s), 10 * sizeof(unsigned int));
			printSet(pset);
		}
		
	}
}
int main(int argc, char *argv[]){

    /* Itteration Variables */
    int i = 1;
    int gen = 0;
    double bestSSE = DBL_MAX; 
    /* Creating performance variables */
    double genDiv = 0;
    double genSSE[3] = {0,0,0};     /* worst, avg, best */
    double sseError[MAXPOP];
    double val[NUMPOINTS][2];
    /* Genetic Paramenters */
    int populationSize = 500;           /* Population size (constant) */
    int treeDepth = 15;                 /* Maximum Tree Depth */
    int maxGenerations = 50;            /* Maximum Number of generations */
    double sseGoal = 0.5;               /* SSE error goal (for spartan) */
    double pruneFactor = 0.0;          /* Probability that a branch will be prunned */
    double constProb = 0.60;            /* Probability that a leaf will be a randomly choose (0,1) constant */
    double mutationRate = 0.20;         /* Mutation Rate (probability that a node will be mutated */
    double swapRate = 0.7;              /* Probability that crossover will occur */
    double tournamentFraction = 0.40;   /* fraction of individuals selected by tournament */
    double rankFraction = 0.50;         /* fraction of individual selected by rank */
    double spartanFraction = 0.1;        /* fraction of individuals selected by rank, copied as is */
    struct geneticParam genParam;       /* compat representation of generation */
    node *forest[MAXPOP];               /* Forest of trees */
    node *bestTree;
    /* Output Variables */
    int train = 1;
    int performance = 1;
    double evalPoint = 0;
    FILE *out = stdout;
    char bestTreeName[128];
    char response[128] = "Y";
    strcpy(bestTreeName,"bestTree");

    /* Processing Command Line Inputs */
    for (i = 1;  i < argc; i++){
        if (strcmp(argv[i],"--maxDepth")==0){
            sscanf(argv[++i],"%d",&treeDepth);
        }
        else if (strcmp(argv[i],"--test")==0){
            test();
            return EXIT_SUCCESS;
        }
        else if (strcmp(argv[i],"--popSize")==0){
            populationSize = atoi(argv[++i]);
        }
        else if (strcmp(argv[i],"--pruneFactor")==0){
            pruneFactor = (double)atof(argv[++i]);
        }
        else if (strcmp(argv[i],"--constProb")==0){
            constProb = (double)atof(argv[++i]);
        }
        else if (strcmp(argv[i],"--sseGoal")==0){
            sseGoal = (double)atof(argv[++i]);
        }
        else if (strcmp(argv[i],"--mutationRate")==0){
            mutationRate = (double)atof(argv[++i]);
        }
        else if (strcmp(argv[i],"--swapRate")==0){
            swapRate = (double)atof(argv[++i]);
        }
        else if (strcmp(argv[i],"--tournamentFraction")==0){
            tournamentFraction = (double) atof(argv[++i]);
            rankFraction = 1.0 - tournamentFraction;
        }
        else if (strcmp(argv[i],"--rankFraction")==0){
            rankFraction = (double) atof(argv[++i]);
        }
        else if (strcmp(argv[i],"--spartanFraction")==0){
            spartanFraction = (double) atof(argv[++i]);
        }
        else if (strcmp(argv[i],"--maxGen")==0){
            maxGenerations = atoi(argv[++i]);
        }
        else if(strcmp(argv[i],"--bestTreeName")==0){
            strcpy(bestTreeName,argv[++i]);
        }
        else if (strcmp(argv[i],"--help")==0){
            usage(stdout,argv[0]);
            exit(EXIT_SUCCESS);
        }
        else{
            fprintf(stderr,"Argument %s is not reconized\n",argv[i]);
            usage(stderr,argv[0]);
            exit(EXIT_FAILURE);
        }
    }
    /* Checking Input Arguments */
    if (populationSize > MAXPOP){
        fprintf(stderr,"population size is set to the max at %d. Change define for larger population\n",MAXPOP);
        populationSize = MAXPOP;
    }
    if (mutationRate > 1)
        mutationRate = 0.1;
    if (swapRate > 1)
        swapRate = 0.1;
    if (tournamentFraction + rankFraction > 1.0){
        fprintf(stderr,"Tournament Fraction %5.3f and rank fraction %5.3f are greater than 1.0\n",
                tournamentFraction,rankFraction);
        fprintf(stderr,"Both are set to default values\n");
        tournamentFraction = 0.9;
        rankFraction = 1.0 - tournamentFraction;
    }
    genParam.mutationRate = mutationRate;
    genParam.swapRate = swapRate;
    genParam.touramentFraction = tournamentFraction;
    genParam.rankFraction = rankFraction;
    genParam.spartanFraction = spartanFraction;
    genParam.constProb = constProb;
    genParam.maxDepth = treeDepth;
    genParam.pruneFraction = pruneFactor;
    splash(out);

    /* Train or Run? */
    if (argc <= 1){
        fprintf(stdout,"Preform symbolic regression with genetic programming [y/n]:\n");
        fscanf(stdin,"%s",response);
        if (strcmp(response,"y")==0 || strcmp(response,"Y")==0)
            train = 1;
        else
            train = 0;

        fprintf(stdout,"Do you want to print the performance of the best tree [y/n]: \n");
        fscanf(stdin,"%s",response);
        if (strcmp(response,"y")==0 || strcmp(response,"Y")==0)
            performance = 1;
        else
            performance = 0;

    }
    /* Run Information */
    fprintf(out,"Parameters:\n");
    fprintf(out,"\tPopulation Size: %d\n\tMax Tree Depth: %d\n",populationSize,treeDepth);
    fprintf(out,"\tPrune factor: %3.2f\n\tConstant Probability: %3.2f\n",pruneFactor,constProb);
    fprintf(out,"\tSSE Goal: %3.2f\n\tMax Generations: %d\n",sseGoal,maxGenerations);
    fprintf(out,"\tSpartan Fraction: %3.2f\n",spartanFraction);
    fprintf(out,"\tTournament Fraction: %3.2f\n\tRank Fraction: %5.2f\n",tournamentFraction,rankFraction);
    fprintf(out,"\tMutation Rate: %3.2f\n\tSwap Rate: %3.2f\n",mutationRate,swapRate);
    printSet();

    /* Reading in the data file */
    importData("proj2-data.dat",val);

    /* Creating the intitial population */
    if (train){
        srand( time(NULL));
        fprintf(stdout,"Creating Intial Population\n");
        rampedHalfHalf(forest,populationSize,&genParam);

        /* Running Generations */
        fprintf(out,"Generation\tDiversity\tMean SSE\tBest SSE\n");
        while(gen < maxGenerations && bestSSE > sseGoal){

            /* Diversity and SSE */
            genDiv = diversity(forest,populationSize);
            bestSSE = SSE(forest,populationSize,val,genSSE,sseError,bestTreeName); 
            fprintf(out,"\t%d\t%3.2f\t\t%3.2e\t%3.2e\n",gen,genDiv,genSSE[1],genSSE[2]);

            /* Genetic Operations */
            breedGeneration(forest,populationSize,sseError,&genParam);
            gen++;
        }
        /* Diversity and SSE */
       genDiv = diversity(forest,populationSize);
       bestSSE = SSE(forest,populationSize,val,genSSE,sseError,bestTreeName); 
       fprintf(out,"\t%d\t%3.2f\t\t%3.2e\t%3.2e\n",gen,genDiv,genSSE[1],genSSE[2]);
        /* Clean up, clean up, everybody do your share */
        deleteForest(forest,populationSize);
    }
    /* Looking at the performance of the best tree */
    if (performance){
        sprintf(response,"%s.postfix",bestTreeName);
        bestTree = bestTreeSummary(out,response,val);
        if (argc <= 1){
        
        fprintf(stdout,"Enter value on which to test the tree [n to escape]: \n");
        while(fscanf(stdin,"%lf",&evalPoint)==1){
            fprintf(stdout,"Tree(%5.3f) = %5.3f\n",evalPoint,evalTree(bestTree,evalPoint));
        }
        deleteTree(bestTree);
    
        }
    }
    return EXIT_SUCCESS;
}
Esempio n. 28
0
// Propagate conditions
bool ConditionPropagator::runOnFunction(llvm::Function &F)
{
    m_map.clear();
    llvm::SmallVector<std::pair<const llvm::BasicBlock*, const llvm::BasicBlock*>, 32> backedgesVector;
    llvm::FindFunctionBackedges(F, backedgesVector);
    std::set<std::pair<const llvm::BasicBlock*, const llvm::BasicBlock*> > backedges;
    backedges.insert(backedgesVector.begin(), backedgesVector.end());
    if (m_debug) {
        std::cout << "========================================" << std::endl;
    }
    for (llvm::Function::iterator bbi = F.begin(), bbe = F.end(); bbi != bbe; ++bbi) {
        llvm::BasicBlock *bb = &*bbi;
        std::set<llvm::BasicBlock*> preds;
        for (llvm::Function::iterator tmpi = F.begin(), tmpe = F.end(); tmpi != tmpe; ++tmpi) {
            if (isPred(&*tmpi, bb) && backedges.find(std::make_pair(&*tmpi, bb)) == backedges.end()) {
                if (m_debug) {
                    std::cout << bb->getName().str() << " has non-backedge predecessor " << tmpi->getName().str() << std::endl;
                }
                preds.insert(&*tmpi);
            }
        }
        std::set<llvm::Value*> trueSet;
        std::set<llvm::Value*> falseSet;
        bool haveStarted = false;
        for (std::set<llvm::BasicBlock*>::iterator i = preds.begin(), e = preds.end(); i != e; ++i) {
            TrueFalseMap::iterator it = m_map.find(*i);
            if (it == m_map.end()) {
                std::cerr << "Did not find condition information for predecessor " << (*i)->getName().str() << "!" << std::endl;
                exit(99999);
            }
            if (!haveStarted) {
                trueSet = it->second.first;
                falseSet = it->second.second;
                haveStarted = true;
            } else {
                // intersect
                trueSet = intersect(trueSet, it->second.first);
                falseSet = intersect(falseSet, it->second.second);
            }
        }
        if (preds.size() == 1) {
            llvm::BasicBlock *pred = *(preds.begin());
            // branch condition!
            if (!m_onlyLoopConditions || m_lcbs.find(pred) != m_lcbs.end()) {
                llvm::TerminatorInst *termi = pred->getTerminator();
                if (llvm::isa<llvm::BranchInst>(termi)) {
                    llvm::BranchInst *br = llvm::cast<llvm::BranchInst>(termi);
                    if (br->isConditional()) {
                        if (br->getSuccessor(0) == bb) {
                            // branch on true
                            trueSet.insert(br->getCondition());
                        } else {
                            // branch on false
                            falseSet.insert(br->getCondition());
                        }
                    }
                }
            }
            // assumes!
            if (!m_onlyLoopConditions) {
                for (llvm::BasicBlock::iterator insti = pred->begin(), inste = pred->end(); insti != inste; ++insti) {
                    if (llvm::isa<llvm::CallInst>(insti)) {
                        llvm::CallInst *ci = llvm::cast<llvm::CallInst>(insti);
                        llvm::Function *calledFunction = ci->getCalledFunction();
                        if (calledFunction != NULL) {
                            std::string functionName = calledFunction->getName().str();
                            if (functionName == "__kittel_assume") {
                                llvm::CallSite callSite(ci);
                                trueSet.insert(callSite.getArgument(0));
                            }
                        }
                    }
                }
            }
        }
        if (m_debug) {
            std::cout << "In " << bb->getName().str() << ":" << std::endl;
            std::cout << "TRUE: "; printSet(trueSet); std::cout << std::endl;
            std::cout << "FALSE: "; printSet(falseSet); std::cout << std::endl;
            if (++bbi != bbe) {
                std::cout << std::endl;
            }
            --bbi;
        }
        m_map.insert(std::make_pair(bb, std::make_pair(trueSet, falseSet)));
    }
    return false;
}
Esempio n. 29
0
File: set.c Progetto: SIEGE/siege
int main(void)
{
    char buf[1024];
    char* ptr;

    SGSet* set = sgSetCreate(_setCmp, NULL);

    printf("Example of SIEGE sets");
    printf("----------------------------------------\n");

    int option;
    do
    {
        printf("Select a set operation:\n");
        printf("+<elem> -- Add a new element\n");
        printf("-<elem> -- Delete an element\n");
        printf("?<elem> -- Query whether an element is present\n");
        printf("p       -- Print all elements in (strcmp) order\n");
        printf("pp      -- Pretty-print the set's search tree\n");
        printf("s       -- Print the set's tree in a compact s-expression form\n");         // yes, I was bored.
        printf("ss      -- Pretty print the set's tree in a compact s-expression form\n");  // ...very bored.
        printf("\n");
        printf("q        -- Quit the program\n");
        printf("----------------------------------------\n");
        printf("Selection: "); fflush(stdout);
        fgets(buf, sizeof(buf), stdin);
        printf("\n");

        trimNL(buf);
        if(strstr(buf, "+") == buf)
            option = '+';
        else if(strstr(buf, "-") == buf)
            option = '-';
        else if(strstr(buf, "?") == buf)
            option = '?';
        else if(!strcmp(buf, "p") || !strcmp(buf, "P"))
            option = 'p';
        else if(!strcmp(buf, "pp") || !strcmp(buf, "pP") || !strcmp(buf, "Pp") || !strcmp(buf, "PP"))
            option = 'P';
        else if(!strcmp(buf, "s") || !strcmp(buf, "S"))
            option = 's';
        else if(!strcmp(buf, "ss") || !strcmp(buf, "sS") || !strcmp(buf, "Ss") || !strcmp(buf, "SS"))
            option = 'S';
        else if(!strcmp(buf, "q") || !strcmp(buf, "Q"))
            option = 'q';
        else
            option = 0;

        ptr = skipSpace(buf + 1);
        switch(option)
        {
            case '+':
                if(!strlen(ptr))
                {
                    printf("Error -- element must be a non-empty string!\n");
                    break;
                }
                switch(insertItem(set, ptr))
                {
                    case 0: printf("Element '%s' already exists in the set!\n", ptr); break;
                    case 1: printf("Element '%s' successfully added!\n", ptr); break;
                    default: printf("Error adding element '%s' -- probably out of memory!\n", ptr);
                }
                break;
            case '-':
                if(!strlen(ptr))
                {
                    printf("Error -- element must be a non-empty string!\n");
                    break;
                }
                switch(removeItem(set, ptr))
                {
                    case 0: printf("There is no element '%s' in the set!\n", ptr); break;
                    case 1: printf("Element '%s' successfully removed!\n", ptr); break;
                    default: printf("Error removing element '%s'!\n", ptr);
                }
                break;
            case '?':
                if(!strlen(ptr))
                {
                    printf("Error -- element must be a non-empty string!\n");
                    break;
                }
                if(sgSetSearch(set, ptr))
                    printf("Element '%s' is present in the set!\n", ptr);
                else
                    printf("Element '%s' is *NOT* present in the set!\n", ptr);
                break;
            case 'p':
                printSet(set);
                break;
            case 'P':
                pprintSet(set);
                break;
            case 's':
                sprintSet(set, 0);
                break;
            case 'S':
                sprintSet(set, 1);
                break;
            case 'q':
                break; /* handled by the while() */
            default:
                printf("Invalid option '%s'!\n", trimSpace(buf));
                break;
        }
        printf("\n");
        fflush(stdout);
    }
    while(option != 'q');

    while(set->root)
        removeItem(set, set->root->item);
    sgSetDestroy(set);

    return 0;
}