void addNeighbors(int x, int y, unordered_map<string,Point*>& pointsQueue){
    Point* p1 = new Point(x+1, y);
    string key1 = makeString(p1);
    
    if(isAccessible(x+1,y) && pointsQueue.count(key1)== 0){
        pointsQueue.insert(make_pair<string, Point*>( key1,p1));
        addNeighbors(p1->x, p1->y, pointsQueue);
    }else
        delete p1;
    
    Point* p2 = new Point(x-1, y);
    string key2 = makeString(p2);
    if(isAccessible(x-1,y) && pointsQueue.count(key2)== 0){
        pointsQueue.insert(make_pair<string, Point*>(key2,p2));
        addNeighbors(p2->x, p2->y, pointsQueue);
    }else
        delete p2;
    
    Point* p3 = new Point(x, y + 1);
    string key3 = makeString(p3);
    if(isAccessible(x,y +1) && pointsQueue.count(key3)== 0){
        
        pointsQueue.insert(make_pair<string, Point*>(key3, p3));
        addNeighbors(p3->x, p3->y, pointsQueue);
    }else
        delete p3;
    
    Point* p4 = new Point(x, y - 1);
    string key4 = makeString(p4);
    if(isAccessible(x,y-1) && pointsQueue.count(key4)== 0){
        pointsQueue.insert(make_pair<string, Point*>(key4, p4));
        addNeighbors(p4->x, p4->y, pointsQueue);
    }else
        delete p4;
}
    bool isMatch(const char *s, int pos, vector<pair<char, int> > &pattern, int ppos) {
    	unsigned int id = (pos << 16) | ppos;
    	
    	unordered_map<unsigned int, bool>::iterator iter = memo.find(id);
		if (memo.find(id) != memo.end()) return iter->second;
		
		bool res = false;
		
		if (ppos == pattern.size()) {
			res = s[pos] == '\0';
			memo.insert(make_pair(id, res));
			return res;
		}
		int i = pos;
		pair<char, int> &p = pattern[ppos];

		int 	offset = (p.second == SINGLE) ? 0 : -1;
		char 	ch = '\0';
		while (offset < 0 || (ch = s[pos + offset]) != '\0') {
			if (offset >= 0 && !cmp(ch, p.first)) {
				res = false;
				break;
			}
			if (isMatch(s, pos + offset + 1, pattern, ppos + 1)) {
				res = true;
				break;
			}
			if (p.second == SINGLE) break;
			offset++;
		}
		memo.insert(make_pair(id, res));
		return res;
	}
