Example #1
0
bool hamilton(int start) {
	path.clear();
	path.PB(start);
	list<int>::iterator cur, pre;
	for (int i = 1; i <= n; i++) {
		if (i == start) continue;
		cur = path.begin();
		if (g[i][*cur]) {
			path.push_front(i);
			continue;
		}
		cur = path.end(); cur--;
		if (g[*cur][i]) {
			path.PB(i);
			continue;
		}

		pre = cur = path.begin();
		cur++;
		for (; cur != path.end(); cur++, pre++) {
			if (g[*pre][i] && g[i][*cur]) {
				path.insert(cur, i);
				break;
			}
		}
	}
	pre = path.begin(); cur = path.end(); cur--;
	if (g[*cur][*pre]) {
		for (list<int>::iterator it = path.begin(); it != path.end(); it++) {
			if (it != path.begin()) printf(" ");
			printf("%d", *it);
		}
		puts("");
		return true;
	}
	return false;
}
Example #2
0
// -----------------------------------------------------------------
// Debe retornar una lista con las numeros relativos de soldados de
// que van saliendo segun el algoritmo de Josephus, donde "n" es la 
// cantidad de soldados y "s" es el salto en el juego
// -----------------------------------------------------------------
void josephus (int n,int s,list<int> &L) {
  list <int> H;
  list <int> :: iterator p;
  // Inicialmente carga en lista auxiliar H con los enteros [0,n]
  for (int j=0;j<n;j++) H.insert(H.end(),j);
     p=H.begin();
    // Va simulando el algoritmos extrayendo soldados de H y
    // pasandolos a L. Como hay que extraer exactamente N soldados 
    // directamente hacemos un lazo de 0 a N-1
    for (int k = 0; k < n ; k++) {
    // Avanzamos S posiciones en sentido circular por lo que nunca 
    // debe quedar en H.end (). Para evitarlo, cuando llega a
    // ser H.end () pasamos a H.begin ().
    for (int j = 0 ; j < s-1; j++) 
      if (++p == H.end()) p = H.begin (); // Notar pre-incremento
      // Pasamos el soldado en P a la lista L
      L.insert (L.end(),*p);
      // Borra en sentido circular, es decir, si P es el
      // ultimo elemento, entonces al borrar queda en H.end(), 
      // en ese caso lo pasamos a H.begin ()
      p = H.erase(p);
      if (p == H.end () ) p = H.begin ();
    } // end j
} // end void
 /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
 void inc(string key) 
 {
     int val = Str2Num[key];
             
     Str2Num[key]++;
     
     Num2Strs[val+1].insert(key);
     if (val!=0) Num2Strs[val].erase(key);
     
     if (Num2Strs[val+1].size()==1)
     {
         auto it = Num2Iter[val];
         ListNum.insert(next(it),val+1);
         Num2Iter[val+1] = next(it);
     }
     
     if (val!=0 && Num2Strs[val].size()==0)
     {
         auto it = Num2Iter[val];
         ListNum.erase(it);
         Num2Iter.erase(val);
     }
     
 }
