Exemplo n.º 1
0
Eigen::VectorXf Simplex::run() {
	int piv_col, piv_row;
	while(1){
		piv_col = findPivotColumn();
		//std::cout << " CHOIX PIVOT " << std::endl;
		//std::cout << " simplexe run piv_col : "<< piv_col << std::endl;
		if(piv_col < 0)
		{
			//std::cout<< " STOP " << std::endl;
			getBest(); // optimal
			return best;
		}
		piv_row = findPivotRow(piv_col);
		//std::cout << " simplexe run piv_row : " << piv_row << std::endl;

		if(piv_row < 0)
		{
			//std::cout << " Pas de solution" << std::endl;
			break; //caca
		}
		//std::cout << " val pivot : " << tab(piv_row,piv_col);
		//std::cout << " " << std::endl;
		pivot(piv_row, piv_col);
		//std::cout << tab << std::endl;
	}
	return best;
}
std::pair<roadPtr, bool> IntersectionGeometry::getAntiClockwise(float angle, bool clockwise) {
	//Travelling on the right and looking for left most, is the same as looking for the right most(i.e. first)
	if (clockwise == true)
		return getClockwise(angle, clockwise);
	auto next = getBest(angle, clockwise);
	float outgoingAngle = next.second;
	//Switch sides if travel vertically
	return std::make_pair(next.first, getNextSide(angle, outgoingAngle, clockwise));
}
std::pair<roadPtr, bool> IntersectionGeometry::getClockwise(float angle, bool clockwise) {
	if (clockwise == false) 
		return getAntiClockwise(angle, clockwise);
	//Find angle with smalles +ve change
	auto next = getBest(angle, clockwise);
	float outgoingAngle = next.second;
	//Switch sides if travel vertically
	return std::make_pair(next.first, getNextSide(angle, outgoingAngle, clockwise));
}
Exemplo n.º 4
0
/**
 * @brief getBest This function returns the node with the highest value in the tree, using
 * DFS algorithm.
 * @param head The head of the tree.
 * @param getChildren A function that gets a node and a pointer to an array of nodes.
 * The function allocates memory for an array of all the children of the node, populate it,
 * and returns it using the second parameter. The returned value is the number of children.
 * @param getVal A function that gets a node and returns its value, as int.
 * @param freeNode A function that frees a node from memory. This function will be called for each
 * node returned by getChildren.
 * @param copy A function that does a deep copy of a node.
 * @param best The highest possible value for a node. When the function encounters a node with that
 * value, it stops looking and returns it. If the best value can't be determined, pass
 * UINT_MAX (defined in limits.h) for that parameter.
 * @return The node with the highest value in the tree. In case of an error, or when all the nodes
 * in the tree have a value of zero, the returned node is NULL. If some nodes share the best value,
 * the function returns the first one it encounters.
 */
