Example #1
0
int main()
{
    srand(1337);

    //Set<int> *s = new ArrayIntSet(60000000);
    //Set<int> *s = new BsVectorSet<int>();
    //Set<double> *s = new ListSet<double>();
    Set<double> *s = new OrderedVectorSet<double>();

    for(int i = 0; i != 20; i++) {
        s->insert(rand() % 30);
    }

    for(int i = 0; i != 30; i++) {
        cout << i << ": " << (s->contains(i) ? "Yes" : "No") << endl;
        if (i % 2 == 0) {
            s->remove(i);
        }
    }
    cout << endl;

    for(int i = 0; i != 30; i++) {
        cout << i << ": " << (s->contains(i) ? "Yes" : "No") << endl;
    }

    for(int i = 0; i != 100000; i++) {
        s->insert(rand() % 55789127);
    }

    cout << "Done inserting" << endl;

    for(int i = 0; i != 1000000; i++) {
        s->contains(i);
    }
}
Example #2
0
public List<String> wordBreak(String s, Set<String> dict) {
    List<String> result = new ArrayList<String>();
    for(int j = s.length() - 1; j >= 0; j--){
        if(dict.contains(s.substring(j)))
            break;
        else{
            if(j == 0)
                return result;
        }
    }
    for(int i = 0; i < s.length()-1; i++)
    {
        if(dict.contains(s.substring(0,i+1)))
        {
            List<String> strs = wordBreak(s.substring(i+1,s.length()),dict);
            if(strs.size() != 0)
                for(Iterator<String> it = strs.iterator();it.hasNext();)
                {
                    result.add(s.substring(0,i+1)+" "+it.next());
                }
        }
    }
    if(dict.contains(s)) result.add(s);
    return result;
}
Example #3
0
static void generateAllPossibleWords(const Grid<char> & boggleBoard, Set<string> & wordsSpottedSoFar,
                                     const Lexicon & english, int rowIndex, int colIndex, string buildingWord,
                                     Set<coord> wordPath){
    buildingWord += boggleBoard[rowIndex][colIndex];
    if (buildingWord.size() >= kMinGuessLength && english.contains(buildingWord)
           && !wordsSpottedSoFar.contains(buildingWord)) {
         wordsSpottedSoFar.add(buildingWord);
         recordWordForPlayer(buildingWord, COMPUTER);
    }
    if (!english.containsPrefix(buildingWord)) return;
    for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <=1; j++){
            if(isShiftValid(boggleBoard, rowIndex, colIndex, i, j)){
                coord nextPos;
                nextPos.row = rowIndex + i;
                nextPos.col = colIndex + j;
                if (!wordPath.contains(nextPos)){
                    wordPath.add(nextPos);
                    generateAllPossibleWords(boggleBoard, wordsSpottedSoFar, english,
                                             rowIndex + i, colIndex + j, buildingWord, wordPath);
                    wordPath.remove(nextPos);
                }
            }
        }
    }
}
Example #4
0
/*
 * Recursive Computer Search
 *
 * Recursively searches the Boggle board to find all the
 * words that can be made on the board and haven't
 * been guessed correctly by the human player
 */