Example #4
0
void sorted_insert(list<T>& ll, const T& item, compare_t<T> compare) {
    // If the list is empty, insert at the head
    if(ll.empty()) {
        ll.push_front(item);
        return;
    }

    // Search through the list to find the appropriate insertion point
    for(auto iter = ll.begin(); iter != ll.end(); iter++) {
        // Do not insert duplicates
        if(compare(item, *iter) == 0) {
            throw runtime_error("Item already exists in the list");
        }

        // If the new item sorts before the current node, insert before it
        if(compare(item, *iter) < 0) {
            ll.insert(iter, item);
            return;
        }
    }

    // Reached the tail, append here
    ll.push_back(item);
}
Example #5
0
void max_path_if (tree<T> & Q, typename tree<T>::iterator n,
		int (*comp) (T,T), list<T> & L) {
  list<T> L2;
  typename tree<T>::iterator cmax, c ;
  int lmax = 0;
  c = n.lchild();
  while (c != Q.end()) {
    L2.clear();
    if ( comp (*n,*c)>0) {
      max_path_if (Q, c, comp, L2);
      if (L2.size() > lmax) {
	cmax = c; 
	lmax = L2.size();
      }
    }
    c++;
  }
  L.clear ();
  L.insert (L.begin(),*n);
  if (cmax != Q.end()) {
    max_path_if (Q,cmax,comp,L2);
    L.splice (L.end(), L2);
  }
}
Example #6
0
void AStar::recalculateGCost(OccupancyGridMap* map, list<coupleOfCells> & OPL, vector<int> neighborCellsInOpenList,int currentCell, float gCostCurrent)
{
  
  for(uint i=0; i< neighborCellsInOpenList.size(); i++)
  {
    coupleOfCells CP;
     
    //compare the gCost that exist in the openlist with the new gcost
    list<coupleOfCells>::iterator it=getPositionInList(OPL,neighborCellsInOpenList[i]);
    float previousGCost=(*it).gCost;
  
    //if the new gCost is better than the cost that exist in OPL: update the gCost
    if(previousGCost > gCostCurrent+map->getMoveCost(currentCell,neighborCellsInOpenList[i]))
    {
      CP.currentCell=(*it).currentCell;
      CP.parentCell=currentCell;
      CP.gCost=gCostCurrent+map->getMoveCost(currentCell,neighborCellsInOpenList[i]);
      CP.hCost=(*it).hCost;
      CP.fCost=CP.gCost+CP.hCost;
      it=OPL.erase(it);
      OPL.insert (it,CP);
    }
  }
}
// 실행 중인 프로세스 중에서 특정 상태인 프로세스 목록을 얻는다.
// 상태를 지정하지 않으면(-1) 가장 안좋은(worst) 프로세스 찾는다.
int CProcessManager::GetStatus(list<ST_APPRUNINFO>& a_lstInfo,
												CProcStatus::EN_STATUS a_nStatus)
{
	// 최악의 상태를 찾는다.
	if (a_nStatus == CProcStatus::NONE) {
		vector<CProcStatus::EN_STATUS> vecStatus;
		ExtracStatus(vecStatus);

		CProcStatus clsStatus;
		a_nStatus = clsStatus.FindWorstStatus(vecStatus);
	}

	vector<proc_t::iterator> P;
	OrderStatus(P);

	list<ST_APPRUNINFO>::iterator liter;

	for (size_t i=0; i < P.size(); ++i) {
		if (P[i]->second.m_stAppInfo.m_bIsBatch) {
			continue;
		}
		if (P[i]->second.m_pclsApp->GetStatus() == a_nStatus) {
			liter = a_lstInfo.insert(a_lstInfo.end(), ST_APPRUNINFO());
			liter->m_stInfo = P[i]->second.m_stAppInfo;
			liter->m_stRun = P[i]->second.m_pclsApp->m_stRunInfo;
		} else {
			// 상태 종류별로 정렬되어 있기 때문에 상태가 다른 프로세스가 확인되면
			// 불필요한 loop를 멈춘다.
			if (!a_lstInfo.empty()) {
				break;
			}
		}
	}

	return (int)a_lstInfo.size();
}
Example #8
0
//Function to retrive high scores from file (appends them to list of high scores given)
int loadHighScores(list<highScore_t> &highScores)
{
	ifstream inputStream;
	
	//Check input file correctly opened
	inputStream.open(scoresFile, ios::in);
	if(inputStream.is_open() == false) return 1;
	
	char ch; //Holds last char read from stream
	char* currentLine = NULL; //Line we're currently working on
	char* tempName = NULL; //Name extracted from current line
	int tempScore; //Score extracted from current line
	streampos lineStart; //Position of start of line
	streampos lineEnd; //EOL
	
	while(inputStream.peek() != EOF)
	{
		//Remove all newline characters before proceeding
		while(inputStream.peek() == '\n') inputStream.get(ch);
		
		//Find start and end of line
		lineStart = inputStream.tellg();
		do{ inputStream.get(ch); } while(ch != '\n');
		lineEnd = inputStream.tellg();
		
		//Return to start of line
		inputStream.seekg(lineStart);
		
		//Create new char string to store line
		currentLine = new char[lineEnd-lineStart];
		
		//Read the line
		inputStream.getline(currentLine,lineEnd-lineStart);
		
		//Find position of delimiter (',') in line and attempt to parse the name and score
		//Expected format: <name>,<score>
		for(unsigned int i=0; i<strlen(currentLine); i++)
		{			
			if(currentLine[i] == ',')
			{
				tempName = new char[i+1];
				strncpy(tempName,currentLine,i);
				tempName[i] = 0;
				
				//Check for and discard empty strings
				if(strcmp(tempName,"") == 0) break;
				
				bool isWhiteSpace = true;
				for(unsigned int j=0; j<strlen(tempName); j++) if(tempName[j] != ' ') isWhiteSpace = false;
				
				if(isWhiteSpace == true) break;
				
				//Record score
				tempScore = atoi(currentLine+i+1);
				if((tempScore == 0) || (tempScore < 0)) break;
				
				//Place new high score record in correct position in list - preserve ordering of list.
				if(highScores.empty()) highScores.push_front(highScore_t(tempName,tempScore));
				else for(list<highScore_t>::iterator j = highScores.begin(); j != highScores.end(); j++)
				{
					if(tempScore > (*j).getScore())
					{
						highScores.insert(j,highScore_t(tempName,tempScore));
						break;
					}
					else if(tempScore == (*j).getScore()) //Compare Names
					{
						if(strcmp(tempName,(*j).getName()) < 0)
						{
							highScores.insert(j,highScore_t(tempName,tempScore));
							break;
						}
						else if(strcmp(tempName,(*j).getName()) == 0) break; //If name AND score is the same then ignore this score to prevent it being inserted multiple times
					}
					
					//If we're about to get to the end and haven't found a place for the high score, place it at the end
					if(j == --highScores.end())
					{
						highScores.insert(highScores.end(),highScore_t(tempName,tempScore));
						break;
					}
				}
				break;
			}
		}
		
		//Free memory
		if(currentLine != NULL)	delete [] currentLine;
		if(tempName != NULL) delete [] tempName;
		
		currentLine = NULL;
		tempName = NULL;
	}
	
	//Close file
	inputStream.close();

	return 0;
}
Example #9
0
void gameOver(int score,list<highScore_t> &highScores)
{
	int row, col;
	int ch = 0;
	bool isHighScore = false;
	
	//Do we have a high score?
	if(highScores.empty() && (score != 0)) isHighScore = true; //Yes, if you're the first to get a non-zero score. Impressive.
	else for(list<highScore_t>::iterator i=highScores.begin(); i != highScores.end(); i++)
	{
		if((*i).getScore() < score)
		{
			isHighScore = true;
			break;
		}
		else isHighScore = false;
	}
	
	//Wait a little to show players their demise
	usleep(endWaitTime*1000000);
	
	//Set character reading to be blocking
	nodelay(stdscr,FALSE);
	
	//Clear window
	clear();
	
	//Get size of window
	getmaxyx(stdscr,row,col);
	
	//Print game over text
	mvprintw(row/2-3,col/2-38,"  ____       _         _  _      _____          ___             _____  ___");
	mvprintw(row/2-2,col/2-38," /    \\     / \\       / \\/ \\    |              /   \\  \\      / |      |   \\ ");
	mvprintw(row/2-1,col/2-38,"|          /___\\     /      \\   |___          /     \\  \\    /  |___   |___/");
	mvprintw(row/2,col/2-38,"|    ___  /     \\   /        \\  |             \\     /   \\  /   |      |   \\ ");
	mvprintw(row/2+1,col/2-38," \\____/  /       \\ /          \\ |_____         \\___/     \\/    |_____ |    \\ ");
	
	if(isHighScore)
	{
		mvprintw(row/2+4,col/2-strlen("Congratulations! High score!")/2,"Contratulations! High Score!");
		mvprintw(row/2+5,col/2-strlen("Please enter your name: ")/2,"Please enter your name: ");
		move(row/2+6,col/2);
	
		string name = "";
		while(true)
		{
			ch = wgetch(stdscr); //Read character
		
			//Interpret it correctly	
			if(ch == KEY_BACKSPACE) { if(name.length() > 0) name.erase(--name.end()); }
			else if(ch == '\n')
			{
				refresh();
				break;
			}
			else if((ch == ' ') && (name.length() == 0)) { /*Do nothing - I'm onto you*/ }
			else if((ch >= KEY_MIN) && (ch <= KEY_MAX)) { ch = 0; }
			else name += ch;
		
			for(unsigned int i=0; i<name.length()+2; i++) mvprintw(row/2+6,col/2-(name.length()+1)/2-1+i," ");
			mvprintw(row/2+6,col/2-(name.length()+1)/2,"%s",name.c_str());
		
			refresh();
		}
	
		//Remove trailing space characters
		for(string::iterator i=(--name.end()); i != name.begin(); i--)
		{
			if((*i) == ' ') i = name.erase(i);
			else break;
		}
		
		//Record the score in our list of high scores, preserving ordering
		if(highScores.empty()) highScores.push_front(highScore_t(name.c_str(),score));
		else for(list<highScore_t>::iterator i = highScores.begin(); i != highScores.end(); i++)
		{
			if(score > (*i).getScore())
			{
				highScores.insert(i,highScore_t(name.c_str(),score));
				break;
			}
			else if(score == (*i).getScore()) //Compare Names
			{
				if(strcmp(name.c_str(),(*i).getName()) < 0)
				{
					highScores.insert(i,highScore_t(name.c_str(),score));
					break;
				}
				else if(strcmp(name.c_str(),(*i).getName()) == 0) break; //If name AND score is the same then ignore this score to prevent it being inserted multiple times
			}
			
			//If we're about to get to the end and haven't found a place for the high score, place it at the end
			if(i == --highScores.end())
			{
				highScores.insert(highScores.end(),highScore_t(name.c_str(),score));
				break;
			}
		}
		
		//Remove a high score from the list if there are too many
		while(highScores.size() > maxNumHighScores) highScores.pop_back();
		
		//Save the high scores to a file
		if(saveHighScores(highScores) == 1) mvprintw(row-2,col/2-strlen("ERROR: Couldn't save to file")/2,"ERROR: Couldn't save to file");
	}
	
	mvprintw(row-1,col/2-strlen(gameOverText)/2,"%s",gameOverText);
	
	//Move pointer back to top left hand corner
	move(0,0);
	
	//Draw to console
	refresh();
	
	while(ch != 'q') ch = wgetch(stdscr);
}
Example #10
0
/*
	Looks for energy sources that can potentially drive an opamp feedback branch.
	*/