pNode getBest(pNode head, getNodeChildrenFunc getChildren,
			  getNodeValFunc getVal, freeNodeFunc freeNode, copyNodeFunc copy, unsigned int best)
{
	// check the value of the head given and compares it to the
	// best so far - update if better
	unsigned int headValue = getVal(head);
	if (gFoundBestNode != TRUE)
	{
		// in case has the value of the best requested pNode
		if (headValue == best)
		{
			freeNode(gBestNode);
			gBestNode = copy(head);
			gFoundBestNode = TRUE;
		}
		else
		{
			// in case its value is bigger than the best found so far
			if (headValue > getVal(gBestNode))
			{
				if (gBestNode != NULL)
				{
					freeNode(gBestNode);
				}
				gBestNode = copy(head);
			}
		}
	}

	// initialize pNode array and find out how many children the pNode has
	// and run thorugh them recursvely
	pNode* headChildren = NULL;
	int numberOfChildren = getChildren(head, &headChildren), child;
	for (child = 0; child < numberOfChildren; child++)
	{
		// run reccursion only in case hasn't found best node yet
		if (!gFoundBestNode)
		{
			getBest(headChildren[child], getChildren, getVal, freeNode, copy, best);

		}
		else
		{
			break;
		}
	}

	// free memory of all the children and the list and finally return the best node
	for (child = (numberOfChildren - 1); child >= 0; child--)
	{
		freeNode(headChildren[child]);
		headChildren[child] = NULL;
	}
	free(headChildren);
	headChildren = NULL;
	return gBestNode;
}
Exemplo n.º 5
0
int iTree::getBest(int start, int end, int pos, int rootStart, int rootEnd)
{
	if(start == rootStart && end == rootEnd)
		return data[pos];

	int max = 0,
		middle = (rootStart + rootEnd) / 2,
		temp;

	if(start > middle)
		return getBest(start, end, pos * 2 + 1, middle + 1, rootEnd);

	if(end <= middle)
		return getBest(start, end, pos * 2, rootStart, middle);

	max = getBest(start, middle, pos * 2, rootStart, middle);
	temp = getBest(middle + 1, end, pos * 2 + 1, middle + 1, rootEnd);
	return cmp(max, temp)?max:temp;
}
Exemplo n.º 6
0
void GenAI::Run(int epochs){
    
    Initialize();
    
    for (int e = 0; e != epochs; ++e)
    {
        // Seleccion de padres
        int np = crossoverRate * pSize;
        if (np % 2 != 0)
            np += 1;
        
        std::vector<NeuralNet> parents = GenAI::tournamentSelection(population, np);
        
        // Crossover
        std::vector<NeuralNet> offspring;
        for (int i = 0; i != parents.size(); i += 2)
        {
            std::vector<NeuralNet> osp = NeuralNet::crossover(parents[i], parents[i+1]);
            offspring.push_back(osp[0]);
            offspring.push_back(osp[1]);
        }
        
        // Mutacion
        int maxMutation = mutationRate * offspring.size();
        for (int i = 0; i != maxMutation; ++i)
            offspring[i].mutate();
        
        // Seleccion de sobrevivientes
        for (int i = 0; i != offspring.size(); ++i)
            population.push_back(offspring[i]);
        
        population = GenAI::rankingSelection(population, pSize);
        
        allFitness.push_back(getBest().getFitness());
        std::cout <<"Epoch: "<<e <<" MejorFit: " << getBest().getFitness()<< std::endl;
 
    }
    
}
Exemplo n.º 7
0
bool RumorMill_getNode(struct RumorMill* mill, struct Address* output)
{
    struct RumorMill_pvt* rm = Identity_check((struct RumorMill_pvt*) mill);
    if (!rm->pub.count) {
        return false;
    }
    struct Address* best = getBest(rm);
    if (output) {
        Bits_memcpyConst(output, best, sizeof(struct Address));
    }

    rm->pub.count--;
    if (&rm->pub.addresses[rm->pub.count] != best) {
        Bits_memcpyConst(best, &rm->pub.addresses[rm->pub.count], sizeof(struct Address));
    }
    return true;
}
Exemplo n.º 8
0
void AstarPathfinding::getPath(float srcX, float srcY, float destX, float destY, PointList_t &path){

    ///init
    this->srcP.x = srcX;
    this->srcP.y = srcY;
    this->destP.x = destX;
    this->destP.y = destY;
    clearList(path);
    clearList(openedList);
    clearList(closedList);

    ///set the first point
    currentP = new Point_t();
    currentP->x = srcX;
    currentP->y = srcY;
    currentP->costa = 0.f;
    currentP->costb = (destX - srcX)*(destX - srcX) + (destY - srcY)*(destY - srcY);
    currentP->totalcost = currentP->costa + currentP->costb;
    openedList.push_back(currentP);

    ///perform
    while(!openedList.empty() && !(currentP->x == destX && currentP->y == destY) ){
        //std::cout << "currentP = " << currentP->x << "; " << currentP->y << "\n";

        openedList.remove(currentP);
        closedList.push_back(currentP);
        perform();

        currentP = getBest();
    }


    ///return result
    if(currentP != NULL && currentP->x == destX && currentP->y == destY){
        do{
            Point_t* p = new Point_t();
            p->x = currentP->x;
            p->y = currentP->y;
            path.push_front(p);
            currentP = currentP->previous;
        }while(currentP != NULL);
    }

    clearList(openedList);
    clearList(closedList);
}
void PfRectPrismFitting::captureThreadFunction()
{ 
  
  while (true)
  {

    // Lock before checking running flag
    boost::unique_lock<boost::mutex> capture_lock (capture_mutex);
    if(running)
    {
      pf->step(input, 0, false, -1);
//       bestParticle=pf->getBest();
      
      // Check for shape slots
      if (num_slots<sig_cb_fitting_addapt> () > 0 )
        fitting_signal->operator() (getBest ());
    }
    capture_lock.unlock ();
  }
}
Exemplo n.º 10
0
/**
 * the main progrems - calls the diffrent functions to start the orchestras
 * in case of success finding a solution or the best one -  will print it
 * otherwise will print a message
 * @param argc the number of arguments give
 * @param argv the char array that hodls the arguments
 * return 0
 **/