Example #3
0
void getDataFromServer(string uri)
{
	int count=0;
	// http get request
	shared_ptr<HttpConnector> getrequest(new HttpConnector);
	//HttpConnector *getrequest = new HttpConnector;
	//result = getrequest->httpConnect(usrInput);
	result = getrequest->httpConnect(uri);
	if (result != "not valid")
	{
		shared_ptr<Parser> htmlParse(new Parser(result));
		//Parser *htmlParse = new Parser(result);
		// 성공하지 못했을 때 error코드 출력
		if (htmlParse->getstatusNum() != "200")
		{
			ret.push_back("\n페이지 요청 결과 : " + htmlParse->getstatusNum() + "  " + htmlParse->getstatus());
		}
		else
		{
			// html
			result = htmlParse->getHtml();
			shared_ptr<HTMLParser> htmlInfo(new HTMLParser(result));
			//HTMLParser *htmlInfo = new HTMLParser(result);
			ret = htmlInfo->getResult();
			hyperLinkMap = htmlInfo->getHyperLink();
			for (unsigned int i = 0; i < ret.size(); i++)
			{
				if (ret[i].length() >= 5)
				{
					if (ret[i].substr(ret[i].length() - 5, 5) == "image")
					{
						vector<char> tempimage;
						unordered_map<string, char*>::iterator FindIter = imagecache.find(ret[i].substr(0, ret[i].length() - 6));
						// cache image 찾았다면
						if (FindIter != imagecache.end())
						{
							images.insert(pair<int, char*>(count, FindIter->second));
							imageSize.insert(pair<int, int>(count, imagecacheSize.find(ret[i].substr(0, ret[i].length() - 6))->second));
							replace(ret, ret[i], "image");
							count++;
						}
						else
						{
							if (threads.size() < 50)
							{
								threads.push_back(thread(imageRequset, ret[i].substr(0, ret[i].length() - 6), count));
							}
							count++;
						}
					}
				}
			}
		}
	}
	else
	{
		ret.push_back("not valid");
	}
	for (auto& th : threads) th.detach();
}
//helper function to prefill keyboard grid.
void fillKeyboard(unordered_map< char, vector<int> > &keyboard){

	string line1 = "qwertyuiop";
	string line2 = "asdfghjkl";
	string line3 = "zxcvbnm";

	for (int i = 0; i< line1.length(); i++ ){
		vector<int> position;
		position.push_back(0);
		position.push_back(i);
		keyboard.insert(make_pair(line1[i], position));
	}
	for (int i = 0; i< line2.length(); i++ ){
		vector<int> position;
		position.push_back(1);
		position.push_back(i);
		keyboard.insert(make_pair(line2[i], position));
	}
	for (int i = 0; i< line3.length(); i++ ){
		vector<int> position;
		position.push_back(2);
		position.push_back(i);
		keyboard.insert(make_pair(line3[i], position));
	}

	return;
}
Example #5
0
	Arguments(int argc, char **argv, bool ignoreFirst = true) {
		this->argc = argc;
		this->argv = argv;
		this->ignoreFirst = ignoreFirst;

		for (int i = ignoreFirst ? 1 : 0; i < argc; i++) {
			string token = string(argv[i]);
			tokens.push_back(token);
		}

		string currentKey = "";
		map.insert({ currentKey, {} });
		for (string token : tokens) {
			if(startsWith(token, "---")) {
				cerr << "Invalid argument: " << token << endl;
				exit(1);
			} else if (startsWith(token, "--")) {
				currentKey = token.substr(2);
				map.insert({ currentKey,{} });
			} else if (startsWith(token, "-")) {
				currentKey = token.substr(1);
				map.insert({ currentKey,{} });
			} else {
				map[currentKey].push_back(token);
			}
		}
	}