void circuit_t::LookForOpampDrivingSources (const node_t* start, const node_t* output,
											 list<branch_t*>& covered_branches, list<element_t*>& energy_sources) const	
{
	/*
		To keep track of how many energy sources we found
		*/
	unsigned int initial_energy_source_count = energy_sources.size();
		
	/*
		First, we get a list of all branches going in/out of the starting aid.
		*/
	list<branch_t*> all_branches = start->VirtualBranchList();
	
	/*
		Special case: no branches exist, look for sources connected directly to the terminal
		*/
	if (all_branches.size() == 0)
	{
		
		
		
		// Search for VSRC whose actnode is this
		for (list<element_t*>::const_iterator e = start->elements.begin(); e != start->elements.end(); e++)
		{
			element_t* elm = (*e);
			
			
			/* Look for energy sources */
			if ((elm->type == E_VSRC || elm->type == E_CSRC)
				&& (elm->OtherNode (start) != output))
				energy_sources.push_back (elm);				
		} /* for */
		
		/* Look for opamp sources */
		if (start->IsOpampOutput())
			for (list<element_t*>::const_iterator e = start->elements.begin(); e != start->elements.end(); e++)
			{
				element_t* elm = (*e);
				if (elm->type == E_OPAMP_INV)
					energy_sources.push_back (elm);		
			} /* for */
			
	} /* if */
	else
	{
		/*
			An array to store filtered results in 
			*/
		list<branch_t*> filtered_results;
			
		/*
			If checks for energy sources in this actnode's branches 
			fail, we will run recursively until all a source is found
			or all branches have been tried.
		*/	
		for (list<branch_t*>::const_iterator b = all_branches.begin(); b != all_branches.end(); b++)
		{
			/*
				Filter out branches that go to the output node 
				*/
			if (((*b)->TopNode() == output)
				 || ((*b)->BottomNode() == output)
				 ||  ListContains (covered_branches, *b ))
				 continue;

			filtered_results.push_back (*b);
						
			/*
				We now have a list of branches that we know don't come from or
				go to the output node. 
				
				We first check the remaining branches for energy sources;
			*/
			if ((*b)->HasElement (E_CSRC) || (*b)->HasElement (E_VSRC) || (*b)->HasElement (E_OPAMP_INV))
			{		
				list<element_t*> csrc_list = (*b)->GetElements (E_CSRC);
				list<element_t*> vsrc_list = (*b)->GetElements (E_VSRC);
				list<element_t*> ooi_list = (*b)->GetElements  (E_OPAMP_INV);
				
				energy_sources.insert (energy_sources.end(), csrc_list.begin(), csrc_list.end());
				energy_sources.insert (energy_sources.end(), vsrc_list.begin(), vsrc_list.end());
				energy_sources.insert (energy_sources.end(), ooi_list.begin(),  ooi_list.end());
				
			} /* if */		
		} /* for */
				
		/* 
			No immediate energy sources were found,
			re-iterate through all loops 
			*/
		if (initial_energy_source_count == energy_sources.size())
		{
			// Add all branches as covered branches
			for (list<branch_t*>::const_iterator b = filtered_results.begin(); b != filtered_results.end(); b++)
			{				
				covered_branches.push_back (*b);
				
			} /* for */
		
			// iterate through all actnodes
			for (list<branch_t*>::const_iterator b = filtered_results.begin(); b != filtered_results.end(); b++)
			{
				
				/* 
					Recursiveness 
					*/
				LookForOpampDrivingSources ((*b)->OtherSupernode (start), output, covered_branches, energy_sources);
			
			} /* for */	
		} /* if */
			
			
	} /* else */
	
} /* circuit_t::LookForOpampDrivingSources */
Example #11
0
		virtual void randHun(int size) {
			for(int i = 0; i < size; i++) {
				l.insert(l.begin(), rand() % 100 + 1);
			}
		}
