Пример #1
0
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        printf("Usage: %s <number> <bit index>\n", argv[0]);
        return 0;
    }

    unsigned int number = (unsigned int) atoi(argv[1]);
    int i = atoi(argv[2]);

    printf("Number: %d (0x%x)\n", number, number);
    printf("Modifying bit: %d\n", i);

    // Check if bit i is set
    unsigned int result = isBitISet(number, i);
    printResult(i, number, result);

    // Set it
    number = setBit(number, i);

    // Make sure it was set
    result = isBitISet(number, i);
    printResult(i, number, result);

    // Clear bit
    number = clearBit(number, i);

    // Make sure it was cleared
    result = isBitISet(number, i);
    printResult(i, number, result);

    return 0;
}
Пример #2
0
int main()
{
    srand (time(NULL)); // Do not worry about this, but don't delete it
    int age = askForNumber("age");
    
    int favoriteNumbers[3];
    askForManyNumbers("your 3 favorite numbers", 3, favoriteNumbers);
    
    printf("Your age is: %d\n", age);
    printf("Your 3 favorite numbers are %d %d %d\n", favoriteNumbers[0], favoriteNumbers[1], favoriteNumbers[2]);
    
    int added = favoriteNumbers[0] + favoriteNumbers[1] + favoriteNumbers[2];
    int substracted = favoriteNumbers[0] - favoriteNumbers[1] - favoriteNumbers[2];
    int multiplied = favoriteNumbers[0] * favoriteNumbers[1] * favoriteNumbers[2];
    int divided = favoriteNumbers[0] / favoriteNumbers[1] / favoriteNumbers[2];
    
    printResult("added", added);
    printResult("substracted", substracted);
    printResult("multiplied", multiplied);
    printResult("divided", divided);
    
    int randomFavoriteNumber = favoriteNumbers[rand() % 3];
    printf("From your favorite numbers, the next lucky one is: %d\n", randomFavoriteNumber);
    printf("If you play the lottery, use the number %d\n", randomFavoriteNumber * age);
    
    return 0;
}
Пример #3
0
/**
 * Gets a matrix from the user and performs the given operation. Then prints the result.
 * @param op The matrix operation
 * @return An error string message if the operation couldn't be done, EMPTY_STRING if the
 * operation was performed.
 */