Example #6
0
void init() {
	memset(children, -1, sizeof(children));

	int n; scanf("%d", &n);
	for (int i=0; i<n; ++i) {
		scanf("%s %s", name[0], name[1]);
		string sname1(name[0]);
		string sname2(name[1]);

		auto it = namemap.find(sname1);
		if (it == namemap.end()) {
			it = namemap.insert(pair<string, int>(sname1, first)).first;
			names[first++] = move(sname1);
		}
		int cid1 = it->second;

		it = namemap.find(sname2);
		if (it == namemap.end()) {
			it = namemap.insert(pair<string, int>(sname2, first)).first;
			names[first++] = move(sname2);
		}
		int cid2 = it->second;
		
		links[lfirst].cid = cid2;
		links[lfirst].nxt = children[cid1];
		children[cid1] = lfirst++;
	}

	dfs(0, 0);
	prermq();
}
int id_of(string &s, unordered_map<string, int> &mp) {
	auto it = mp.find(s);
	if (it == mp.end()) {
		mp.insert({s, mp.size()});
		return mp.size() - 1;
	} else	return it->second;
}
Example #8
0
void dispatchErrors(vector<string>& vectSequences, uint k, unordered_map<string, vector<int>>& kmerToSignature, unordered_map<string, vector<pair<uint, uint>>>& kmerToReadPosi, unordered_map<uint, vector<uint>>& readToErrorPosition){
	string kmer;
	uint precP(0);
	for (uint r(0); r < vectSequences.size(); ++r){
		for (uint p(0); p < vectSequences[r].size() - k + 1; ++p){
			kmer =  vectSequences[r].substr(p, k);
			auto got = kmerToSignature.find(kmer);
			if (got != kmerToSignature.end()){
				uint sumSignature(0);
				for (uint n : got->second){
					sumSignature += n;
				}
				if (sumSignature > THRESHOLD1) { // we consider the kmer is errorless
					pair<uint, uint> rp({r, p});
					auto got2 = kmerToReadPosi.find(kmer);
					if (got2 != kmerToReadPosi.end()){
						got2->second.push_back(rp);
					} else {
						kmerToReadPosi.insert({kmer, {rp}});
					}
				} else { // kmer with error
					readToErrorPosition[r].push_back(p);
				}
			}
		}
	}
}
Example #9
0
void Solution508::postOrder(TreeNode *root, unordered_map<int, int> &counter, int &maxCount)
{
    if (root == nullptr)
        return;

    if (root->left)
    {
        postOrder(root->left, counter, maxCount);
        root->val += root->left->val;
    }
    if (root->right)
    {
        postOrder(root->right, counter, maxCount);
        root->val += root->right->val;
    }

    int count = counter.count(root->val);
    if (count == 0)
    {
        counter.insert({root->val, 1});
        count = 1;
    } else
        count = ++ counter[root->val];
    maxCount = std::max(maxCount, count);
}
Example #10
0
    void set(int key, int value)
    {
        auto itItemMap = m_itemMap.find(key);

        if (itItemMap != m_itemMap.end())
        {
            // The item with this key exists in the 
            // cache, so promote the item to the list 
            // tail. Note that itItemMap->second is 
            // updated with the new value.
            Promote(itItemMap->second);

            // Set the value.
            itItemMap->second->value = value;
        }
        else
        {
            // Check whether the cache has used all 
            // its capacity.
            if (m_itemMap.size() >= m_capacity)
            {
                // Erase the least recently used item.
                m_itemMap.erase(m_items.front().key);
                m_items.pop_front();
            }

            // Insert the item into the list and the key-to-list-iterator 
            // pair into the map.
            m_itemMap.insert(make_pair(
                key, m_items.insert(m_items.end(), Item(key, value))));
        }
    }
Example #11
0
 S* add_child(M &move) {
     auto child = create_child(move);
     auto key = move.hash();
     auto pair = children.insert({key, child});
     auto it = pair.first;
     return it->second.get();
 }
Example #12
0
	void set(int key, int value) {
		if (capacity == 0) {
			return ;
		}
		unordered_map<int,QNode*>::iterator itr;
		QNode *tmp;
		itr = keyAddress.find(key);
		if (itr == keyAddress.end()) {
			tmp = new QNode(key, value);
			keyAddress.insert(pair<int, QNode*>(key, tmp));
		} else {
			tmp = itr->second;
			tmp->value = value;
			tmp->pre->next = tmp->next;
			tmp->next->pre = tmp->pre;
		}
		if (keyAddress.size() > capacity) {
			keyAddress.erase(rear.pre->key);
			rear.next = rear.pre;
			rear.pre = rear.pre->pre;
			rear.pre->next = &rear;
			delete rear.next;
			rear.next = NULL;
		}
		tmp->next = front.next;
		tmp->next->pre = tmp;
		front.next = tmp;
		tmp->pre = &front;
	}