Example #12
0
void CommandsDefPrivate::generateConfig()
{
    if (cfg.size())
        return;
    if (config.length()){
        list<unsigned> processed;
        string active = config;
        string noactive;
        int n = config.find('/');
        if (n >= 0){
            active   = config.substr(0, n);
            noactive = config.substr(n + 1);
        }
        while (active.length()){
            string v = getToken(active, ',');
            unsigned id = atol(v.c_str());
            cfg.push_back(id);
            if (id)
                processed.push_back(id);
        }
        while (noactive.length()){
            string v = getToken(noactive, ',');
            unsigned id = atol(v.c_str());
            if (id)
                processed.push_back(id);
        }
        for (list<CommandDef>::iterator it = buttons.begin(); it != buttons.end(); ++it){
            CommandDef &c = (*it);
            unsigned grp = m_bMenu ? c.menu_grp : c.bar_grp;
            if (grp == 0)
                continue;
            list<unsigned>::iterator it_p;
            for (it_p = processed.begin(); it_p != processed.end(); ++it_p)
                if ((*it_p) == c.id)
                    break;
            if (it_p != processed.end())
                continue;
            unsigned cur_grp = 0;
            for (it_p = cfg.begin(); it_p != cfg.end(); ++it_p){
                if ((*it_p) == 0){
                    if (cur_grp == grp)
                        break;
                    continue;
                }
                list<CommandDef>::iterator itl;
                for (itl = buttons.begin(); itl != buttons.end(); ++itl)
                    if ((*itl).id == (*it_p))
                        break;
                if (itl == buttons.end())
                    continue;
                unsigned itl_grp = m_bMenu ? (*itl).menu_grp : (*itl).bar_grp;
                if (itl_grp == 0)
                    continue;
                cur_grp = itl_grp;
                if (grp > cur_grp)
                    break;
            }
            cfg.insert(it_p, c.id);
        }
    }else{
        unsigned cur_grp = 0;
        for (list<CommandDef>::iterator it = buttons.begin(); it != buttons.end(); ++it){
            CommandDef &c = (*it);
            unsigned grp = m_bMenu ? c.menu_grp : c.bar_grp;
            if (grp == 0)
                continue;
            if ((grp & ~0xFF) != (cur_grp & ~0xFF)){
                if (cur_grp)
                    cfg.push_back(0);
            }
            cur_grp = grp;
            cfg.push_back(c.id);
        }
    }
}
void Region::merge( Region& r, int* labels, const int& label, double* ucm, const double& saliency, const int& son, const int& tx )
{
  /* 			I. BOUNDARY        */

  // 	Ia. update father's boundary
  list<Bdry_element>::iterator itrb, itrb2;
  itrb = boundary.begin();
  while ( itrb != boundary.end() )
  {
    if( labels[(*itrb).cc_neigh] == son )
    {
      itrb2 = itrb;
      ++itrb;
      boundary.erase(itrb2);
    }
    else ++itrb;
  }

  int coord_contour;

  //	Ib. move son's boundary to father
  for( itrb = r.boundary.begin(); itrb != r.boundary.end(); ++itrb )
  {
    if (ucm[(*itrb).coord] < saliency ) ucm[(*itrb).coord] = saliency;

    if ( labels[(*itrb).cc_neigh] != label )
      boundary.push_back( Bdry_element(*itrb) );

  }
  r.boundary.erase( r.boundary.begin(), r.boundary.end() );

  /* 			II. ELEMENTS      */

  for( list<int>::iterator p = r.elements.begin(); p != r.elements.end(); ++p ) labels[*p] = label;
  elements.insert( elements.begin(), r.elements.begin(), r.elements.end() );
  r.elements.erase( r.elements.begin(), r.elements.end() );


  /* 			III. NEIGHBORS        */

  map<int,Neighbor_Region, less<int> >::iterator itr, itr2;

  // 	IIIa. remove inactive neighbors from father
  itr = neighbors.begin();
  while( itr != neighbors.end() )
  {
    if ( labels[(*itr).first] != (*itr).first )
    {
      itr2 = itr;
      ++itr;
      neighbors.erase(itr2);
    } else ++itr;
  }

  // 	IIIb. remove inactive neighbors from son y and neighbors belonging to father
  itr = r.neighbors.begin();
  while ( itr != r.neighbors.end() )
  {
    if ( ( labels[(*itr).first] != (*itr).first ) || ( labels[(*itr).first] == label ) )
    {
      itr2 = itr;
      ++itr;
      r.neighbors.erase(itr2);
    } else ++itr;
  }
}
Example #14
0
void concat_insert_2l (list<t> &L1,list<t> &L2,list<t> &L){
  L.clear();
  L.insert(L.end(),L1.begin(),L1.end());
  L.insert(L.end(),L2.begin(),L2.end());
}
Example #15
0
    //---:---<*>---:---<*>---:---<*>---:---<*>---:---<*>
    // Solves a sudoku problem. Tries to apply the rules until
    // the problem is solved or either stagnates. In the last
    // case, start guessing for the cell with lowest number of
    // admissible entries and continue. Returns number of
    // posible solutions. If the board is overdetermined then
    // return 0.
    void solve_aux() {

        if (!compute_all_solutions
                && solutions.size()>1) return;
        int retval = apply_rules();
        if (retval==1) {
            solutions.insert(solutions.begin(),w);
            if (!compute_all_solutions
                    && solutions.size()>1) return;
        }
        if (retval==-1) return;

        int jmin=-1, kmin=-1, admiss;

        // Look for the cell not yet determined
        // with the lower number of admissible
        // values
        for (int j=0; j<sizer; j++) {
            for (int k=0; k<sizer; k++) {
                int cellindx = j*sizer+k, sz;
                cell_t &cell = w[cellindx];
                sz = cell.admissible.size();
                // warning: size==1 means the cell
                // has been already filled. Don't take
                // into account.
                if (sz>1 && (jmin==-1 || sz<admiss)) {
                    jmin = j;
                    kmin=k;
                    admiss = sz;
                }
            }
        }

        // Didn't find a cell, the problem
        // is overdetermined.
        if (!(admiss>1 && jmin>=0)) return;

        // Found a cell
        int cellmin = jmin*sizer+kmin;
        // This is the admissible set of values
        // for the cell
        set<int> s = w[cellmin].admissible;
        // Push current state into the stack
        state_stack.insert(state_stack.begin(),w);

        // Try each of the admissible values
        set<int>::iterator q = s.begin();
        while (q!=s.end()) {
            // Reset current state
            w = *state_stack.begin();

            if (verbose) print();

            // Set entry to the guessed value
            set_entry(jmin,kmin,*q);

            if (verbose) {
                printf("guessing (%d,%d) set to %d, current board: \n",
                       jmin,kmin,*q);
                print();
            }

            // Try to solve again (recursively).
            solve_aux();
            q++;
        }
        // Restore state
        state_stack.erase(state_stack.begin());
    }
