Exemple #1
0
void TestCanvas::test(GiCanvas* canvas, int bits, int n, bool randStyle)
{
    s_randStyle = randStyle;
    if ((bits & kDynCurves) == 0 || !s_inited) {
        initRand();
    }
    
    if (bits & kRect)
        testRect(canvas, n * 2);
    if (bits & kLine)
        testLine(canvas, n * 2);
    if (bits & kTextAt)
        testTextAt(canvas, n);
    if (bits & kEllipse)
        testEllipse(canvas, n * 2);
    if (bits & kQuadBezier)
        testQuadBezier(canvas, n);
    if (bits & kCubicBezier)
        testCubicBezier(canvas, n);
    if (bits & kPolygon)
        testPolygon(canvas, n);
    if (bits & kClearRect)
        canvas->clearRect(100, 100, 200, 200);
    if (bits & kClipPath)
        testClipPath(canvas, n);
    if (bits & kHandle)
        testHandle(canvas, n);
    if (bits & kDynCurves)
        testDynCurves(canvas);
}
Exemple #2
0
void TestCanvas::test(GiCanvas* canvas, int bits, int n, bool randStyle)
{
    s_randStyle = randStyle;
    if ((bits & 0x400) == 0 || !s_inited) {
        initRand();
    }
    
    if (bits & 0x01)
        testRect(canvas, n);
    if (bits & 0x02)
        testLine(canvas, n);
    if (bits & 0x04)
        testTextAt(canvas, n);
    if (bits & 0x08)
        testEllipse(canvas, n);
    if (bits & 0x10)
        testQuadBezier(canvas, n);
    if (bits & 0x20)
        testCubicBezier(canvas, n);
    if (bits & 0x40)
        testPolygon(canvas, n);
    if (bits & 0x80)
        canvas->clearRect(100, 100, 200, 200);
    if (bits & 0x100)
        testClipPath(canvas, n);
    if (bits & 0x200)
        testHandle(canvas, n);
    if (bits & 0x400)
        testDynCurves(canvas);
}
Exemple #3
0
int main()
{
  initRand();
  const int size=26;
  int a[size], b[size], out[size];
    
  // make up some random permuations
  shuffle(a, size);
  shuffle(b, size);

  for (int i=0; i<200; i++) {
    print((char *)"B", b, size);
    print((char *)"A", a, size);
    pmx(a, b, out, 3, size);
    print((char *)"OUT", out, size);
    printf("\n");
    if (!isPermP(out, size)) {
      printf("ERROR: NOT PERM: ");
      print((char *)"", out, size);
    }
  }
     

  return 0;
}
void Robot::mutate() {
    initRand();
    //check mutation rate, randomly mutate bits with that percentage chance of mutation
    uint_least64_t mask = 0x01;
    for (int i = 0; i<48; i++) {
        if ((rand() % 100) < Robot::mutationRate) {
            chromosome = chromosome ^ mask;
        }
        mask = mask << 1;
    }
}
int main( void ) {
    initRand();

    getOutput_test();
    weightedSumsAndOutput_test();
    forwardPropagate_test();
    backPropagate_test();
    updateWeights_test();
    train_test();

    return EXIT_SUCCESS;
}
Exemple #6
0
Data MatrixGraph::tabuSearch(uint tabuListSize, uint iterations)
{
	clock_t overallTime = clock();
	initRand();
	if (!iterations)
		iterations = 1 << 10;
	//iterations = 50;
	stringstream results;
	vector<uint> currentPath, bestPath;
	currentPath.reserve(vertexNumber), bestPath.reserve(vertexNumber);
	//TabuArray tabuList(vertexNumber, tabuListSize);
	TabuList tabuList(tabuListSize);
	uint currentCost = 0, bestCost = 0, diverseLimit = (iterations >> 4) + 1, noChange = 0;

	//	1 - Create an initial solution(could be created randomly), now call it the current solution.
	for (uint i = 0; i < vertexNumber; ++i)
		currentPath.push_back(i);
	currentCost = calculateCost(currentPath);
	bestPath = currentPath;
	bestCost = currentCost;

	for (uint i = 0; i < iterations; ++i)
	{
		//	2 - Find the best neighbor of the current solution by applying certain moves.

		currentCost = getBestNeighbour(tabuList, currentPath);

		//	3 - If the best neighbor is reached my performing a non - tabu move, accept as the new current solution.
		// else, find another neighbor(best non - tabu neighbour).
		if (currentCost < bestCost)
		{
			bestPath = currentPath;
			bestCost = currentCost;
			noChange = 0;
		}
		else
		{
			if (++noChange > diverseLimit)
			{
				random_shuffle(currentPath.begin(), currentPath.end());
				currentCost = calculateCost(currentPath);
				tabuList.clear();
				noChange = 0;
			}
		}
	}
	//	4 - If maximum number of iterations are reached(or any other stopping condition), go to 5, else go to 2.
	//	5 - Globally best solution is the best solution we found throughout the iterations.
	double duration = (clock() - overallTime) / (double)CLOCKS_PER_SEC;
	results << "Koszt drogi: " << bestCost << "\nCalkowity czas trwania: " << duration << " sekund\n";
	return Data(bestPath, bestCost, results.str(), duration);
}
Exemple #7
0
void benchAll(bool useSelect = true)
{
	const size_t lp = 100000;
	uint64_t ret = 0;
	for (size_t bitLen = 16; bitLen < 33; bitLen++) {
		const size_t bitSize = size_t(1) << bitLen;
		Vec64 vec;
		initRand(vec, bitSize / (sizeof(uint64_t) * 8));
		double baseClk = getDummyLoopClock(lp, bitLen);
		ret += bench<T>(&vec[0], vec.size(), lp, bitLen, baseClk, useSelect);
	}
	printf("ret=%x\n", (int)ret);
}
Exemple #8
0
/** 
 * Représente une grille.
 * @param grid Grille à remplir
 * @param argc Nombres d'arguments du main
 * @param gridStr Grille sous forme de chaîne
 */