string oneOperandOperation(MatrixOperation& op)
{
	cout << "Operation " << op._name << " requires 1 operand matrix." << endl;
	IntMatrix result;

	switch (op._id)
	{
		case TRANS:
			printMatrix(result = getMatrix());
			result = result.trans();
			printResult(MATRIX, (void*) &result);
			break;
		case TRACE:
			printMatrix(result = getMatrix());
			if (result.isSquare())
			{
				int trace = result.trace();
				printResult(NUMBER, (void*)&trace);
				break;
			}
			else
			{
				return "The matrix isn't square";
			}
		default:
			break;
	}
	return EMPTY_STRING;
}
int main() {
    Solution so;
    printResult(so.zigzagLevelOrder(nullptr));
    printResult(so.zigzagLevelOrder(new TreeNode(1)));
    printResult(so.zigzagLevelOrder(new TreeNode(1, new TreeNode(2, new TreeNode(3), nullptr), nullptr)));
    printResult(so.zigzagLevelOrder(new TreeNode(1, new TreeNode(2, new TreeNode(3), nullptr), new TreeNode(2))));
    printResult(so.zigzagLevelOrder(new TreeNode(3, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7)))));
}
int main() {
    Solution so;

    printResult(so.generateTrees(0));
    printResult(so.generateTrees(1));
    printResult(so.generateTrees(2));
    printResult(so.generateTrees(3));
    printResult(so.generateTrees(4));
}
int main()
{
    /// INPUT START
    freopen("input.txt", "r", stdin);
    freopen("debug.txt", "w", stderr);
    int n;
    int m;
    //cout << "input conditions:\n";
    cin >> n >> m;

    vvd a(m, vd(n));
    vd b(m);
    vc type(m);
    vc sign(n);

    for (int i = 0; i < m; ++i)
    {
        cin >> type[i];
        for (int j = 0; j < n; ++j)
            cin >> a[i][j];
        cin >> b[i];
    }

    for (int i = 0; i < n; ++i)
    {
        cin >> sign[i];
    }

    vd c(n);
    for (int i = 0; i < n; ++i)
    {
        cin >> c[i];
    }
    /// INPUT END

    vvd dual_a;
    vd dual_b;
    vd dual_c;

    getCanonicalMatrix(a, b, c, sign, type);
    printTask(a, b, c);

    getDualProblem(a, b, c, dual_a, dual_b, dual_c);
    printTask(dual_a, dual_b, dual_c, "dual_task.txt");

    cout << "Simplex\n";
    printResult(linearProgramming::simplex(a, b, c), sign);
    cout << "\nAll vertexes\n";
    printResult(linearProgramming::allVertexesCheck(a, b, c), sign);
    cout << "\nDual problem simplex\n";
	printResult(linearProgramming::simplex(dual_a, dual_b, dual_c), sign, false);


    return 0;
}
Пример #7
0
int main(int argc, char* argv[])
{
    printResult(optimize("../sets/burma14.tsp"), 3323);
    printResult(optimize("../sets/ulysses16.tsp"), 6859);
    printResult(optimize("../sets/berlin52.tsp"), 7542);
    // assert(optimize("../sets/kroA100.tsp") == 21282);
    // assert(optimize("../sets/ch150.tsp") == 6528);
    // assert(optimize("../sets/gr202.tsp") == 40160);

    return 0;
}
int main(int argc, char* argv[]) {

	if (argc < 2 ) {
		printUsage();
		exit(2);
	}

	int samplecount = atoi(argv[1]);
	int threadId = 0, i = 0, index = 0;
	double mean_counteroverhead = 0, stddev_counteroverhead = 0,\
	       mean_threadoverhead  = 0, stddev_threadoverhead = 0,\
		   mean_threadswitchoverhead= 0, stddev_threadswitchoverhead = 0;

	double threadOverheadArray[samplecount];
	double threadswitchOverheadArray[samplecount];

	pthread_t aThread;

	mean_counteroverhead = getCounteroverhead(samplecount, &stddev_counteroverhead);

	// MEASURE THE THREAD CREATION TIME
	for ( index = 0; index < samplecount; index++) {
		start = count();
		threadId = pthread_create( &aThread, NULL, threadFunc, NULL);
		pthread_join(aThread, NULL);
		threadOverheadArray[index] = end-start-mean_counteroverhead;
	}

	mean_threadoverhead = getMeanStddev(threadOverheadArray, samplecount, &stddev_threadoverhead);
//	printResult(samplecount, mean_threadoverhead, stddev_threadoverhead, "THREAD CREATION TIME");
	printResult(samplecount, getDurationinMicroSec(mean_threadoverhead),\
	                         getDurationinMicroSec(stddev_threadoverhead),\
							 "THREAD CREATION TIME");

	// MEASURE THE THREAD CONTEXT SWITCH TIME
	for ( index = 0; index < samplecount; index++) {
		threadId = pthread_create( &aThread, NULL, threadFunc, NULL);
		start = count();
		pthread_join(aThread, NULL);
		threadswitchOverheadArray[index] = end-start-mean_counteroverhead;
	}

	mean_threadswitchoverhead = getMeanStddev(threadswitchOverheadArray, samplecount, &stddev_threadswitchoverhead);
	//printResult(samplecount, mean_threadswitchoverhead, stddev_threadswitchoverhead, "THREAD CONTEXT SWITCH TIME");
	printResult(samplecount, getDurationinMicroSec(mean_threadswitchoverhead),\
	                         getDurationinMicroSec(stddev_threadswitchoverhead),\
							 "THREAD CONTEXT SWITCH TIME");

	return 0;
}
Пример #9
0
int main()
{
	program.state = 3;
	program.foo = 4;

	int ret = test(&program);

	printResult(ret);

	ret = foo(6);

	printResult(ret);

	return foo(ret);
}
Пример #10
0
void	run(t_variable *_var)
{
  int		_end = 1;
  t_result	res[9];
  double	sommeCarre = 0; 
  double  max; 
  double  min;
  int		deg_lib = 0; 
  int i = 0;

  calcP(_var);
  loiBinomial(_var->p, _var);
  deg_lib = verifVal(_var, res);
  printResult(res, deg_lib);
  sommeCarre = calcCarre(res, deg_lib);
  printf ("\nloi choisie :\t\t\tB(100, %.4f)\n",_var->p);
  printf ("somme des carrés des écarts :\tX² = %.3f\n", sommeCarre);
  printf ("degrés de liberté :\t\tv = %d\n", (deg_lib - 2));
  while (i < 14 && _end != 0)
    {
      if (sommeCarre > donnees[deg_lib - 2].nb[i])
	       i++;
      else
	      {
      	  _end = 0;
      	  max = donnees[0].nb[i - 1];
      	  min = donnees[0].nb[i];
      	}
    }
  printf ("validité de l’ajustement :\t%.0f%% < P < %.0f%%\n", min, max);
}
Пример #11
0
int main(int argc, char *argv[]) {
	int i,j,k;
	if (argc<2) {
		fprintf(stderr, "Usage: dijkstra <filename>\n");
		fprintf(stderr, "Only supports matrix size is #define'd.\n");
	}
	//Open the adjacency matrix file
	FILE *fp;
	fp = fopen (argv[1],"r");
	/*Step 1: geting the working vertexs and assigning values*/
  	for (i=0;i<NUM_NODES;i++) {
    		for (j=0;j<NUM_NODES;j++) {
     			fscanf(fp,"%d",&k);
			AdjMatrix[i][j]= k;
    		}
  	}
	fclose(fp);
	chStart=0,chEnd=1999; //15 for small input; 1999 for large input
	if (chStart == chEnd) {
		printf("Shortest path is 0 in cost. Just stay where you are.\n");
		
	}else{
		startBarrier(&myBarrier);	/* Start barrier 	*/
		startThreads();			/* Start pthreads */	
	}
	printResult();
//}
	exit(0);
}
Пример #12
0
int dijksktra(int graph[V][V], int source)
{
    int dist[V];
    bool sptSet[V];
    int i;
    for(i=0;i<V;i++)
    {
        dist[i]=INT_MAX; // setting the distance to be maximum value of int (or Infinity)s
        sptSet[i]=false; // all nodes are not travelled
    }
    dist[source]=0; // setting the source node's distance = 0
    for(i=0;i<V;i++)
    {
        int u=minDistance(dist,sptSet); // To get the node with minimum distance which is unvisited
        sptSet[u]=true;
        for(int v=0;v<V;v++)
        {
            if(!sptSet[v] && graph[u][v] && dist[u]!=INT_MAX && dist[u]+graph[u][v]<dist[v])
            {
                dist[v]=dist[u]+graph[u][v]; // setting the distance of a node from a node which is already visited
            }
        }
    }
    printResult(dist,0);
    return 0;
}
Пример #13
0
vector RetriveCore::retrive(vector<string> files)
{
	FeatureExtract fe;
	Mat retriveF;
	
	vector< vector<int> > allLenSeq = read();
	Mat allGlobal = read();
	Mat allLocal = read();
	
	vector<string> cand;
	
	int rv = files.size();
	for(int i = 0; i < rv; i ++)
	{
		retriveF = fe.tomyFeature(files[i]);
		
		
		#ifdef FILTER_BY_LENGTH
		//the minist edit distance
		double* dist = distinct(rLenSeq, allLenSeq);
		cand = filterByLenSeq(cand, dist, allLenSeq);
		#endif
		
		Mat hogFeature = localFeature(retriveF);
		Mat local_code = spectralHash(hogFeature);
		cand = filterByCode(cand, local_code, allLocal);
		
		
		printResult(files[i], cand);
		cand.clear();
		retriveF.release();
	}
	
}
void Manager::Run()
{
 std::ofstream myfile;
 myfile.open("Output.txt");
 int input1, input2, targetOutput;
 for(int i=0; i<2000; ++i)
 {
  inputVals.clear();
  targetVals.clear();
  input1=rand()%2;
  input2=rand()%2;
  targetOutput=1;
  if(input1==input2) targetOutput=0;
  inputVals.push_back(input1);
  inputVals.push_back(input2);
  targetVals.push_back(targetOutput);
  myNet.feedForward(inputVals);
  myNet.backProp(targetVals);
  myNet.getResults(resultVals);
  myfile<<"Pass: "******"\n";
  std::cout<<"Input"<<std::endl;
  myfile<<"Input\n";
  print(inputVals, myfile);
  std::cout<<"TargetVals"<<std::endl;
  myfile<<"TargetVal\n";
  print(targetVals, myfile);
  std::cout<<"resultVals"<<std::endl;
  myfile<<"resultVal\n";
  printResult(resultVals, myfile);
  myfile<<"\n";
 }
 myfile.close();
}
Пример #15
0
// main program
int main()
{
    for (;;) {
        std::string input;

        std::getline(std::cin, input);
        if (input.empty()) break;       // empty input line exits the application 

        auto t = tokenize(input);
        try {
            auto result = parser<atomtype>::parse(t);
            for (auto &z : result) {
                // iterate over all comma-separated equations/expressions
                printResult(z);
            }

        }
        catch (parser<atomtype>::error &e) {
            auto pos = e.t.pos;
            std::cerr << std::endl << input << std::endl;
            std::cerr << std::string(pos, ' ') << "^~~~~ " << e.msg << std::endl;
        }
    }

    return 0;
}
Пример #16
0
int main(void)
{
	int change = 12; //거스름돈 21원을 만들어 보자.
	coinExchange(change);
	printResult(change);

}
Пример #17
0
// Check to see if the ball overcome the net
void Tp1Simulation1::checkNet()
{
    // Do nothing if the net has already been crossed
    if ( mIsNetCrossed )
        return;

    // Since we know that the net is not crossed yet, the first y > zone_length indicate crossing of net
    if ( mBallPosition.y() >= Tp1Constants::PLAYER_ZONE_LENGTH )
    {
        mIsNetCrossed = TRUE;

        // The net is between this position and the last one so we try to interpolate the z
        // if the position is within the limit of the court
        if ( mBallPosition.x() >= 0.0f && mBallPosition.x() <= Tp1Constants::COURT_WIDTH )
        {
            // The very last is == mBallPosition so the one before mBallPosition is size() - 2
            Vector lastBallPosition = mBallPositions[mBallPositions.size() - 2];
            FLOAT deltaY = mBallPosition.y() - lastBallPosition.y();
            FLOAT deltaZ = mBallPosition.z() - lastBallPosition.z();
            FLOAT ratioY = abs(mBallPosition.y() - Tp1Constants::PLAYER_ZONE_LENGTH) / deltaY;

            FLOAT estimatedZ = mBallPosition.z() + deltaZ * ratioY;

            if ( estimatedZ <= Tp1Constants::NET_HEIGHT )
            {
                cout << "================== Resultats ================== " << endl;
                cout << "  La balle ne traverse pas le filet (Echec)" << endl << endl;
                printResult();

                mBallPosition.z() = 0.0f; // This will stop the simulation at the next step
            }
        }
    }
}
Пример #18
0
/******************************************************************************
 * One task/thread per solution. Results are printed by main
 * after all of them have been computed.
 */