Example #16
0
// callback when we press a key
static void keyboard(const unsigned char key, const int x, const int y) {

  switch (key) {
  case 27:
    exit(0);                                  // ESC

  // Spacebar
  case 32:
    if(currentKeyFrame != keyFrames.end()){
      cout << "Restoring to Current Frame: keyFrames[" << currentIndex << "].\n"; 
      frameToSgRbtNodes(*currentKeyFrame);
    }
    break;

  // -'a' control whether draw the sphere
  case 'a':
    DRAW_SPHERE = !DRAW_SPHERE;

    cout << "Now in ";
    if(DRAW_SPHERE)cout << "SPHERE";
    else cout << "NO-SPHERE";  
    cout << " mode.\n";
    break;


  case 'd':
    if(currentKeyFrame != keyFrames.end()){
      cout << "Deleting Current Frame: keyFrames[" << currentIndex << "].\n";
      // delete current key frame
      list<vector<RigTForm> >::iterator tempFrame = currentKeyFrame;
      tempFrame++;
      keyFrames.erase(currentKeyFrame);

      if(!keyFrames.empty()){
        if(tempFrame != keyFrames.begin()){
          currentKeyFrame = --tempFrame;
          currentIndex--;
        }
        else{
          currentKeyFrame = tempFrame;
        }
        cout << "Now Current Frame: keyFrames[" << currentIndex << "].\n";
        frameToSgRbtNodes((*currentKeyFrame));
      }
      else{
        cout << "Now it is an empty list.\n";
        currentKeyFrame = keyFrames.end();
        currentIndex = -1;
      }

    }
    break;
  case 'h':
    cout << " ============== H E L P ==============\n\n"
    << "h\t\thelp menu\n"
    << "s\t\tsave screenshot\n"
    << "f\t\tToggle flat shading on/off.\n"
    << "p\t\tChoose object to edit\n"
    << "v\t\tChoose view\n"
    << "drag left mouse to rotate\n" << endl;
    break;

  case 's':
    glFlush();
    writePpmScreenshot(g_windowWidth, g_windowHeight, "out.ppm");
    break;

  case 'f':
    g_activeShader ^= 1;
    break;

  // update a frame
  case 'u':
    // if not empty
    if(currentKeyFrame != keyFrames.end()){
      cout << "Updating Current Frame: keyFrames[" << currentIndex << "].\n";
      sgRbtNodesToFrame(false);
      break;
    }

  // add a new frame
  case 'n':
  {

    vector<RigTForm> newFrame = sgRbtNodesToFrame(true);
    // if not empty
    if(currentKeyFrame != keyFrames.end()){
      keyFrames.insert(next(currentKeyFrame), newFrame);
      currentKeyFrame++;
    }
    // if empty
    else{
      keyFrames.push_back(newFrame);
      currentKeyFrame = keyFrames.begin();
    }

    cout << "Added a new frame at keyFrames[" << ++currentIndex << "].\n";

    break;
  }

  case '>':
    if(currentKeyFrame != prev(keyFrames.end()) && currentKeyFrame != keyFrames.end()){
      currentKeyFrame++;
      currentIndex++;
      cout << "Forward to: keyFrames[" << currentIndex << "].\n";
      frameToSgRbtNodes((*currentKeyFrame));
    }
    break;

  case '<':
    if(currentKeyFrame != keyFrames.begin() && currentKeyFrame != keyFrames.end()){
      currentKeyFrame--;
      currentIndex--;
      cout << "Backward to: keyFrames[" << currentIndex << "].\n";
      frameToSgRbtNodes(*currentKeyFrame);
    }
    break;

  case 'i':
  {
    ifstream input;
    input.open("Frames.txt", ifstream::in);
    int frameNumber, frameSize;
    input >> frameNumber >> frameSize;
    keyFrames.clear();

    cout << "Reading keyFrameList from file Frame.txt.\n";
    for(int i = 0;i < frameNumber;i++){
      vector<RigTForm> tempFrame;
      for(int j = 0;j < frameSize;j++){
        Cvec3 t;
        Quat q;
        for(int k = 0;k < 7;k++){
          double temp;
          input >> temp;
          if(k < 3){t[k] = temp;}
          else{q[k - 3] = temp;}
        }
        tempFrame.push_back(RigTForm(t, q));
      }
      keyFrames.push_back(tempFrame);
    }

    currentKeyFrame = keyFrames.begin();
    if(keyFrames.empty()){
      currentIndex = -1;
    }
    else{
      currentIndex = 0;
    }
    frameToSgRbtNodes((*currentKeyFrame));
    input.close();

    break;
  }

  case 'w':
  {
    ofstream output;
    output.open("Frames.txt", ofstream::out);
    int frameNumber = keyFrames.size();
    int frameSize;

    if(!frameNumber){
      frameSize = 0;
    }
    else{
      frameSize = keyFrames.front().size();
    }

    cout << "Writring keyFrameList to file Frame.txt.\n";
    output << frameNumber << " " << frameSize << endl;
    for(list<vector<RigTForm> >::iterator i = keyFrames.begin();i != keyFrames.end();i++){
      for(vector<RigTForm>::iterator j = (*i).begin();j != (*i).end();j++){
        for(int i = 0;i < 3;i++){
          output << (*j).getTranslation()[i] << " ";
        }
        for(int i = 0;i < 4;i++){
          if(i < 3){output << (*j).getRotation()[i] << " ";}
          else{output << (*j).getRotation()[i] << endl;}
        }
      }
    }

    break;
  }

  case 'y':
    if(keyFrames.size() < 4){
      cout << "Warning: not enough frames, must be at lease 4.\n";
      break;
    }
    else{
      PLAYING = !PLAYING;
      if(PLAYING){
        cout << "Staring Animation Playback...\n";
        glutTimerFunc(0, animateTimerCallback, 0);
      }
      else{
        list<vector<RigTForm> >::iterator t = keyFrames.end();
        t--;t--;
        currentKeyFrame = t;
        currentIndex = keyFrames.size() - 2;
        cout << "Currently Frame: keyFrames[" << currentIndex << "].\n";
        frameToSgRbtNodes(*currentKeyFrame);
      }
      break;
    }


  case '+':
    if(g_msBetweenKeyFrames > 100){
      g_msBetweenKeyFrames-=100;
      cout << "accelerating..." << g_msBetweenKeyFrames << " ms between frames\n";
    }
    break;
  case '-': 
    if(g_msBetweenKeyFrames < 4000){
      g_msBetweenKeyFrames+=100;
      cout << "slowing..." << g_msBetweenKeyFrames << " ms between frames\n";
    }
    break;
  // - 'v': cycle through the 3 views
  case 'v':
    CHOOSEN_FRAME += (CHOOSEN_FRAME == 2) ? -2 : 1;
    cerr << "Currently active eye frame: " << MODE[CHOOSEN_FRAME] <<"\n";

    break;
  // - 'o': cycle through the 3 objects being manipulated

  case 'm':
    if(CHOOSEN_FRAME == 0){
      WORLD_SKY = !WORLD_SKY;
      cerr << "Switching to " << SKY_MODE[WORLD_SKY?0:1] << " frame" << "\n";
    }
    break;

  case 'p':
    PICKING = true;
    cout << "PICKING: " << "ON" << endl;
    return;

  // - 'r': reset the scene
  case 'r':
    reset();
    break;
  }
  glutPostRedisplay();
}
	list<int>::iterator recent(list<int>::iterator p) {
		int key = *p;
		time.erase(p);
		return time.insert(time.end(), key);
	}