Example #13
0
void loadProgram()
{
    std::ifstream fin;
    int count = 0;
    
    for (auto iter = filenames.cbegin(); iter != filenames.cend(); ++iter)
    {
        fin.open(*iter);
        if (fin.fail())
        {
            std::cerr << "Error: file " << *iter << "does not exsist!\n";
            exit(-1);
        }
        string temp;
        while (std::getline(fin, temp))
        {
            vector<string> instruction;
            std::istringstream iss(temp);
            string word;
            while (iss >> word)
            {
                instruction.push_back(word);
            }
            if (instruction[0] == "label" || instruction[0] == "function")
                instruction_address.insert({ instruction[1], count });
            instructions_ram.push_back(instruction);
            count++;
        }
        fin.close();
    }
    vector<string> end;
    end.push_back("end");
    instructions_ram.push_back(end);
}
Example #14
0
	void set(int key, int value) {
		count++;
		if (valuemap.find(key) == valuemap.end())
		{
			// not find key in the cache

			if (size == cap)
			{
				// cache full, need deletion
				map<int, int>::iterator it = timekey.begin();
				int keytodelete = it->second;
				timekey.erase(it);
				keytime.erase(keytodelete);
				valuemap.erase(keytodelete);
				size--;
			}

			valuemap.insert(pair<int, int>(key, value));
			keytime.insert(pair<int, int>(key, count));
			timekey.insert(pair<int, int>(count, key));
			size++;

		}
		else
		{
			// find key in cache
			int time = keytime[key];
			timekey.erase(time);
			timekey.insert(pair<int, int>(count, key));
			keytime[key] = count;
			valuemap[key] = value;
		}
	}
Example #15
0
void TestSchemaEvolution::gatherAllClasses() {
  static const char *classes[] = {"TH1F",
                                  "TH1S",
                                  "TH1D",
                                  "TH1I",
                                  "TH2F",
                                  "TH2S",
                                  "TH2D",
                                  "TH2I",
                                  "TH3F",
                                  "TH3S",
                                  "TH3D",
                                  "TH3I",
                                  "TProfile",
                                  "TProfile2D",
                                  "TF1",
                                  0};

  int i = 0;
  while (classes[i]) {
    TClass *tcl = TClass::GetClass(classes[i]);
    if (!tcl)
      continue;
    unique_classes_.insert(std::make_pair(classes[i], tcl->GetClassVersion()));
    analyseClass(tcl);
    ++i;
  }
}
Example #16
0
 void set(int key, int value) {
     auto i = cache.find(key);
     
     if (maxSize == 0)
         return;
     if (i != cache.end()) {
         Item *item = i->second;
         remove(item);
         insert(item);
         item->value = value;
     } else {
         if (currSize == maxSize) {
             // remove at rear
             Item *item = lru.prev;
             //cout << "remove " << item->key << " at rear" << endl;
             remove(item);
             cache.erase(item->key);
             delete item;
             currSize--;
         }
         Item *newItem = new Item(key, value);
         insert(newItem);
         cache.insert(make_pair(key, newItem));
         currSize++;
     }
 }
Example #17
0
 void AddOne(unordered_map<char, int>& m, char c) {
     if(m.find(c) == m.end()) {
         m.insert(make_pair(c, 1));
     } else {
         ++m[c];
     }
 }