void recursiveComputer(int row, int col, string word, Grid<string>& board, Lexicon& dictionary, Set<string>& results, Grid<bool>& visitedCubes, int& computerScore, Set<string>& usedWords){
    if(!board.inBounds(row, col)) return;
    if(dictionary.contains(word) && word.length() >= 4) {
        if (!results.contains(word) && !usedWords.contains(word)) {
            computerScore += word.length() - 3;
            results.add(word);
        }
    }

    if(!dictionary.containsPrefix(word)){
        return;
    }
    word = word + board[row][col];

    visitedCubes[row][col] = true;

    for(int i = -1; i <= 1; i++){
        for(int j = -1; j <= 1; j++){
            if(visitedCubes.inBounds(row + i, col + j) && !visitedCubes[row + i][col + j]){
                recursiveComputer(row + i, col + j, word, board, dictionary, results, visitedCubes, computerScore, usedWords);
            }
            if(visitedCubes.inBounds(row + i, col + j) && dictionary.contains(word) && !results.contains(word) && word.length() >=4) {
                computerScore += word.length() - 3;
                results.add(word);
            }
        }
    }
    visitedCubes[row][col] = false;
}
Example #5
0
int main()
{

	int numbers[10] = {1,2,3,4,5,6,7,8,9,0};
	Set<int> a;
	Set<int> b(a);
	Set<int> c(numbers, 10);
	
	b = a;
	assert(b==a);
	
	a = b & c;
	assert(a.empty());
	
	a = b & 3;
	assert(a.empty());
	
	a = 3 & b;
	assert(a.empty());
	
	b &= a;
	assert(b.empty());
	
	b &= 3;
	assert(b.empty());
	
	b = a | c;
	assert(b == c);
	
	b = a | 3;
	assert(b.size() == 1);
	
	b = 3 | a;
	assert(b.size() == 1);
	
	a |= b;
	assert(a.size() == 1);
	
	a |= 3;
	assert(a.size() == 1 && a.contains(3));
	

	assert(!(a != b));
	
	assert(a< c);
	
	assert(3 < c);
	c > a;
	c > 3;
	a <= c;
	c >= a;
	a.contains(3);
	a.empty();
	a.size();
	a.insert(99);
	cout << a << endl << c;
	a.remove(99);
	
}
static void testExtractionOperator() {
   declare(istringstream ss("{one, two, three}"));
   reportMessage("Set<string> set;");
   Set<string> set;
   trace(ss >> set);
   test(set.size(), 3);
   test(set.contains("one"), true);
   test(set.contains("two"), true);
   test(set.contains("three"), true);
}
bool MultipleDeriv
::isInRequiredSet(const Set<MultiSet<int> >& funcCombinations,
  const Set<MultiIndex>& multiIndices) const
{
  if (spatialOrder() == 0)
  {
    return funcCombinations.contains(dofIDs());
  }
  else
  {
    return multiIndices.contains(spatialDeriv());
  }
}
int main() {
	Set ss;
	ss.insert("focaccia");
	assert(!ss.contains(""));
	ss.insert("tortilla");
	ss.insert("");
	ss.insert("lavash");
	assert(ss.contains(""));
	ss.erase("focaccia");
	assert(ss.size() == 3);
	assert(ss.contains("lavash")); 
	assert(ss.contains("tortilla")); 
	assert(ss.contains(""));
}
Example #9
0
int main()
{
	Set<string> round;   // Round things
	Set<string> green;   // Green things

	round.add("peas");   // Sample data for both sets
	round.add("ball");
	round.add("pie");
	round.add("grapes");
	green.add("peas");
	green.add("grapes");
	green.add("garden hose");
	green.add("grass");

	cout << "Contents of set round: ";
      	round.output();
	cout << "Contents of set green: ";
       	green.output();

	cout << "ball in set round? " <<
		round.contains("ball") << endl;
	cout << "ball in set green? " <<
		green.contains("ball") << endl;

	cout << "ball and peas in same set? ";
	if ((round.contains("ball") && round.contains("peas")) ||
	    (green.contains("ball") && green.contains("peas")))
	    cout << "  true" << endl;
	else
            cout << "  false" << endl;

	cout << "pie and grass in same set? ";
	if ((round.contains("pie") && round.contains("grass")) ||
	    (green.contains("pie") && green.contains("grass")))
	    cout << "  true" << endl;
	else
            cout << "  false" << endl;

	cout << "Union of green and round: " << endl;
	Set<string> *unionset = round.setUnion(green);
	unionset->output();
	delete unionset;

	cout << "Intersection of green and round: " << endl;
	Set<string> *interset = round.setIntersection(green);
	interset->output();
	delete interset;

	return 0;
}
Example #10
0
int GoNext(int start,Vector<int> squares){ // it is better not to return value for this kind of function
	int value;
	//cout << "start : " << start << endl;
	path.add(start);
	if (squares.getAt(start)==0) {
		answer=1;
		return 1;
	}else if (curnum > 1000) {
		answer=2;
		return 2;
	}else {
		curnum++;
		value=squares.getAt(start);
		//cout << "value: " << value << endl;
		if ((start+value) >= squares.size()) {
			//cout << "1" << endl;
			GoNext((start-value),squares);
		}else if ((start-value) < 0) {
			//cout << "2" << endl;
			GoNext((start+value),squares);
		}else {
			/*cout << "3" << endl;
			 // This would go into infinite loop
			if (switchon) {
				GoNext((start+value),squares);
				GoNext((start-value),squares);
				switchon=false;
			}else {
				GoNext((start-value),squares);
				GoNext((start+value),squares);
				switchon=true;
			}*/
			if (!path.contains(start+value)) {
				GoNext((start+value),squares);
			}else if (!path.contains(start-value)) {
				GoNext((start-value),squares);
			}else {
				GoNext((start-value),squares);
				GoNext((start+value),squares);
			}

			
			
		}

	}
    
}
Example #11
0
bool WordIsValid(string word, Grid<string> & board, Lexicon & lex, Set<string> & wordsSeen) {
	if (word.length() < 4) {
		return false;
	} else if (wordsSeen.contains(word)) {		//already seen the word
		return false;	
	} else if (!lex.containsWord(word)) {		//not a word according to the dictionary
		return false;
	} else {
		Vector<locationT> empty;
		Vector<Vector<locationT> > results;
		Findable(board, word, -1, -1, empty, results);
		if (results.size() == 0) {							//no paths were found for the word, so word can't be found
			return false;
		} else {
			Vector<locationT> answer = results[0];			//at least one path was found, so return true and highlight the cubes
			for (int i = 0; i < answer.size(); i++) {
				HighlightCube(answer[i].numRow, answer[i].numCol, true);
			}
			Pause(.5);
			for (int i = 0; i < answer.size(); i++) {		//then un-highlight the cubes
				HighlightCube(answer[i].numRow, answer[i].numCol, false);
			}
			return true;
		}
	}
}
static std::string addAutograderButton(GWindow& gui, const std::string& text, const std::string& icon) {
    static Set<char> usedMnemonics;

    std::string html = "<html><center>" + stringReplace(text, "\n", "<br>") + "</center></html>";
    GButton* button = new GButton(html);
    STATIC_VARIABLE(AUTOGRADER_BUTTONS).add(button);

    // set mnemonic shortcut
    char mnemonic = '\0';
    for (int i = 0; i < (int) text.length(); i++) {
        if (isalpha(text[i]) && !usedMnemonics.contains(text[i])) {
            mnemonic = text[i];
            break;
        }
    }
    if (mnemonic) {
        usedMnemonics.add(mnemonic);
        button->setMnemonic(mnemonic);
        button->setAccelerator("ctrl " + charToString(mnemonic));
    }

    if (!icon.empty()) {
        button->setIcon(icon);
        button->setTextPosition(SwingConstants::SWING_CENTER, SwingConstants::SWING_BOTTOM);
    }
    gui.addToRegion(button, "SOUTH");
    return html;
}
Example #13
0
bool solvePuzzle(Grid<MarbleType>& board, int marblesLeft, Set<uint32_t>& exploredBoards,
                 Vector<Move>& moveHistory){
    /* TODO: COMPLETE THIS */
    if (exploredBoards.size()%10000 == 0){
               cout << "Boards evaluated: " << exploredBoards.size()
                    << "\tDepth: " << moveHistory.size() << endl;
               cout.flush();
    }
    if(marblesLeft == 1)
        return true;
    if(exploredBoards.contains(compressMarbleBoard(board)))
        return false;
    exploredBoards.add(compressMarbleBoard(board));
    Vector<Move> moves = findPossibleMoves(board);
    for(int i=0; i<moves.size(); ++i){
         Move move = moves[i];
         makeMove(move, board);
         moveHistory.add(move);
         if(solvePuzzle(board, marblesLeft-1,exploredBoards, moveHistory))
         {
             return true;
         }
         else{
             undoMove(move, board);
             moveHistory.remove(moveHistory.size()-1);
         }
    }
    return false;
}
int AToCPointLocator::findEnclosingCell(int initialGuessLID,
                                        const double* x,
                                        double* xLocal) const
{
  std::queue<int> Q;
  Set<int> repeats;
  int d = mesh_.spatialDim();
  Array<int> facets(mesh_.numFacets(d, 0, 0));
  Array<int> facetOr(facets.size());

  Q.push(initialGuessLID);

  while (!Q.empty())
    {
      int next = Q.front();
      Q.pop();
      if (repeats.contains(next)) continue;
      
//      const int* facets = mesh_.elemZeroFacetView(next);
      mesh_.getFacetArray(d, next, 0, facets, facetOr);
      if (cellContainsPoint(next, x, &(facets[0]), xLocal)) return next;
      repeats.put(next);
      
      fillMaximalNeighbors(next, &(facets[0]));
      
      for (Set<int>::const_iterator 
             i=neighborSet_[next]->begin(); i!=neighborSet_[next]->end(); i++)
        {
          Q.push(*i);
        }
    }
  return -1; // no containing cell found
}
Example #15
0
static void tryPlayerGuess(const Grid<char> & boggleBoard, Set<string> & playerAnswers,
                           string playerGuess, const Lexicon & english) {
    if (playerGuess.size() < kMinGuessLength){
        cout << endl << "Words need to be at least " +
             integerToString(kMinGuessLength) + " characters long" << endl;
        return;
    }
    if (!english.contains(playerGuess)){
        cout << endl << "That word is not in the english language" << endl;
        return;
    }
    playerGuess = toUpperCase(playerGuess);
    if (playerAnswers.contains(playerGuess)){
        cout << endl << "You have already guessed that word" << endl;
        return;
    }
    for(int i = 0; i < boggleBoard.numRows(); i++){
        for(int j = 0; j < boggleBoard.numCols(); j++){
            Set <coord> wordPath;
            coord pos;
            pos.row = i;
            pos.col = j;
            wordPath.add(pos);
            if(tryPlayerGuess(boggleBoard, playerAnswers,
                           playerGuess, english, "", i, j, wordPath)){
                pause(highlightPause);
                clearBoard(wordPath);
                recordWordForPlayer(playerGuess, HUMAN);
                return;
            }
        }
    }
    cout << endl << "That word is not on the board." << endl;
}
Example #16
0
  int findEnclosingCell(const Mesh& mesh, int cellDim,
                        int initialGuessLID,
                        const double* x)
  {
    std::queue<int> Q;
    Set<int> repeats;
    static Array<int> facets;

    Q.push(initialGuessLID);

    

    while (!Q.empty())
      {
        int next = Q.front();
        Q.pop();
        if (repeats.contains(next)) continue;

        if (cellContainsPoint(mesh, cellDim, next, x, facets)) return next;
        repeats.put(next);
        
        std::list<int> neighbors;
        maximalNeighbors(mesh, cellDim, next, facets, neighbors);
        for (std::list<int>::const_iterator 
               i=neighbors.begin(); i!=neighbors.end(); i++)
          {
            Q.push(*i);
          }
      }
    return -1; // no containing cell found
  }