Example #18
0
void insert( list<intPoint>& mylist, int x, int y, int z, int N)
{
  if( mylist.empty())
  {
    intPoint temp;
    temp.val = 1;
    temp.diff = 0;
    temp.pair = N;
    mylist.push_back(temp);

    temp.val = N;
    temp.diff = 0;
    temp.pair = 1;
    mylist.push_back(temp);

    minVal = 1;
    maxVal = N;
  }
  else
  {
    list<intPoint>::iterator it = mylist.begin();
    while( it != mylist.end() && (*it).val < x)
      it++;

    list<intPoint>::iterator leftP = it;
    //cout << "leftP point to: " << (*it).val << endl;

    intPoint newLP, newRP;

    newLP.val = x;
    newLP.pair = y;
    if( leftP != mylist.begin())
    {
      leftP--;
      if( (*leftP).pair >= x)
        newLP.diff = z + (*leftP).diff;
      else
        newLP.diff = z;
      leftP++;
    }
    else
      newLP.diff = z;

    mylist.insert( leftP, newLP);
    //cout << "After insert leftP point to: " << (*it).val << endl;

    while( it != mylist.end() && (*it).val < y)
        it++;

    list<intPoint>::iterator rightP = it;
    //cout << "rightP point to: " << (*rightP).val << endl;

    if( rightP == leftP)
    {
      newRP.val = y;
      newRP.diff = newLP.diff;
      newRP.pair = x;
      mylist.insert( rightP, newRP);
    }
    else
    {
      newRP.val = y;
      rightP--;
      if( (*rightP).pair >= y)
        newRP.diff = z + (*rightP).diff;
      else
      newRP.diff = z;
      newRP.pair = x;
      rightP++;
      mylist.insert( rightP, newRP);
    }
    while( leftP != mylist.end())
    {
      if( (*leftP).val < y && (*leftP).val != x)
      {
        (*leftP).diff += z;
        //cout << "Increasin: " << (*leftP).val << " by: " << z << endl;
        leftP++;
      }
      else
        break;
    }

  }
  //printList( mylist);
}
Example #19
0
// ----------------------------------------------------------------------------
void f(const Entry& ee, list<Entry>::iterator p, list<Entry>::iterator q){

  phone_book.insert(p, ee);                                                     // add ee before the element referred to by p
  phone_book.erase(q);                                                          // remove the element referred to by q
}
Example #20
0
void peopleCallback(const people_msgs::PositionMeasurement::ConstPtr& people_meas)
{
list<PeoplePositionVelocity*>::iterator begin = people_position_velocity_.begin();
list<PeoplePositionVelocity*>::iterator end = people_position_velocity_.end();
list<PeoplePositionVelocity*>::iterator it1, it2;
bool found=0;
int i=0;
    for (it1=begin;it1!=end;it1++,i++)
    {
       if((*it1)->object_id_ == people_meas->object_id)
       {
        found=1;
        //if time stamp differ by time interval sec
        if (people_meas->header.stamp.toSec() - (*it1)->position_.stamp_.toSec() > time_interval)
        {
         Point pt;
         pointMsgToTF(people_meas->pos, pt);
	 (*it1)->v[0]=(pt[0]-(*it1)->position_[0])/( people_meas->header.stamp.toSec() - (*it1)->position_.stamp_.toSec() );
	 (*it1)->v[1]=(pt[1]-(*it1)->position_[1])/( people_meas->header.stamp.toSec() - (*it1)->position_.stamp_.toSec() );
	//it1->position=*people_meas;	
         (*it1)->position_[0] = pt[0];
         (*it1)->position_[1] = pt[1];
         (*it1)->position_[2] = pt[2];
	 (*it1)->position_.stamp_=people_meas->header.stamp;
        //publish velocity marker
	    double theta = atan2((*it1)->v[1],(*it1)->v[0]);
            visualization_msgs::Marker m;
            m.header.stamp = (*it1)->position_.stamp_;
            m.header.frame_id = fixed_frame;
            m.ns = "VELOCITY";
            m.id = i;
            m.type = m.ARROW;
            m.pose.position.x = (*it1)->position_[0];
            m.pose.position.y = (*it1)->position_[1];
            m.pose.position.z = 0;
 	    m.pose.orientation.x = 0.0;
   	    m.pose.orientation.y = 0.0;
  	    m.pose.orientation.z = sin(theta/2);
  	    m.pose.orientation.w = cos(theta/2);
	    double scale = sqrt( (*it1)->v[0] * (*it1)->v[0] + (*it1)->v[1] * (*it1)->v[1] );
	    //float scale = 2;
            m.scale.x = scale;
            m.scale.y = scale;
            m.scale.z = scale;
            m.color.a = 1;
            m.color.g = 1;
            m.lifetime = ros::Duration(0.5);
	    outfile<<scale<<"   "<<(*it1)->object_id_<<"\n";
            markers_pub_.publish(m);	 
	}
        break;
       }
    }
    if (!found)
    {
      Point pt;
      pointMsgToTF(people_meas->pos, pt);
      Stamped <Point> pos (pt,people_meas->header.stamp,people_meas->header.frame_id);
      list<PeoplePositionVelocity*>::iterator new_saved = people_position_velocity_.insert(people_position_velocity_.end(), new PeoplePositionVelocity(pos,people_meas->object_id));
    }
}
Example #21
0
		virtual void insert(int element) {
			l.insert(l.begin(), element);
		}