void Grille(t_Case grid[N][N],int argc, char * gridStr[]){
    int i, j;
    int nb_bonus[2] = {0};

    initRand();
    initGrid(grid);

    // Affichage grille aléatoire ou définis par l'utilisateur
    printf("----------------------------------------------------\n");
    printf("|");
    if(argc == 1){
    
        for (i = 0; i < N; i++)
        {
            for (j = 0; j < N; j++)
            {   
                getCase(grid, i, j, nb_bonus);
            }
            printf("\n----------------------------------------------------\n");
            if(i < N-1 )printf("|");
        }
    }else if(argc == 2){

        if(strlen(gridStr[1]) >= 16){
            gridStr[16] = '\0';

            for (i = 0; i < 16; i++)
            {   
                // Vérifie que le caractère courant est valide
                if(!isalpha(gridStr[1][i])){
                    printf("\nErreur caractère invalide !\n");
                    exit(0);
                }

                getCaseFromStr(grid, nb_bonus, gridStr[1], i);
                if((i - 3) % 4 == 0){ 
                    printf("\n----------------------------------------------------\n");
                     if(i < 12)printf("|");
                }
            }

        }else{
            printf("Chaîne de caractère trop courte.");
        }

    }else{
        printf("Erreur nombre d'arguments incorrect !\nNormal usage: ./bin/ruzzleSolver [a-z]*16\n");
        exit(0);
    }
}
Robot::Robot(const Robot& rbt1, const Robot& rbt2) {
    initRand();
    //check to see if the chromosomes are the same
    if (rbt1.chromosome == rbt2.chromosome) {
        chromosome = rbt1.chromosome;
    } else {
        uint_least64_t mask = 0x01;
        int pos = rand()%48;
        for (int i = 0; i<pos; i++) mask = (mask << 1 | 0x01);
        chromosome = (rbt1.chromosome & mask) | (rbt2.chromosome & ~mask);
    }
    
    //perform a random mutation on the new chromosome based on mutationRate
    mutate();
}
Exemple #10
0
int
main (int argc, const char **argv) {
    printLicense();

    if (argc < 2) {
        printUsage();
        return 0;
    }

    initStartTime();
    // parse input
    cmdArguments    args = parseInput (argc, argv);
    // init random seed
    initRand();
    // go
    run (&args);
}
Exemple #11
0
uint_least64_t Robot::randomChromosome() {
    initRand();
   
    // get three 16 bit random numbers
    // the & 0xffff makes sure we only get the last 16 bits
    // any other bits before the last 16 are erased by the bitwise AND
    uint_least64_t n1 = rand() & 0xffff;
    uint_least64_t n2 = rand() & 0xffff;
    uint_least64_t n3 = rand() & 0xffff;

    // now shift n3 to the left 16 bits: n3 << 16
    // bitwise OR it with n2 to fill in the 16 bits we just vacated: | n2
    // shift the combined new int 16 bits to the left: << 16
    // bitwise OR it with n1 to fill in the 16 bits we just vacated: | n1
    uint_least64_t chromo = ((n3 << 16) | n2) << 16 | n1;

    return chromo;
}
Exemple #12
0
int main()
{
    FILE * f = fopen("matrix.txt","r");
    readFromAdjMatrix(f);
    printAdjMatrix();
    initRand();

    bfs(0);
    dfs(0);
    dfsRecurs(0);

    prim(0);
    dijkstra(0);
    bellmanFord(0);
    kruskal();

    vertexCover(adjMatrix);

    return 0;
}
Exemple #13
0
int main() {
  long i;
  long isum;
  float fsum;

  initRand();

  isum = 0L;
  for (i = 0; i < ITERATIONS; i++) {
    isum += getRand(10);
  }
  printf("getRand() Average %d\n", (int) (isum / ITERATIONS));

  fsum = 0.0;
  for (i = 0; i < ITERATIONS; i++) {
    fsum += getSRand();
  }
  printf("getSRand() Average %f\n", (fsum / (float) ITERATIONS));

  return 0;
}
int main( int argc, char *argv[] ) {
    int numInputs;
    Layer *hiddenLayer, *outputLayer;
    TestCase testCase;
    int i;

    initRand();

    if( !processArguments( argc, argv ) ) {
        fprintf( stderr, "Usage: main [-r, -t] [node definition file] [input file, training file]\n" );
        exit( EXIT_FAILURE );
    }

    numInputs = buildLayers( &hiddenLayer, &outputLayer );
    if( !numInputs ) {
        exit( EXIT_FAILURE );
    }

    getDefaultTestCase( numInputs, outputLayer->numNodes, &testCase );

    if( trainingFlag ) {
        for( i = 0; i < 1000; ++i ) {
            populateNextTestCase( &testCase );
            train( &testCase, hiddenLayer, outputLayer );
        }

        if( !persistWeights( numInputs, hiddenLayer, outputLayer ) ) {
            exit( EXIT_FAILURE );
        }
    } else {
        while( populateNextTestCase( &testCase ) == NEW_INPUT ) {
            forwardPropagate( testCase.inputs, hiddenLayer, outputLayer );
            printTestResults( testCase.inputs, outputLayer, testCase.desiredOutputs );
        }
    }

    exit( EXIT_SUCCESS );
}
Exemple #15
0
int main(int argc, char* argv[]){
  
int len = argc - 1;
int k;
combo = malloc(sizeof(int)*len);
guess = malloc(sizeof(int)*len);

comp = len;
//combo[0] ist höchstwertige Stelle

for(k=0; k < len; k++){
  combo[k] = atoi(argv[k+1]);
}

for(k = 0; k < len; k++){
  initRand(k);
}

while(loop == 1){
  increment(len - 1);
}
return 0;
}
Exemple #16
0
CItemToEat::CItemToEat():_rangeX(0), _rangeY(0){initRand();}
Exemple #17
0
int main( int argc, const char** argv)
{
	try
	{
		if (argc < 3)
		{
			throw std::runtime_error( "missing arguments <nof inserts> <nof queries>");
		}
		unsigned int nofInserts;
		unsigned int nofQueries;
		try
		{
			nofInserts = strus::utils::toint( argv[1]);
			nofQueries = strus::utils::toint( argv[2]);
		}
		catch (const std::exception& e)
		{
			throw std::runtime_error( std::string("bad values for arguments <nof inserts> <nof queries> (2 non negative integers expected): ") + e.what());
		}
		initRand();
		typedef strus::StringMap<strus::Index> TestMap;
		TestMap testmap;
		conotrie::CompactNodeTrie origmap;
		std::vector<std::string> keyar;

		std::size_t ii = 0;
		for (; ii<nofInserts; ++ii)
		{
			std::string key;
			do
			{
				key = randomKey( 32);
			}
			while (testmap.find(key) != testmap.end());

			testmap[ key] = ii+1;
			keyar.push_back( key);
		}
		testmap.clear();

		std::clock_t start;
		double duration;
		start = std::clock();

		for (ii=0; ii<nofInserts; ++ii)
		{
			testmap[ keyar[ ii]] = ii+1;
		}
		duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
		std::cerr << "inserted " << nofInserts << " keys in STL map in " << doubleToString(duration) << " seconds" << std::endl;

		start = std::clock();
		for (ii=0; ii<nofInserts; ++ii)
		{
			origmap.set( keyar[ ii].c_str(), ii+1);
		}
		duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
		std::cerr << "inserted " << nofInserts << " keys in variable size node tree in " << doubleToString(duration) << " seconds" << std::endl;

		start = std::clock();
		for (ii=0; ii<nofQueries; ++ii)
		{
			unsigned int keyidx = RANDINT(0,nofInserts);
			TestMap::const_iterator
				mi = testmap.find( keyar[ keyidx]);
			if (mi == testmap.end() || mi->second != (strus::Index)keyidx+1)
			{
				throw std::logic_error("TESTMAP LOOKUP FAILED");
			}
		}
		duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
		std::cerr << "queried boost unordered map with " << nofQueries << " random selected keys in " << doubleToString(duration) << " seconds" << std::endl;

		start = std::clock();
		for (ii=0; ii<nofQueries; ++ii)
		{
			unsigned int keyidx = RANDINT(0,nofInserts);
			conotrie::CompactNodeTrie::NodeData val;
			if (!origmap.get( keyar[ keyidx].c_str(), val)
			||  val != keyidx+1)
			{
				throw std::runtime_error( "VARIABLE SIZE NODE LOOKUP FAILED");
			}
		}
		duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
		std::cerr << "queried variable size node tree " << nofQueries << " random selected keys in " << doubleToString(duration) << " seconds" << std::endl;

		TestMap::const_iterator
			ti = testmap.begin(), te = testmap.end();

		for (; ti != te; ++ti)
		{
			conotrie::CompactNodeTrie::NodeData val;
			if (!origmap.get( ti->first, val))
			{
				throw std::runtime_error( std::string( "inserted key '") + ti->first + "' disapeared in variable size node tree");
			}
		}

		conotrie::CompactNodeTrie::const_iterator
			oi = origmap.begin(), oe = origmap.end();
		std::size_t oidx = 0;
		for (; oi != oe; ++oi,++oidx)
		{
			TestMap::const_iterator ti = testmap.find( oi.key());
			if (ti == testmap.end())
			{
				throw std::runtime_error( std::string( "non existing key '") + oi.key() + "' found in variable size node tree");
			}
			else if (ti->second != (strus::Index)oi.data())
			{
				std::ostringstream dt;
				dt << ti->second << " != " << oi.data();
				throw std::runtime_error( std::string( "inserted key '") + oi.key() + "' has not the expected value (" + dt.str() + ")");
			}
		}
		if (oidx != nofInserts)
		{
			std::ostringstream dt;
			dt << oidx << " != " << nofInserts;
			throw std::runtime_error( std::string( "number of inserts in variable size node tree does not match (") + dt.str() + ")");
		}
		std::cerr << "checked inserted content in maps. OK" << std::endl;
		return 0;
	}
	catch (const std::exception& err)
	{
		std::cerr << "EXCEPTION " << err.what() << std::endl;
	}
	return -1;
}
Exemple #18
0
/**
 * \fn void voiture(int numero, int voie)
 * \brief Fonction realisee par chaque processus (chaque voiture).
 * Comprend 2 phases :
 * - Initialisation de la voiture, de deux facons :
 *  - Avec une voie aleatoire
 *  - Avec une voie choisie par l'utilisateur
 * - Parcours de la voie par la voiture.
 *
 * \param numero Le numero de la voiture.
 * \param voie Le numero de la voie. Peut valoir :
 * - -1 : la voiture prendra une voie dont le numero est genere aleatoirement (1<=voie<=12)
 * - >0 : la voiture prendra la voie correspondant a ce numero
 */