Example #18
0
void process_incoming(multiset<order, IN> &incoming, multiset<order, WAIT> &waiting, int seq)
{
    int size, price; cin >> size >> price;
    auto top_waiting = waiting.begin();
    for ( ; size && top_waiting != waiting.end(); ++top_waiting)
    {
        if (can_trade(price, top_waiting, waiting))
        {
            int trade_price = top_waiting->price;
            int trade_size = min(top_waiting->size, size);
            cout << "TRADE " << trade_size << " " << trade_price << '\n';
            size -= trade_size;
            top_waiting->size -= trade_size;

            price2size[trade_price] -= trade_size;
            if (!top_waiting->size)
                gone.insert(top_waiting->seq);
            else
                break;
        }
        else break;
    }
    waiting.erase(waiting.begin(), top_waiting);
    if (size)
    {
        auto p2s_pit = price2size.insert({price, size});
        if (!p2s_pit.second)
            p2s_pit.first->second += size;
        auto it = incoming.insert(incoming.begin(), {price, seq, size});
        add_seq2iter_map(seq, it, &incoming);
    }
    else
        gone.insert(seq);
}
bool populateVec7Messages(unordered_map<string,string>& htabVecMessages){

	ifstream infile(vec7messagesFileName);
	if(infile.is_open()){
		string line;
		while(getline(infile,line)){
			if(line.find(",") != string::npos){
				vector<string> messageLine = splitStringByDelimiter(line,',');
				if(messageLine.size() == 2){
					string key = trimWhiteSpaces(messageLine[0]);
					string value = messageLine[1];
					if(htabVecMessages.find(key) != htabVecMessages.end()){
						string temp = htabVecMessages.at(key);
						temp = temp + ";" + value;
						htabVecMessages.at(key) = temp;
					}
					else
						htabVecMessages.insert(make_pair<string,string>(key,value));
				}
			}
		}
		infile.close();
	}
	else
		return false;
	return true;
}
Example #20
0
void apply_cumulative_l1_penalty(
    unordered_map<idxT, weightT> &weights,
    const vector<pair<idxT, weightT>> &gradients,
    weightT learning_rate,
    weightT cumulative_l1_penalty,
    unordered_map<idxT, weightT> &cumulative_l1_actual_penalty) {

    for (auto gradient = gradients.begin(); gradient != gradients.end(); ++gradient) {
        idxT idx = gradient->first;
        weightT gradient_val = gradient->second;
        auto weight = weights.find(idx);
        weightT half_update_weight = weight->second + gradient_val * learning_rate;
        auto last_actual_penalty = cumulative_l1_actual_penalty.find(idx);
        if (last_actual_penalty == cumulative_l1_actual_penalty.end()) {
            last_actual_penalty = cumulative_l1_actual_penalty.insert(make_pair(idx, 0.0)).first;
        }
        if (half_update_weight > 0) {
            weight->second = max(0.0, half_update_weight - (cumulative_l1_penalty + last_actual_penalty->second));
        } else if (half_update_weight < 0) {
            weight->second = max(0.0, half_update_weight + (cumulative_l1_penalty - last_actual_penalty->second));
        }

        last_actual_penalty->second += weight->second - half_update_weight;
    }
}
Example #21
0
 static void InsertLanguage(unordered_map< string, int >& Language, string lang)
 {
     if (!FIND(Language, lang))
     {
         Language.insert(make_pair(lang, index_counter++));
     }
 }
Example #22
0
/* De Casteljau Algorithm for generating a point from the Curve.
* r is the upper index of the point, i the lower and t the parameter
* which shows the ratio we will divide in. We use the memoization technique
* to reduce the number of recursive calls to the function. Store the already
* found points in the unordered_map foundPoints and avoid calculating them 
* more than once */
Point generatePoint(int r, int i, double t,
	unordered_map<std::pair<int, int>, Point> &foundPoints) {
	if (r == 0)
		return controlPolygon[i];

	/* In order to find the point with lower index i and upper r>0 first
	* we need to find b(i)(r-1) and b(i+1)(r-1) and then interpolate
	* between them with t -> b = (1-t)*b(i)(r-1) + t*b(i+1)(r-1)
	*/

	Point p1, p2;
	std::pair<int, int> index1, index2;
	index1 = std::make_pair(r - 1, i);
	index2 = std::make_pair(r - 1, i + 1);
	unordered_map<std::pair<int, int>, Point>::const_iterator iter1 =
		foundPoints.find(index1);
	unordered_map<std::pair<int, int>, Point>::const_iterator iter2 =
		foundPoints.find(index2);
	/* Check if we have already calculated the first point and if we
	* haven't than make a recursive call to the same function to find it.
	* If we have already calculated it just use it. */
	if (iter1 == foundPoints.end()) {
		p1 = generatePoint(r - 1, i, t, foundPoints);
		foundPoints.insert(std::make_pair(index1, p1));
	}
	else {
		p1 = iter1->second;
	}
	/* Check if we have already calculated the second point and if we
	* haven't than make a recursive call to the same function to find it.
	* If we have already calculated it just use it. */
	if (iter2 == foundPoints.end()) {
		p2 = generatePoint(r - 1, i + 1, t, foundPoints);
		foundPoints.insert(std::make_pair(index2, p2));
	}
	else {
		p2 = iter2->second;
	}

	/// Interpolate between the already found points
	Point current;

	current.x = (1 - t) * p1.x + t * p2.x;
	current.y = (1 - t) * p1.y + t * p2.y;

	return current;
}
Example #23
0
void onConn(shared_ptr<TcpConn> conn)
{
	DEBUG("have new client connect server!");
	g_connMtx.lock();
	g_connlist.insert(pair<int,shared_ptr<TcpConn>>(conn->getSocket(),conn));
	g_connMtx.unlock();
	return;
}
Example #24
0
	void insertEdge(char start, char end, int weight){
		vertices.insert(start);
		vertices.insert(end);
		string string1, string2;
		if (edges.find(string1.append(1, start).append(1, end)) == edges.end() && 
			edges.find(string2.append(1, end).append(1, start)) == edges.end())
			edges.insert(make_pair(string1, weight));
	}