Example #17
0
bool recSolvable(int start, Vector<int> & squares, Set<int> &indexVisited) {
	if (start < 0 || start >= squares.size() || indexVisited.contains(start)) return false;
	if (start == (squares.size() - 1)) return true;
	indexVisited.add(start);
	return (recSolvable(start + squares[start], squares, indexVisited)
		||recSolvable(start - squares[start], squares, indexVisited));
}
Example #18
0
bool Store::retrieveValue(const BinaryString &key, Set<BinaryString> &values)
{
	// Note: values is not cleared !

	const Identifier localNode = Network::Instance->overlay()->localNode();

	Database::Statement statement = mDatabase->prepare("SELECT value FROM map WHERE key = ?1");
	statement.bind(1, key);
	while(statement.step())
	{
		BinaryString v;
		statement.value(0, v);
		values.insert(v);
	}
	statement.finalize();

	if(!values.contains(localNode))
	{
		// Also look for digest in blocks in case map is not up-to-date
		statement = mDatabase->prepare("SELECT 1 FROM blocks WHERE digest = ?1 LIMIT 1");
		statement.bind(1, key);
		if(statement.step())
			values.insert(localNode);
		statement.finalize();
	}

	return !values.empty();
}
void ArticulatedModel::Part::transformGeometry(shared_ptr<ArticulatedModel> am, const Matrix4& xform) {
    // TODO: this is a linear search through the mesh array for every part, could be sped up
    // TODO: this transforms any geometry that is touch by a mesh in this part. This will have
    // unintended side effects when multiple parts have meshes that share geometry
    Set<ArticulatedModel::Geometry*> touchedGeometry;
    for (int i = 0; i < am->m_meshArray.size(); ++i) {
        Mesh* mesh = am->m_meshArray[i];
        alwaysAssertM(notNull(mesh->geometry), "Found a NULL mesh in transformGeometry");
        if ( mesh->logicalPart == this && ! touchedGeometry.contains(mesh->geometry)) {
            touchedGeometry.insert(mesh->geometry);
            CPUVertexArray::Vertex* vertex = mesh->geometry->cpuVertexArray.vertex.getCArray();
            const int N = mesh->geometry->cpuVertexArray.size();
            for (int i = 0; i < N; ++i) {
                vertex->position = xform.homoMul(vertex->position, 1.0f);
                vertex->tangent  = Vector4::nan();
                vertex->normal   = Vector3::nan();
                ++vertex;
            }
        }
  
    }
    for (int c = 0; c < m_children.size(); ++c) {
        m_children[c]->cframe.translation = 
            xform.homoMul(m_children[c]->cframe.translation, 1.0f);
    }
}
int AToCPointLocator::findEnclosingCell(int initialGuessLID,
                                        const double* x,
                                        double* xLocal) const
{
  std::queue<int> Q;
  Set<int> repeats;

  Q.push(initialGuessLID);

  while (!Q.empty())
    {
      int next = Q.front();
      Q.pop();
      if (repeats.contains(next)) continue;
      
      const int* facets = mesh_.elemZeroFacetView(next);
      if (cellContainsPoint(next, x, facets, xLocal)) return next;
      repeats.put(next);
      
      fillMaximalNeighbors(next, facets);
      
      for (Set<int>::const_iterator 
             i=neighborSet_[next]->begin(); i!=neighborSet_[next]->end(); i++)
        {
          Q.push(*i);
        }
    }
  return -1; // no containing cell found
}
Example #21
0
void subtract(const Set& s1, const Set& s2, Set& result)
{
    Set A = s1;
    Set B = s2;
    Set C;
    result = C; //clear the contents of result by setting it equal to empty Set C
    
    for (int a = 0; a < B.size(); a++)
    {
        ItemType value;
        B.get(a, value);
        if (A.contains(value))
        {
            A.erase(value);     //if A contains a value that is also in B, delete it from A
        }
        
    }
    
    for (int d = 0; d < A.size(); d++)
    {
        ItemType value;
        A.get(d, value);
        result.insert(value);   //insert these into result, which now only contains values from A and not B
    }
}
Example #22
0
void WatcherData::watch(const Path& path)
{
    std::lock_guard<std::mutex> lock(mutex);

    assert(!paths.contains(path));

    paths.insert(path);
    CFRunLoopSourceSignal(source);
    CFRunLoopWakeUp(loop);
}
Example #23
0
void test()
{
    Set uls;
    assert(uls.insert(10));
    assert(uls.insert(20));
    assert(uls.size() == 2);
    assert(uls.contains(20));
    ItemType x = 30;
    assert(uls.get(0, x)  &&  (x == 10  ||  x == 20));
}
Example #24
0
bool Set<ElemType>::isSubsetOf(Set & otherSet) {
	if (cmpFn != otherSet.cmpFn) {
		Error("isSubsetOf: sets have different comparison functions");
	}
	Iterator iter = iterator();
	while (iter.hasNext()) {
		if (!otherSet.contains(iter.next())) return false;
	}
	return true;
}
Example #25
0
Set<std::string> WebPage::allWords () const {
	std::stringstream ss;
	ss.str(data);
	Set<std::string>* words = new Set<std::string>();
	while(!ss.fail()) {
		std::string word = "";
		ss >> word;
		bool insideWord = false;
		bool skipForBracket = false;
		Set<std::string> innerWords = Set<std::string>();
		int startIndex = 0;
		int endIndex = 0;
		for(unsigned int j = 0; j < word.length(); j++) {
			if(word[j] == '[') {
				skipForBracket = true;
			}
			if(word[j] == ']') {
				skipForBracket = false;
			}

			//Check to see if the char at line[j] is within the ASCII bounds of upper/lower case alphabet letters
			if(isalnum(word[j]) && !skipForBracket) {
				if(insideWord == false) {
					startIndex = j;
				}
				insideWord = true;		//If yes, then it is inside a word
			} else {
				if(insideWord == true) {  //else the word has ended
					insideWord = false;
					endIndex = j;
					int length = endIndex - startIndex;
					innerWords.insert(innerWords.end(),word.substr(startIndex,length));
				}
			}
		}
		if(insideWord) {
			endIndex = word.length();
		}
		int length = endIndex - startIndex;
		if(length > 0) {
			innerWords.insert(innerWords.end(),word.substr(startIndex,length));
		}
		set<std::string>::iterator innerWordsIter = innerWords.begin();
		for(unsigned int i = 0; i < innerWords.size(); i++) {
			if(innerWordsIter != innerWords.end()) {
				std::string addition = *innerWordsIter;
				innerWordsIter++;
				if (!words->contains(addition)) {
					words->insert(words->end(),addition);
				}
			}
		}
	}	
	return *words;
}
Example #26
0
void dirtySymbols(SymbolMap &map, const Set<uint32_t> &dirty)
{
    SymbolMap::iterator it = map.begin();
    while (it != map.end()) {
        if (dirty.contains(it->first.fileId())) {
            map.erase(it++);
        } else {
            it->second->dirty(dirty);
            ++it;
        }
    }
}
/* Determines any covered cities in hospital location and removes them from the cities set.
 * Returns the removed/covered cities.
 */