static void paralleSolutionsSequentialResults()
{

	//Create the containers to use and preallocate the memory needed
	auto scount = getSolutions().size();
	//one thread for each solution for now
	std::vector<std::thread> threads;
	threads.reserve(scount);
	//one future for each solution
	std::vector<std::future<long>> futures;
	futures.reserve(scount);

	// Grab the futures and create a thread for each solution;
	for(const auto &s : getSolutions() ){
		// get the function pointer for the solution
		auto fp = s.second;
		// and create a future and a thread for it through a prepared_task.
		std::packaged_task<long()> tsk(fp);
		futures.emplace_back(std::move(tsk.get_future()));
		threads.emplace_back(std::move(tsk));
	}

	// wait for the threads t finish the computations.
	for(auto &t: threads)
		t.join();

	// print the computed results (and compared them to the expected ones).
	for(size_t i=0; i < getSolutions().size(); ++i){
		const auto problem = getSolutions().at(i).first;
		long result = futures[i].get();

		printResult(problem, result);
	}
}
Пример #19
0
//Receive the N input test cases
void inputInt(int total){
	int X;
	if (ctr==total){
		printResult(result,ctr);
	}
	else{
		scanf("%d",&X);
		scanf("%c",&trash);
		if (X>0 && X<=100){
			scanf("%[^\n\t]s",input);
			char tmp[256]="";
			int checkY = toIntArray(arr,input,0,tmp,X);
			// calculate
			result[ctr]=0;
			calculate(result,arr,k);
			ctr++;
			k=0;
			if (checkY==0){
				printf("Please input Yn ( -100 <= Yn <= 100 )!\n");
				return;
			}
		}
		else{
			printf("Please input X ( 0 < X <= 100 )!");
			return;
		}
		inputInt(total);
	}
}
void *listenThread(void *arg)
{
    printf("Listen Thread: init sphinx...\n");
    if(!sphinxInit())
        exit(-1);
    
    if(!recordInit())
        exit(-1);
    
    while(!getExitApp())
    {
        if(getRun())
        {
            printf("Listen Thread: starting to decode...\n");
            pthread_barrier_wait(&startBarrier);
            if(!decode())
                exit(-1);
            printf("Listen Thread: decoding finished...\n");
            
            if (!printResult())
                exit(-1);
            
            pthread_barrier_wait(&endBarrier);
        } else {
			usleep(1000);
		}
    }
    
    recordClose();
    sphinxClose();
    
    printf("Listen thread terminated.\n");
    return NULL;
}
int main(void) {
  sort(blueOrders, n);
  sort(redOrders, m);
  solveDynamic();
  printResult();
  return 0;
}
Пример #22
0
void partition(int *result, int length)
{
    int len = length - 1;
    int i;
    while(len > 0)
    {
	if(result[len] == 1)
	{
	    (result[len - 1])++;
	    result[len] = 0;
	    len--;
	}
	else
	{
	    (result[len - 1])++;
	    (result[len])--;
	    for(i = result[len]; i > 0; i--)
	    {
		result[len] = 1;
		len++;
	    }
	    len--;
	}
	printResult(result, len + 1);
    }
}
Пример #23
0
void qfit::startFitClicked()
{
    if(filePath->text().isEmpty()) {
        appendLog("Select a file to open!");
        return;
    }
    double error = -1;

    // retrive error from the QLineEdit
    if(customError->isChecked()) {
        error = errorValue->text().toDouble();
        if(error <= 0.0) {
            appendLog("Custom error is not valid, a default one of 1.0 will be used");
            error = 1;
        }
    }

    if(Data::ReadFile(filePath->text().toLatin1().data(), xdata, ydata, yerrors, error)) {
        appendLog("Error opening file");
        return;
    }

    // start fittools
    delete fit;
    if(error <= 0)
        fit = new FitTools(xdata, ydata, yerrors, fit_type);
    else
        fit = new FitTools(xdata, ydata, error, fit_type);
    fit->Fit();
    printResult();

#ifdef Qwt6_FOUND
    plotData();
#endif
}
Пример #24
0
int main ( void )
{
/* Prototype Declarations */
void getData 	      (	float *num1, float *num2 ) ;
void printResult      (	float num1,
			float num2,	
			float result,
			int option ) ;
int getOption ( void ) ;

float calc ( int option, float num1, float num2 ) ;

/* Local Declarations */
	int option ;

	float num1 ;
	float num2 ;
	float result ;

/* Statements */
	option = getOption ( ) ;
	getData ( &num1, &num2 ) ;
	result = calc ( option, num1, num2 ) ;
	printResult ( num1, num2, result, option ) ;

return 0 ;
}	/* main */
void printResult(Node* leaf)
{
	Node* current = leaf;

	if (current && current->parent == NULL)
	{
		std::cout << "M = " << current->missionaries << " C = " << current->canibals << " B = " << current->boat << "\t";
		std::cout << "M = " << 3 - current->missionaries << " C = " << 3 - current->canibals << " B = " << 1 - current->boat << std::endl << std::endl;

		return;
	}

	if (current != NULL)
	{
		printResult(current->parent);

		if (current->boat == 1)
		{
			std::cout << "Leve " << current->missionaries - current->parent->missionaries << " M e " << current->canibals - current->parent->canibals << " C para a esquerda \t";
		}
		else
		{
			std::cout << "Leve " << (3 - current->missionaries) - (3 - current->parent->missionaries) << " M e " << (3 - current->canibals) - (3 - current->parent->canibals) << " C para a direita \t";;
		}

		std::cout << "ESQUERDA M = " << current->missionaries << " C = " << current->canibals << " B = " << current->boat << "\t\t";
		std::cout << "DIREITA M = " << 3 - current->missionaries << " C = " << 3 - current->canibals << " B = " << 1 - current->boat << std::endl << std::endl;
	}
}
void solveMissionariesCannibals()
{
	Node* root = (Node*) malloc(sizeof(struct Node));
	root->missionaries = 3;
	root->canibals = 3;
	root->boat = 1;
	root->parent = NULL;

	std::stack<Node*> nodes;
	std::vector<Node*> statesVisited;

	nodes.push(root);

	while (nodes.empty() == false)
	{
		Node* currentNode = nodes.top();
		nodes.pop();

		statesVisited.push_back(currentNode);

		if (currentNode->missionaries == 0 && currentNode->canibals == 0 && currentNode->boat == 0)
		{
			printResult(currentNode);
		}

		addSucessorsToStack(nodes, currentNode, statesVisited);
	}
}
Пример #27
0
int main(int argc,char **argv) {
	sort(NUMS, SIZE);

	printResult();

	return EXIT_SUCCESS;
}
Пример #28
0
int main()
{
    printf("\n\n");  bool result1 = test1();
    printf("\n\n");  bool result2 = test2();
    printf("\n\n");  bool result3 = test3();
    printf("\n\n");  bool result4 = test4();
    
    
    printf("\n\n****** TEST RESULTS ******\n");
    printResult(result1, 1);
    printResult(result2, 2);
    printResult(result3, 3);
    printResult(result4, 4);
    printf("\n\n");
    
    return 0;
}
Пример #29
0
int main(int argv, char **argc)
{

  if(argv != 3){
    printf("Wrong command.\n");
    return 1;
  }

  srand(time(NULL));

  int len = atoi(argc[2]);
  int i;
  clock_t begin, end;
  double time_spent;

  if(len < 1){
    printf("The number of elements must be larger than 0.\n");
    return 1;
  }

  mytype *A = malloc(len*sizeof(mytype));
  MaxSub mySub, mySub2;

  //generate data for computation
  generateData(A, argc[1], -1000, 1000, len);

  //for(i = 0; i < len; i++) printf("%d ", A[i]);
  printf("\n");

  printf("Using recursive method\n");
  begin = clock();
  mySub = findMaxSubarray(A, 0, len-1);
  end = clock();
  time_spent = (double) (end - begin)/CLOCKS_PER_SEC;
  printResult(mySub, time_spent);

  printf("\nUsing dynamic method\n");
  begin = clock();
  mySub2 = findMaxSub_Dynamic(A, len);
  end = clock();
  time_spent = (double) (end - begin)/CLOCKS_PER_SEC;
  printResult(mySub, time_spent);

  free(A);

}//end main
int main(void) {
  calcDist();
  solve();
  printResult();
  printf("\nДиагонали от минималния разрез: ");
  writeCut(1, n-1);
  return 0;
}