Example #25
0
 void build_tlb() {
     int pw = 1;
     for (int i=0; i<3; i++) {
         for (int j=1; j<=9; j++) {
             string rm;
             for (int k=0; pattern[j][k] != '\0'; k++) {
                 rm.push_back(roman[i][ pattern[j][k] - '0' ]);
             }
             a2i.insert(make_pair(rm, pw * j));
         }
         pw *= 10;
     }
 
     a2i.insert(make_pair("M", 1000));
     a2i.insert(make_pair("MM", 2000));
     a2i.insert(make_pair("MMMM", 3000));
 }
Example #26
0
// 前方一致検索による単語リスト
void f_search(map<string, int>& words, unordered_map<string, int>& um, string s) {
	typedef map<string, int>::const_iterator cit;

	for(cit it = words.begin(); it != words.end(); ++it) {
		if((s.length() <= 1 && it->first.rfind(s, s.length() - 1) != string::npos)
			|| (s.length() > 1 && it->first.rfind(s, s.length() - 2) != string::npos))
			um.insert(make_pair(it->first, it->second));
	}
}
// A* Greedy
// find a solution and print the list of states to get to it
string treeSearch(const SearchProblem& problem) {
	SearchNodesList fringe;
	auto initialNode = make_shared<SearchNode>(problem.GetInitialState());
	nodesHistory.insert(make_pair(initialNode->state_.toString(), initialNode));
	fringe.push_back(initialNode);

	while (!fringe.empty()) {
		auto currNode = selectFrom(fringe);
		if (problem.TestGoal(currNode->state_))
			return pathTo(currNode.get());
		SearchNodesList newNodes = expand(problem, currNode.get());
		for (auto& node : newNodes) {
			nodesHistory.insert(make_pair(node->state_.toString(), node));
			fringe.push_back(node);
		}
	}
	return "No solution!";
}
 WordDistance(vector<string>& words) {
     for (int i=0; i<words.size(); i++) {
         auto it = wordToLocations.find(words[i]);
         if (it == wordToLocations.end()) {
             wordToLocations.insert(make_pair(words[i], unordered_set<int>()));
         }
         wordToLocations[words[i]].insert(i);
     }
 }
Example #29
0
 void setDeploymentStart(const string deploymentId, const string manifest) {
   DeployInfo info;
   info.id = deploymentId;
   info.status = DeployStatus::PENDINGSTART;
   info.manifest = manifest;
   PullStatus pullStatus;
   info.pullStatus = pullStatus;
   activeDeployments.insert(make_pair(deploymentId, info));
 }
Example #30
0
  pair<TValue &, bool> Get(TKey const & key)
  {
    auto r = m_map.insert(make_pair(key, TValue()));

    ++m_accesses;
    if (r.second)
      ++m_misses;

    return pair<TValue &, bool>(r.first->second, r.second);
  }