void voiture(int numero, int voie)
{
	Voiture v;
	Requete req;
	Reponse rep;
	int croisement_numero, croisement_voie, i;

	v.numero = numero;

	if (voie == -1) {
		initRand();
		int voie_random = rand()%12+1;
		v.voie = &voies[voie_random-1];
	} else
		v.voie = &voies[voie-1];

	P(MUTEX);
	constructionRequete(&req, &v, 0, v.voie->numero, 0, MESSARRIVE);
	affichageRequete(&req);
	msgsnd(msgid,&req,tailleReq,0);
	V(MUTEX);

	for (i=0 ; i < 6 ; i++) {
		croisement_numero = v.voie->sem_num[i];
		croisement_voie = v.voie->croisements[i];

		if (croisement_numero == -1) break;

		P(MUTEX);
		maj_position(&v, croisement_numero, PASTRAVERSE);
		constructionRequete(&req, &v, croisement_numero, croisement_voie, PASTRAVERSE, MESSDEMANDE);
		affichageRequete(&req);
		V(MUTEX);

		do {
			msgsnd(msgid,&req,tailleReq,0);
			msgrcv(msgid,&rep,tailleRep,getpid(),0);
		} while (rep.autorisation == 0);

		P(MUTEX);
		maj_position(&v, croisement_numero, TRAVERSE);
		constructionRequete(&req, &v, croisement_numero, croisement_voie, TRAVERSE, MESSTRAVERSE);
		affichageRequete(&req);
		msgsnd(msgid,&req,tailleReq,0);
		V(MUTEX);

		sleep(rand()%MAXPAUSE);

		P(MUTEX);
		maj_position(&v, croisement_numero, ATRAVERSE);
		constructionRequete(&req, &v, croisement_numero, croisement_voie, ATRAVERSE, MESSATRAVERSE);
		affichageRequete(&req);
		msgsnd(msgid,&req,tailleReq,0);
		V(MUTEX);
	}

	P(MUTEX);
	constructionRequete(&req, &v, 0, v.voie->numero, 0, MESSSORT);
	affichageRequete(&req);
	msgsnd(msgid,&req,tailleReq,0);
	V(MUTEX);
}
Exemple #19
0
void
RandHelper::initRandGlobal(std::mt19937* which) {
    OptionsCont& oc = OptionsCont::getOptions();
    initRand(which, oc.getBool("random"), oc.getInt("seed"));
}
Exemple #20
0
void TestCanvas::testDynCurves(GiCanvas* canvas)
{
    static float x1, y1, x2, y2, x3, y3, x4, y4;
    static float xy[2 * (3 * 100 + 1)];
    static int n = 0;
    
    if (!s_inited) {
        initRand();
    }
    if (n == 0) {
        x1 = randFloat(100.f, 400.f);
        y1 = randFloat(100.f, 400.f);
        x2 = x1 + randFloat(-20.f, 20.f);
        y2 = y1 + randFloat(-20.f, 20.f);
        x3 = x2 + randFloat(-20.f, 20.f);
        y3 = y2 + randFloat(-20.f, 20.f);
    }
    else if (n == sizeof(xy)/sizeof(xy[0])) {
        for (int i = 0; i + 6 < n; i++) {
            xy[i] = xy[i + 6];
        }
        n -= 6;
    }
    x4 = x3 + randFloat(-20.f, 20.f);
    y4 = y3 + randFloat(-20.f, 20.f);
    if (x4 < 0 || y4 < 0 || x4 > 2048 || y4 > 2048) {
        n = 0;
        return;
    }
    
    canvas->beginPath();
    
    if (n >= 8) {
        canvas->moveTo(xy[0], xy[1]);
        for (int i = 2; i + 5 < n; i += 6) {
            canvas->bezierTo(xy[i], xy[i+1],
                            xy[i+2], xy[i+3], xy[i+4], xy[i+5]);
        }
    }
    else {
        canvas->moveTo(x1, y1);
        xy[0] = x1;
        xy[1] = y1;
        n = 2;
    }
    
    canvas->bezierTo(x2, y2, x3, y3, x4, y4);
    canvas->drawPath(true, false);
    
    xy[n++] = x2;
    xy[n++] = y2;
    xy[n++] = x3;
    xy[n++] = y3;
    xy[n++] = x4;
    xy[n++] = y4;
    
    x1 = x2; y1 = y2;                   // P2
    x2 = 2 * x4 - x3;                   // Q2=2P4-P3
    y2 = 2 * y4 - y3;
    x3 = 4 * (x4 - x3) + x1;            // Q3=4(P4-P3)+P2
    y3 = 4 * (y4 - y3) + y1;
    x1 = x4; y1 = y4;                   // Q1=P4
}
Exemple #21
0
Maze::Maze() : Board(Maze::DEFAULT_ROWS, Maze::DEFAULT_COLS) {
    initRand();
    setupMaze();    
}
int main(int argc, char** argv)
{
  for (int i = 1; i < argc; i++) {

    if(process_command_line_option(argc, argv, &i) == 0){
      continue;
    }   

    if( strcmp(argv[i], "--tol") == 0){
      float tmpf;
      if (i+1 >= argc){
        usage(argv);
      }
      sscanf(argv[i+1], "%f", &tmpf);
      if (tmpf <= 0){
        printf("ERROR: invalid tol(%f)\n", tmpf);
        usage(argv);
      }
      tol = tmpf;
      i++;
      continue;
    }

    if( strcmp(argv[i], "--cpu_prec") == 0){
      if (i+1 >= argc){
        usage(argv);
      }
      cpu_prec= get_prec(argv[i+1]);
      i++;
      continue;
    }

    printf("ERROR: Invalid option:%s\n", argv[i]);
    usage(argv);
  }

  if (prec_sloppy == QUDA_INVALID_PRECISION){
    prec_sloppy = prec;
  }
  if (link_recon_sloppy == QUDA_RECONSTRUCT_INVALID){
    link_recon_sloppy = link_recon;
  }


  // initialize QMP or MPI
#if defined(QMP_COMMS)
  QMP_thread_level_t tl;
  QMP_init_msg_passing(&argc, &argv, QMP_THREAD_SINGLE, &tl);
#elif defined(MPI_COMMS)
  MPI_Init(&argc, &argv);
#endif

  // call srand() with a rank-dependent seed
  initRand();

  display_test_info();

  int ret = invert_test();

  display_test_info();


  // finalize the communications layer
#if defined(QMP_COMMS)
  QMP_finalize_msg_passing();
#elif defined(MPI_COMMS)
  MPI_Finalize();
#endif

  return ret;
}
Exemple #23
0
CItemToEat::CItemToEat(unsigned int rangeX, unsigned int rangeY): _rangeX(rangeX), _rangeY(rangeY)
{
    initRand();
}
Exemple #24
0
CItemToEat::CItemToEat(const CPoint& newPoint)
{
    _itemsToEat.push_back(newPoint);
    initRand();
}
int main( int argc, const char** argv)
{
	try
	{
		initRand();

		g_errorBuffer = strus::createErrorBuffer_standard( 0, 1, NULL/*debug trace interface*/);
		if (!g_errorBuffer)
		{
			std::cerr << "construction of error buffer failed" << std::endl;
			return -1;
		}
		else if (argc > 1)
		{
			std::cerr << "too many arguments" << std::endl;
			return 1;
		}
		unsigned int documentSize = 100;

		strus::local_ptr<strus::PatternMatcherInterface> pt( strus::createPatternMatcher_std( g_errorBuffer));
		if (!pt.get()) throw std::runtime_error("failed to create pattern matcher");
		strus::local_ptr<strus::PatternMatcherInstanceInterface> ptinst( pt->createInstance());
		if (!ptinst.get()) throw std::runtime_error("failed to create pattern matcher instance");
		createPatterns( ptinst.get(), testPatterns);
		ptinst->compile();

		if (g_errorBuffer->hasError())
		{
			throw std::runtime_error( "error creating automaton for evaluating rules");
		}
		Document doc = createDocument( 1, documentSize);
		std::cerr << "starting rule evaluation ..." << std::endl;

		// Evaluate results:
		std::vector<strus::analyzer::PatternMatcherResult> 
			results = processDocument( ptinst.get(), doc);

		// Verify results:
		std::vector<strus::analyzer::PatternMatcherResult>::const_iterator
			ri = results.begin(), re = results.end();

		typedef std::pair<std::string,unsigned int> Match;
		std::set<Match> matches;
		for (;ri != re; ++ri)
		{
			matches.insert( Match( ri->name(), ri->ordpos()));
		}
		std::set<Match>::const_iterator li = matches.begin(), le = matches.end();
		for (; li != le; ++li)
		{
			std::cout << "MATCH " << li->first << " -> " << li->second << std::endl;
		}
		unsigned int ti=0;
		for (; testPatterns[ti].name; ++ti)
		{
			unsigned int ei=0;
			for (; testPatterns[ti].results[ei]; ++ei)
			{
				std::cout << "CHECK " << ti << ": " << testPatterns[ti].name << " -> " << testPatterns[ti].results[ei] << std::endl;
				std::set<Match>::iterator
					mi = matches.find( Match( testPatterns[ti].name, testPatterns[ti].results[ei]));
				if (mi == matches.end())
				{
					char numbuf[ 64];
					::snprintf( numbuf, sizeof(numbuf), "%u", testPatterns[ti].results[ei]);
					throw std::runtime_error( std::string("expected match not found '") + testPatterns[ti].name + "' at ordpos " + numbuf);
				}
				else
				{
					matches.erase( mi);
				}
			}
		}
		if (!matches.empty())
		{
			std::set<Match>::const_iterator mi = matches.begin(), me = matches.end();
			for (; mi != me; ++mi)
			{
				std::cerr << "unexpected match of '" << mi->first << "' at ordpos " << mi->second << std::endl;
			}
			throw std::runtime_error( "more matches found than expected");
		}
		if (g_errorBuffer->hasError())
		{
			throw std::runtime_error("error matching rule");
		}
		std::cerr << "OK" << std::endl;
		delete g_errorBuffer;
		return 0;
	}
	catch (const std::runtime_error& err)
	{
		if (g_errorBuffer->hasError())
		{
			std::cerr << "error processing pattern matching: "
					<< g_errorBuffer->fetchError() << " (" << err.what()
					<< ")" << std::endl;
		}
		else
		{
			std::cerr << "error processing pattern matching: "
					<< err.what() << std::endl;
		}
	}
	catch (const std::bad_alloc&)
	{
		std::cerr << "out of memory processing pattern matching" << std::endl;
	}
	delete g_errorBuffer;
	return -1;
}
Exemple #26
0
Maze::Maze(const int ROWS, const int COLS) : Board(ROWS, COLS) {
    initRand();
    setupMaze();
}    
Exemple #27
0
int find_tsp_solution(int num, DTYPE *cost, int *ids, int start, int end, DTYPE *total_len, char *err_msg) {
    int   i, j;
    int   istart = 0;
    int   jstart = 0;
    int   iend = -1;
    int   jend = -1;
    int   rev = 0;
    TSP   tsp;
    int64_t  seed = -314159L;
    DTYPE blength;

    PGR_DBG("sizeof(int64_t)=%d", (int)sizeof(int64_t));

    initRand((int) seed);

#ifdef DEBUG
    char bufff[2048];
    int nnn;
    PGR_DBG("---------- Matrix[%d][%d] ---------------------\n", num, num);
    for (i = 0; i < num; i++) {
        sprintf(bufff, "%d:", i);
        nnn = 0;
        for (j = 0; j < num; j++) {
            nnn += sprintf(bufff + nnn, "\t%.4f", cost[i * num + j]);
        }
        PGR_DBG("%s", bufff);
    }
#endif

    /* initialize tsp struct */
    tsp.n = num;
    tsp.dist   = NULL;
    tsp.iorder = NULL;
    tsp.jorder = NULL;
    tsp.border = NULL;

    if (!(tsp.iorder =(int*) palloc((size_t) tsp.n * sizeof(int)))   ||
        !(tsp.jorder =(int*) palloc((size_t) tsp.n * sizeof(int)))   ||
        !(tsp.border =(int*) palloc((size_t) tsp.n * sizeof(int)))   ) {
            elog(FATAL, "Memory allocation failed!");
            return -1;
        }

    tsp.dist = cost;
    tsp.maxd = 0;
    for (i=0; i < tsp.n * tsp.n; i++) {
        tsp.maxd = MAX(tsp.maxd, cost[i]);
    }

    /* identity permutation */
    for (i = 0; i < tsp.n; i++) tsp.iorder[i] = i;

    tsp.bestlen = pathLength(&tsp);
    for (i = 0; i < tsp.n; i++) tsp.border[i] = tsp.iorder[i];

    PGR_DBG("Initial Path Length: %.4f", tsp.bestlen);

    /*
     * Set up first eulerian path iorder to be improved by
     * simulated annealing.
     */
    if (findEulerianPath(&tsp))
        return -1;

    blength = pathLength(&tsp);
    if (blength < tsp.bestlen) {
        tsp.bestlen = blength;
        for (i = 0; i < tsp.n; i++) tsp.border[i] = tsp.iorder[i];
    }

    PGR_DBG("Approximated Path Length: %.4f", blength);

    annealing(&tsp);

    *total_len = pathLength(&tsp);
    PGR_DBG("Final Path Length: %.4f", *total_len);

    *total_len = tsp.bestlen;
    for (i = 0; i < tsp.n; i++) tsp.iorder[i] = tsp.border[i];
    PGR_DBG("Best Path Length: %.4f", *total_len);

    //  reorder ids[] with start as first

#ifdef DEBUG
    for (i = 0; i < tsp.n; i++) {
        PGR_DBG("i: %d, ids[i]: %d, io[i]: %d, jo[i]: %d, jo[io[i]]: %d",
            i, ids[i], tsp.iorder[i], tsp.jorder[i], tsp.jorder[tsp.iorder[i]]);
    }
#endif

    //  get index of start node in ids
    for (i=0; i < tsp.n; i++) {
        if (ids[i] == start) istart = i;
        if (ids[i] == end)   iend = i;
    }
    PGR_DBG("istart: %d, iend: %d", istart, iend);

    //  get the idex of start in iorder
    for (i=0; i < tsp.n; i++) {
        if (tsp.iorder[i] == istart) jstart = i;
        if (tsp.iorder[i] == iend)   jend = i;
    }
    PGR_DBG("jstart: %d, jend: %d", jstart, jend);

    /*
     * If the end is specified and the end point and it follow start
     * then we swap start and end and extract the list backwards
     * and later we reverse the list for the desired order.
    */
    if ((jend > 0 && jend == jstart+1) ||(jend == 0 && jstart == tsp.n-1)) {
        int tmp = jend;
        jend = jstart;
        jstart = tmp;
        rev = 1;
        PGR_DBG("reversed start and end: jstart: %d, jend: %d", jstart, jend);
    }

    //  copy ids to tsp.jorder so we can rewrite ids
    memcpy(tsp.jorder, ids, (size_t) tsp.n * sizeof(int));

    //  write reordered ids into ids[]
    //  remember at this point jorder is our list if ids
    for (i=jstart, j = 0; i < tsp.n; i++, j++)
        ids[j] = tsp.jorder[tsp.iorder[i]];

    for (i=0; i < jstart; i++, j++)
        ids[j] = tsp.jorder[tsp.iorder[i]];

    //  if we reversed the order above, now put it correct.
    if (rev) {
        int tmp = jend;
        jend = jstart;
        jstart = tmp;
        reverse(tsp.n, ids);
    }

#ifdef DEBUG
    PGR_DBG("ids getting returned!");
    for (i=0; i < tsp.n; i++) {
        PGR_DBG("i: %d, ids[i]: %d, io[i]: %d, jo[i]: %d",
            i, ids[i], tsp.iorder[i], tsp.jorder[i]);
    }
#endif

    PGR_DBG("tsplib: jstart=%d, jend=%d, n=%d, j=%d", jstart, jend, tsp.n, j);

    return 0;
}
int main( int argc, const char** argv)
{
	try
	{
		if (argc <= 1)
		{
			printUsage( argc, argv);
			return 0;
		}
		unsigned int nofThreads = 0;
		bool doOptimize = false;
		int argidx = 1;
		for (; argidx < argc && argv[argidx][0] == '-'; ++argidx)
		{
			if (std::strcmp( argv[argidx], "-h") == 0)
			{
				printUsage( argc, argv);
				return 0;
			}
			else if (std::strcmp( argv[argidx], "-o") == 0)
			{
				doOptimize = true;
			}
		}
		if (argc - argidx < 4)
		{
			std::cerr << "ERROR too few arguments" << std::endl;
			printUsage( argc, argv);
			return 1;
		}
		else if (argc - argidx > 5)
		{
			std::cerr << "ERROR too many arguments" << std::endl;
			printUsage( argc, argv);
			return 1;
		}
		initRand();
		g_errorBuffer = strus::createErrorBuffer_standard( 0, 1+nofThreads, NULL/*debug trace interface*/);
		if (!g_errorBuffer)
		{
			std::cerr << "construction of error buffer failed" << std::endl;
			return -1;
		}
		unsigned int nofFeatures = strus::utils::getUintValue( argv[ argidx+0]);
		unsigned int nofDocuments = strus::utils::getUintValue( argv[ argidx+1]);
		unsigned int documentSize = strus::utils::getUintValue( argv[ argidx+2]);
		unsigned int nofPatterns = strus::utils::getUintValue( argv[ argidx+3]);
		const char* outputpath = (argc - argidx > 4)? argv[ argidx+4] : 0;

		strus::local_ptr<strus::PatternMatcherInterface> pt( strus::createPatternMatcher_std( g_errorBuffer));
		if (!pt.get()) throw std::runtime_error("failed to create pattern matcher");
		strus::local_ptr<strus::PatternMatcherInstanceInterface> ptinst( pt->createInstance());
		if (!ptinst.get()) throw std::runtime_error("failed to create pattern matcher instance");

		GlobalContext ctx( nofFeatures, nofPatterns);
		std::vector<strus::utils::Document> docs = createRandomDocuments( nofDocuments, documentSize, nofFeatures);
		std::vector<TreeNode*> treear = createRandomTrees( &ctx, docs);
		KeyTokenMap keyTokenMap;
		fillKeyTokens( keyTokenMap, treear);
		createRules( ptinst.get(), &ctx, treear);
		if (doOptimize)
		{
			ptinst->compile();
		}
		if (g_errorBuffer->hasError())
		{
			throw std::runtime_error( "error creating automaton for evaluating rules");
		}
#ifdef STRUS_LOWLEVEL_DEBUG
		std::cout << "patterns processed" << std::endl;
		std::vector<TreeNode*>::const_iterator ti = treear.begin(), te = treear.end();
		for (; ti != te; ++ti)
		{
			std::cout << (*ti)->tostring() << std::endl;
		}
#endif
		std::cerr << "starting rule evaluation ..." << std::endl;

		std::map<std::string,double> stats;
		unsigned int totalNofMatches = processDocuments( ptinst.get(), keyTokenMap, treear, docs, stats, outputpath);
		unsigned int totalNofDocs = docs.size();

		if (g_errorBuffer->hasError())
		{
			throw std::runtime_error("uncaugth exception");
		}
		std::cerr << "OK" << std::endl;
		std::cerr << "processed " << nofPatterns << " patterns on " << totalNofDocs << " documents with total " << totalNofMatches << " matches" << std::endl;
		std::cerr << "statistiscs:" << std::endl;
		std::map<std::string,double>::const_iterator gi = stats.begin(), ge = stats.end();
		for (; gi != ge; ++gi)
		{
			int value;
			if (gi->first == "nofTriggersAvgActive")
			{
				value = (int)(gi->second/totalNofDocs + 0.5);
			}
			else
			{
				value = (int)(gi->second + 0.5);
			}
			std::cerr << "\t" << gi->first << ": " << value << std::endl;
		}
		delete g_errorBuffer;
		return 0;
	}
	catch (const std::runtime_error& err)
	{
		if (g_errorBuffer && g_errorBuffer->hasError())
		{
			std::cerr << "error processing pattern matching: "
					<< g_errorBuffer->fetchError() << " (" << err.what()
					<< ")" << std::endl;
		}
		else
		{
			std::cerr << "error processing pattern matching: "
					<< err.what() << std::endl;
		}
	}
	catch (const std::bad_alloc&)
	{
		std::cerr << "out of memory processing pattern matching" << std::endl;
	}
	delete g_errorBuffer;
	return -1;
}
Exemple #29
0
Data MatrixGraph::simulatedAnnealing(uint temperature)
{
	clock_t overallTime = clock();
	initRand();
	stringstream results;
	vector<uint> route, bestRoute;
	route.reserve(vertexNumber);
	bestRoute.reserve(vertexNumber);
	uint prevCost = greedyAlg(route), bestCost;
	route.pop_back();
	bestRoute = route;
	bestCost = prevCost;

	if (!temperature)
		temperature = vertexNumber << 10;

	default_random_engine gen(uint(time(nullptr)));
	uniform_real_distribution<double> doubleRnd(0.0, 1.0);

	uint i = 0;
	for (; temperature; --temperature, ++i)
	{
		i %= route.size();
		uint firstIndex = rand() % (route.size());
		uint secondIndex = rand() % (route.size() - 1);
		if (secondIndex >= firstIndex)
			++secondIndex;

		vector<uint> tmpVector(route);
		uint tmp = tmpVector[firstIndex];
		tmpVector[firstIndex] = tmpVector[secondIndex];
		tmpVector[secondIndex] = tmp;

		uint tmpCost = calculateCost(tmpVector);
		if (tmpCost < prevCost)
		{
			route = tmpVector;
			prevCost = tmpCost;
		}
		else
		{
			if (acceptanceProbability(prevCost, tmpCost, temperature) >= doubleRnd(gen))
			{
				route = tmpVector;
				prevCost = tmpCost;
			}
		}

		// Śledzenie najlepszego rozwiązania
		if (prevCost < bestCost)
		{
			bestRoute = route;
			bestCost = prevCost;
		}
	}

	double duration = (clock() - overallTime) / (double)CLOCKS_PER_SEC;
	results << "Koszt drogi: " << bestCost << "\nCalkowity czas trwania: " << duration << " sekund\n";
	return Data(bestRoute, bestCost, results.str(), duration);

}