Example #22
0
void ArgParser::addOptionsToCommandLine(list<string> & commandLine) {
    commandLine.insert(commandLine.end(), javaOptions.begin(), javaOptions.end());
    commandLine.insert(commandLine.end(), bootclass);
    commandLine.insert(commandLine.end(), progArgs.begin(), progArgs.end());
}
Example #23
0
void exercise(list x, object y, object print)
{
    x.append(y);
    x.append(5);
    x.append(X(3));
    
    print("after append:");
    print(x);
    
    print("number of", y, "instances:", x.count(y));
    
    print("number of 5s:", x.count(5));

    x.extend("xyz");
    print("after extend:");
    print(x);
    print("index of", y, "is:", x.index(y));
    print("index of 'l' is:", x.index("l"));
    
    x.insert(4, 666);
    print("after inserting 666:");
    print(x);
    print("inserting with object as index:");
    x.insert(x[x.index(5)], "---");
    print(x);
    
    print("popping...");
    x.pop();
    print(x);
    x.pop(x[x.index(5)]);
    print(x);
    x.pop(x.index(5));
    print(x);

    print("removing", y);
    x.remove(y);
    print(x);
    print("removing", 666);
    x.remove(666);
    print(x);

    print("reversing...");
    x.reverse();
    print(x);

    print("sorted:");
    x.pop(2); // make sorting predictable
    x.pop(2); // remove [1,2] so the list is sortable in py3k
    x.sort();
    print(x);

    print("reverse sorted:");
#if PY_VERSION_HEX >= 0x03000000
    x.sort(*tuple(), **dict(make_tuple(make_tuple("reverse", true))));
#else
    x.sort(&notcmp);
#endif
    print(x);

    list w;
    w.append(5);
    w.append(6);
    w += "hi";
    BOOST_ASSERT(w[0] == 5);
    BOOST_ASSERT(w[1] == 6);
    BOOST_ASSERT(w[2] == 'h');
    BOOST_ASSERT(w[3] == 'i');
}
Example #24
0
bool apply_rules(
    list<int> &paths,
    map<string, Signal> &signals,
    map<string, Point> &points,
    list<Rule> &rules,
    map<int, set<int> > &edges)
{
  vector<Signal> v_signals;
  for (map<string, Signal>::iterator it = signals.begin(); it != signals.end(); ++it) {
    v_signals.push_back(it->second);
  }

  vector<Point> v_points;
  for (map<string, Point>::iterator it = points.begin(); it != points.end(); ++it) {
    v_points.push_back(it->second);
  }

  int max_point_v = v_points.size() * 6;

  map<string, list<Rule> > rules_from;
  list<Rule>::iterator itr = rules.begin();
  while (itr != rules.end()) {
    rules_from[itr->x].push_back(*itr);
    ++itr;
  }

  list<int>::iterator itp = paths.begin();
  while (itp != paths.end()) {
    // cout << "checking x: " << *itp << endl;
    int v = *itp;
    if (v >= max_point_v || !IS_TO_FRONT(v)) {
      ++itp;
      continue;
    }

    Point x = v_points[v/6];

    Rule *valid_rule = NULL;
    list<int>::iterator target = paths.begin();
    list<Rule>::iterator itr2 = rules_from[x.name].begin();
    list<Rule>::iterator end = rules_from[x.name].end();

    while (itr2 != end) {
      string y = itr2->y;
      Point &py = points[y];
      int away_front = py.vertices[0];

      list<int>::iterator itp2 = itp;
      while (itp2 != paths.end()) {
        if (*itp2 == away_front) {
          valid_rule = &(*itr2);
          target = itp2;
          break;
        }

        ++itp2;
      }

      if (valid_rule) {
        break;
      }

      ++itr2;
    }

    int back = *(++itp);
    string choice = IS_AWAY_BACK_NEG(back) ? "-" : "+";
    --itp;

    bool need_switch = false;
    if (valid_rule) {
      if (valid_rule->sign != choice) {
        need_switch = true;
      }
    }
    else {
      if (choice != "-") {
        need_switch = true;
        target = paths.end();
        target--;
      }
    }

    if (need_switch) {
      int to = *target;
      int from = back + 1;
      if (IS_AWAY_BACK_POS(back)) {
        from = back - 1;
      }

      list<int> alt_paths;
      alt_paths.push_back(from);
      bool valid_alt = search(from, to, alt_paths, edges);
      if (valid_alt) {
        list<int>::iterator it_ins = paths.erase(++itp, ++target);
        paths.insert(it_ins, alt_paths.begin(), alt_paths.end());

        for (int k = 0; k < alt_paths.size(); ++k) {
          --it_ins;
        }

        itp = it_ins;
        itp--;
      }
    }

    ++itp;
  }
}
Example #25
0
void inserta_ord (list <T> & L, const T & x) {
  typename list<T>::iterator p ;
  p = L.begin ();
  while (p != L.end () && *p < x) p++;     // avanza si *p < x
  L.insert (p, x);
} // end void
Example #26
0
File: ZM_DS.cpp Project: z163/Count
 void mySplice(int key) { // assume in the list
     // cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
     list<CacheNode>::iterator itr = cacheMap[key];
     cacheList.insert(cacheList.begin(), *cacheMap[key]);
     cacheList.erase(itr);
 }