int main(int argc, char* argv[])
{
	atexit(cleanFiles);
	argumentParser(argc, argv);
	int** sudukuTable = NULL;
	sudukuTable = fileParser(sudukuTableFile);
	unsigned int best = ((gTableSize*(1 + gTableSize)) / 2)*gTableSize;
	pNode bestNode = getBest((pNode)sudukuTable, getNodeChildrenSoduku, calculateTableSum, 
							 nodeReleaser, copySudukuTable, best);
	if (bestNode != NULL)
	{
		printSudukuSolution((int**)bestNode, gTableSize);
		nodeReleaser(bestNode);
	}
	else
	{
		printf("no solution!\n");
	}
	
	nodeReleaser(sudukuTable);
	return 0;
}
Exemplo n.º 11
0
/**
 * This function is the main function of the program. responsible of getting the file, make the 
 * check if it's legal and print the board if it does, else exit with the matching error message.
 * input :
 * 		int argc - number of arguments 
 * 		char* argv[] - the arguments in the command line
 * output :
 * 		0 if finished working fine, 1 else.
 **/
int main(int argc, char* argv[])
{
	FILE *file;
	int boardSize;
	// oppening the file with reading permission
	file = fopen(argv[FILE_NAME], "r");
	//in case of NULL means no file was given or wrong location
	if (file == NULL) 
	{
		printf("please supply a file!\n");
		printf("usage: sudukusolver <filename>\n");
		exit(EXIT_FAILURE);
	}
	// illeagl input line
	if (argc != LEGAL_COMMAND_LINE_SIZE) 
	{	
		printf("please supply a file!\n");
		printf("usage: sudukusolver <filename>\n");
		exit(EXIT_FAILURE);
	}
	SudukuBoardStruct *suduku = (SudukuBoardStruct*) malloc(sizeof(SudukuBoardStruct));
	// sending the file and the suduku to the parser and put in boardSize the size of the Board
	boardSize = parser(file, suduku, argv[FILE_NAME]);	
	SudukuBoardStruct *finalSuduku = (SudukuBoardStruct*) getBest(suduku, getSudukuChildrenFunc, \
								getSudukuValFunc, freeSudukuFunc, copySudukuFunc, \
								(boardSize * boardSize));
	if (finalSuduku == NULL)
	{
		printf("no solution!\n");
		exit(EXIT_FAILURE);
	}
	printf("%d\n", boardSize);
	sudukuBoardPrinter(finalSuduku, finalSuduku->size);
	freeSudukuFunc(finalSuduku);
	freeSudukuFunc(suduku);
	fclose(file);
	return 0;
}
Exemplo n.º 12
0
/* Initializers */
cl_int CLFW::Initialize(bool _verbose, bool queryMode) {
  verbose = _verbose;
  if (verbose) Print("Initializing...", infoFG, infoBG);
  cl_int  error = get(Platforms);
  error |= get(Devices);

  if (queryMode == false) {
    error |= getBest(DefaultDevice);
  }
  else {
    error |= query(DefaultDevice);
  }
  Contexts.clear();
  error |= get(DefaultContext);
  Contexts.push_back(DefaultContext);
  Queues.clear();
  error |= get(DefaultQueue);
  Queues.push_back(DefaultQueue);
  error |= get(DefaultSources);
  error |= Build(DefaultProgram, DefaultSources);
  error |= get(Kernels);
  
  return error;
}
Exemplo n.º 13
0
//**********************************************************************
//* The handout expected us to brute force the key.
//* If not marking exactly to a mark scheme ignore this function.
//* Its only called if the program is called with the -bf flag
//* It tries every key against the first two characters building up a list
//* of the most likely. Then uses frequency analysis to knock out unlikely keys.
//* until the correct key is found
uint16_t bf_key(uint8_t *inbuf, long buffsize, char bf)
{
	struct key_l *h = NULL, *t = NULL, *iter = NULL, *tmp, *bestKey = NULL, *secondBestKey = NULL;
	uint16_t val, scr, cur, keycount = 0 , cutoff = 10;
	uint32_t key;
	long lim = 0;
	uint8_t c1 = 0, c2 = 0, pos = 2, *check = NULL;
		
	if (buffsize < 4)
	{
		printf("I need at least 4 bytes! I mean come on... Outputting garbage\n");
		return 0;
	}
	
	if (buffsize > 40)
		lim = 40;
	else
		lim = buffsize;
	
	if (bf)
	{
		check = (uint8_t*)malloc(sizeof(uint8_t)*lim);
		if (check == NULL)
			printf("Warning: Check malloc failed - Best guess will be used\n");
	}
	
	cur = inbuf[1] | (uint16_t)(inbuf[0]) << 8;
	// Round 1 - for every possible key decrypt the first two characters.
	// Score them based on the frequency data & keep brack of the best.
	for (key = 0; key < 0xFFFF; key++)
	{
		val = cur^key;
		c1 = val >> 8;
		c2 = val & 0xFF;;

		scr = charVal(c1) + charVal(c2) + biVal(val);
		if (scr > 20)
		{
			t = add_key(&h,t,key,scr);
			if (bestKey == NULL || scr > bestKey->score)
			{
				secondBestKey = bestKey;
				bestKey = t;
			}
			keycount++;
		}
	}
	// Subsequent rounds. While we have more than 20 keys
	// And have looked at less than 20 characters & haven't exhausted the buffer
	while (keycount > 20 && pos < 20 && pos < buffsize)
	{
		// Concatenate the two characters.
		cur = inbuf[pos+1] | (uint16_t)(inbuf[pos]) << 8;
		iter = h;
		// Go through all remaining keys
		while (iter != NULL)
		{
			// Check the score for the output characters
			val = cur^iter->key;
			c1 = val >> 8;
			c2 = val & 0xFF;

			scr = charVal(c1) + charVal(c2);
			if (scr > 0)
			{
				scr += biVal(val);
				iter->score += scr;
				if (scr > 20 && iter->score > cutoff)
				{
					if (iter->score > bestKey->score)
					{
						secondBestKey = bestKey;
						bestKey = iter;
					}
				}
				else
				{	
					tmp = iter;
					iter = iter->next;
					if (tmp->key == bestKey->key)
						bestKey = getBest(bestKey->key, &secondBestKey, h);
					remove_key(&h, &t, tmp);
					keycount--;
					continue;
				}
			}
			else
			{
				tmp = iter;
				iter = iter->next;
				if (tmp->key == bestKey->key)
					bestKey = getBest(bestKey->key, &secondBestKey, h);
				remove_key(&h, &t, tmp);
				keycount--;
				continue;
			}
			iter = iter->next;
		}
		if (pos > 7 && bestKey->score > (2*secondBestKey->score))
		{
			printf("Key took %hhu rounds. max = %lu, keycount = %hu (double second highests score)\n", pos/2, bestKey->score, keycount);
			pos+=20;
			break;
		}
		if (check != NULL)
		{
			decrypt(inbuf, check, bestKey->key, &lim);
			c2 = 2;
			for (c1 = 0; c1 < lim && c2; c1++)
			{
				if (charVal(check[c1]) < 35)
					c2--;
			}
			if (c1 != lim)
			{
				printf("Key failed prelim check. Abandoning 0x%X\n", bestKey->key);
				tmp = bestKey;
				bestKey = getBest(bestKey->key, &secondBestKey, h);
				remove_key(&h, &t, tmp);
				keycount--;
			}
			else
			{
				printf("Key took %hhu rounds. max = %lu, keycount = %hu (best key for round check)\n", pos/2, bestKey->score, keycount);
				pos+=20;
				break;
			}
		}
		cutoff*=4;
		pos+=2;
	}
	free(check);
	if (pos <=20)
		printf("Key took %hhu rounds. max = %lu, keycount = %hu (max blocks)\n", pos/2, bestKey->score, keycount);
	iter = h;
	key = bestKey->key;
	while (iter != NULL)
	{
		tmp = iter->next;
		free(iter);
		iter = tmp;
	}
	return key;
}