Set<string> getCoveredCities(Set<string>& cities, Set<string> location) {
    Set<string> coveredCities;
    
    foreach(string city in cities) {
        if (location.contains(city)) {
            coveredCities.add(city);
            cities.remove(city);
        }
    }
    
    return coveredCities;
}
TIMED_TEST(MapTests, forEachTest_Map, TEST_TIMEOUT_DEFAULT) {
    Map<std::string, int> map;
    map.put("zz", 26);
    map.put("a", 1);
    map.put("ss", 97);
    map.put("bbbb", 2);
    map.put("E", 4);
    map.put("yZ44", 33);
    Set<std::string> expected {"zz", "a", "ss", "bbbb", "E", "yZ44"};
    for (const std::string& key : map) {
        assertTrue("foreach Map contains " + key, expected.contains(key));
    }
    map.remove("ss");
    map.remove("zz");
    map.remove("yZ44");
    map.remove("notfound");
    expected = {"a", "bbbb", "E"};
    for (const std::string& key : map) {
        assertTrue("foreach Map contains " + key, expected.contains(key));
    }
}
Example #29
0
void TestTools::set_initializerList()
{
    Set<int> set = {1, 1, 2, 3, 4, 5};
    QCOMPARE(set.count(), 5);
    QVERIFY(set.contains(1));
    QVERIFY(set.contains(2));
    QVERIFY(set.contains(3));
    QVERIFY(set.contains(4));
    QVERIFY(set.contains(5));

    // check _which_ of the equal elements gets inserted (in the QHash/QMap case, it's the last):
    const Set<IdentityTracker> set2 = {{1, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
    QCOMPARE(set2.count(), 5);
    const int dummy = -1;
    const IdentityTracker searchKey = {1, dummy};
    QCOMPARE(set2.find(searchKey)->id, 0);

    Set<int> emptySet{};
    QVERIFY(emptySet.isEmpty());

    Set<int> set3{{}, {}, {}};
    QVERIFY(!set3.isEmpty());
}
bool WatcherThread::isWatching(const Path& p) const
{
    Path path = p, parent;
    if (!path.endsWith('/'))
        path += '/';
    for (;;) {
        if (paths.contains(path))
            return true;
        parent = path.parentDir();
        if (parent == path || parent.isEmpty())
            break;
        path = parent;
    }
    return false;
}