Example #27
0
 void insertRow(RowIter it, const string& key, int value) {
     it = rows.insert(it, Row(value, key));
     iterMap[key] = make_pair(it, it->strs.begin());
 }
int main(){
	 int n=0,m=0,k=0,q=0;
	
	scanf("%d%d%d%d",&n,&m,&k,&q);
	cout<<n<<m<<k<<q<<endl;
	int windows[n][2];
	for(int i=0;i<n;i++)
	{	
		windows[i][0]=windows[i][1]=0;
	}
	for(int i=0;i<k;i++)
	{
		person p;
		p.id=i;
		scanf("%d",&(p.time));
		Outline.push_back(p);
	}
	for(deque<person>::iterator i=Outline.begin();i!=Outline.end();i++)
	{
		cout<<" "<<i->time<<" ";
	}
	cout<<"\n";
	while(true)
	{
		if (timer>LIMIT)
			break;
	
		//入线 
		while(num<n*m)
		{ 
		    Min=0;
		    currpeo=windows[0][0];
		    for(int i=0;i<n;i++)
			    if(windows[i][0]<currpeo)
			    {
			    	Min=i;
			    	currpeo=windows[i][0];
			    }
			num++;
			if (Outline.size()==0)
			    break;
			person pl=Outline.front();
			windows[Min][1]+=pl.time;
			pl.donetime=windows[Min][1];
			pl.window=Min;
			for(int i=0;i<n;i++)
			{
				cout<<windows[i][0]<<" "<<windows[i][1]<<endl; 
			}
			list<person>::iterator ite = --Inline.end();
			for (; ite !=Inline.begin(); --ite)
			{
				cout<<pl.donetime<<" "<<ite->donetime<<ite->id<<endl; 
				if (pl.donetime>ite->donetime)
					cout<<"looped "<<ite->id<<" ";
					break;
			}
			cout<<"looped2 "<<ite->id<<"\n";
			Inline.insert(ite,pl);
			for (list<person>::iterator it = Inline.begin(); it !=Inline.end(); ++it)
			{
			    cout<<it->time<<"-->";
				//"<<ite->time<<" "<<ite->window<<" "<<ite->donetime<<endl;
			}
			cout<<"\n";
			Outline.pop_front();
		}
		//出线 
		if (Inline.size()>0)
		{
		 person lp=Inline.front();
		 Inline.pop_front();
		 num--;
		 donepson[lp.id]=lp;
		 timer=lp.donetime;
	    }
	    else
	    	break;
	}
	//query 查询 
	for(int i=0;i<q;i++)
	{
		int tmpq;
		int donetime;
		scanf("%d",&tmpq);
		if(donepson.find(tmpq-1)==donepson.end())
			cout<<"Sorry"<<endl;
		else
		{
			donetime=donepson[tmpq-1].donetime;
			printf("%02d:%02d\n",8+donetime/60,donetime%60);
		}
	}
}
Example #29
0
 void add_more(const list<T>& more)
 {
     std::lock_guard<std::mutex> lock(_mtx);
     _datas.insert(_datas.end(), more.begin(), more.end());
 }
Example #30
0
int init(){
  L.clear();
  for(int i=400;i<600;i++)
    for(int j=i+1;j<=600;j++)
      L.insert(L.end(),make_pair(i,j));
}