/* This api takes the user input - and looks up the word[s] in the inverted index. The candidate documents are then ranked based on tf-idf BOW (bag of words) model */ std::vector<std::pair<int,double> > ServeIndex(const std::string& word,int topK) { //tokenize and normalize the user text std::vector<std::string>& word_tokens = _wordBreaker->BreakEnglishText(word.c_str()); std::vector<std::pair<int,double> > results; //generate the candidate document set std::set<int> candSet; bool foundAny = false; for(size_t i=0;i<word_tokens.size();++i) { boost::unordered_map<std::string,IndexEntry>::iterator itor = _indexPtr->_wordIndex.find(word_tokens[i]); if( itor == _indexPtr->_wordIndex.end() ) continue; else{ //first entry which was found if(!foundAny){ candSet = itor->second._docSet; foundAny = true; } else{ std::set<int> temp; set_intersection(candSet.begin(),candSet.end(),(itor->second)._docSet.begin(),(itor->second)._docSet.end(),inserter(temp,temp.begin())); candSet.clear(); candSet = temp; } } } return Rank(word_tokens,candSet,topK); }
/** Create output workspace * @brief ConvertCWSDExpToMomentum::createExperimentMDWorkspace * @return */ API::IMDEventWorkspace_sptr ConvertCWSDMDtoHKL::createHKLMDWorkspace( const std::vector<Kernel::V3D> &vec_hkl, const std::vector<signal_t> &vec_signal, const std::vector<detid_t> &vec_detid) { // Check if (vec_hkl.size() != vec_signal.size() || vec_signal.size() != vec_detid.size()) throw std::invalid_argument("Input vectors for HKL, signal and detector " "IDs are of different size!"); // Create workspace in Q_sample with dimenion as 3 size_t nDimension = 3; IMDEventWorkspace_sptr mdws = MDEventFactory::CreateMDWorkspace(nDimension, "MDEvent"); // Extract Dimensions and add to the output workspace. std::vector<std::string> vec_ID(3); vec_ID[0] = "H"; vec_ID[1] = "K"; vec_ID[2] = "L"; std::vector<std::string> dimensionNames(3); dimensionNames[0] = "H"; dimensionNames[1] = "K"; dimensionNames[2] = "L"; Mantid::Kernel::SpecialCoordinateSystem coordinateSystem = Mantid::Kernel::HKL; // Add dimensions std::vector<double> m_extentMins(3); std::vector<double> m_extentMaxs(3); std::vector<size_t> m_numBins(3, 100); getRange(vec_hkl, m_extentMins, m_extentMaxs); // Get MDFrame of HKL type with RLU auto unitFactory = makeMDUnitFactoryChain(); auto unit = unitFactory->create(Units::Symbol::RLU.ascii()); Mantid::Geometry::HKL frame(unit); for (size_t i = 0; i < nDimension; ++i) { std::string id = vec_ID[i]; std::string name = dimensionNames[i]; // std::string units = "A^-1"; mdws->addDimension( Geometry::MDHistoDimension_sptr(new Geometry::MDHistoDimension( id, name, frame, static_cast<coord_t>(m_extentMins[i]), static_cast<coord_t>(m_extentMaxs[i]), m_numBins[i]))); } // Set coordinate system mdws->setCoordinateSystem(coordinateSystem); // Creates a new instance of the MDEventInserter to output workspace MDEventWorkspace<MDEvent<3>, 3>::sptr mdws_mdevt_3 = boost::dynamic_pointer_cast<MDEventWorkspace<MDEvent<3>, 3>>(mdws); MDEventInserter<MDEventWorkspace<MDEvent<3>, 3>::sptr> inserter(mdws_mdevt_3); // Go though each spectrum to conver to MDEvent for (size_t iq = 0; iq < vec_hkl.size(); ++iq) { Kernel::V3D hkl = vec_hkl[iq]; std::vector<Mantid::coord_t> millerindex(3); millerindex[0] = static_cast<float>(hkl.X()); millerindex[1] = static_cast<float>(hkl.Y()); millerindex[2] = static_cast<float>(hkl.Z()); signal_t signal = vec_signal[iq]; signal_t error = std::sqrt(signal); uint16_t runnumber = 1; detid_t detid = vec_detid[iq]; // Insert inserter.insertMDEvent( static_cast<float>(signal), static_cast<float>(error * error), static_cast<uint16_t>(runnumber), detid, millerindex.data()); } return mdws; }
var tau::operator()(const var&v){ var out; out.real=mapping(v.real); for_each_copy(v.dual->begin(),v.dual->end(),inserter(*(out.dual),out.dual->begin()),mul_make_pair<std::pair<int,double> >, primitive(v.real)); return out; }
bool ArMapFileLineSet::calculateChanges(ArMapFileLineSet &origLines, ArMapFileLineSet &newLines, ArMapFileLineSet *deletedLinesOut, ArMapFileLineSet *addedLinesOut, bool isCheckChildren) { if ((deletedLinesOut == NULL) || (addedLinesOut == NULL)) { return false; } ArMapFileLineGroupCompare compare; ArMapFileLineGroupLineNumCompare compareLineNums; std::sort(origLines.begin(), origLines.end(), compare); std::sort(newLines.begin(), newLines.end(), compare); set_difference(origLines.begin(), origLines.end(), newLines.begin(), newLines.end(), inserter(*deletedLinesOut, deletedLinesOut->begin()), compare); set_difference(newLines.begin(), newLines.end(), origLines.begin(), origLines.end(), inserter(*addedLinesOut, addedLinesOut->begin()), compare); if (isCheckChildren) { ArMapFileLineSet unchangedOrigLines; ArMapFileLineSet unchangedNewLines; set_difference(origLines.begin(), origLines.end(), deletedLinesOut->begin(), deletedLinesOut->end(), inserter(unchangedOrigLines, unchangedOrigLines.begin()), compare); set_difference(newLines.begin(), newLines.end(), addedLinesOut->begin(), addedLinesOut->end(), inserter(unchangedNewLines, unchangedNewLines.begin()), compare); ArMapFileLineCompare compareLine; for (ArMapFileLineSet::iterator iterO = unchangedOrigLines.begin(), iterN = unchangedNewLines.begin(); ( (iterO != unchangedOrigLines.end()) && (iterN != unchangedNewLines.end()) ); iterO++, iterN++) { ArMapFileLineGroup &origGroup = *iterO; ArMapFileLineGroup &newGroup = *iterN; std::sort(origGroup.getChildLines()->begin(), origGroup.getChildLines()->end(), compareLine); std::sort(newGroup.getChildLines()->begin(), newGroup.getChildLines()->end(), compareLine); ArMapFileLineSet tempDeletedLines; ArMapFileLineSet tempAddedLines; set_difference(origGroup.getChildLines()->begin(), origGroup.getChildLines()->end(), newGroup.getChildLines()->begin(), newGroup.getChildLines()->end(), inserter(tempDeletedLines, tempDeletedLines.begin()), compareLine); set_difference(newGroup.getChildLines()->begin(), newGroup.getChildLines()->end(), origGroup.getChildLines()->begin(), origGroup.getChildLines()->end(), inserter(tempAddedLines, tempAddedLines.begin()), compareLine); // TODO: Right now just sending the entire group -- but someday // we may just want to send the lines that have changed within // the group (plus the group heading). if (!tempDeletedLines.empty() || !tempAddedLines.empty()) { deletedLinesOut->push_back(origGroup); addedLinesOut->push_back(newGroup); } // end if child changes } // end for each unchanged line } // end if check children std::sort(deletedLinesOut->begin(), deletedLinesOut->end(), compareLineNums); std::sort(addedLinesOut->begin(), addedLinesOut->end(), compareLineNums); return true; } // end method calculateChanges
void pcl::ExtractIndices<pcl::PCLPointCloud2>::applyFilter (std::vector<int> &indices) { if (negative_) { // If the subset is the full set if (indices_->size () == (input_->width * input_->height)) { // Empty set copy indices.clear (); return; } // Set up the full indices set std::vector<int> indices_fullset (input_->width * input_->height); for (int p_it = 0; p_it < static_cast<int> (indices_fullset.size ()); ++p_it) indices_fullset[p_it] = p_it; // If the subset is the empty set if (indices_->empty () || (input_->width * input_->height == 0)) { // Full set copy indices = indices_fullset; return; } // If the subset is a proper subset // Set up the subset input indices std::vector<int> indices_subset = *indices_; std::sort (indices_subset.begin (), indices_subset.end ()); // Get the difference set_difference (indices_fullset.begin (), indices_fullset.end (), indices_subset.begin (), indices_subset.end (), inserter (indices, indices.begin ())); } else indices = *indices_; }
PluginMetadata PluginMetadata::DiffMetadata(const PluginMetadata& plugin) const { BOOST_LOG_TRIVIAL(trace) << "Calculating metadata difference for: " << name; PluginMetadata p(*this); if (priority == plugin.Priority()) { p.Priority(0); p.SetPriorityExplicit(false); } //Compare this plugin against the given plugin. set<File> files = plugin.LoadAfter(); set<File> filesDiff; set_symmetric_difference(loadAfter.begin(), loadAfter.end(), files.begin(), files.end(), inserter(filesDiff, filesDiff.begin())); p.LoadAfter(filesDiff); filesDiff.clear(); files = plugin.Reqs(); set_symmetric_difference(requirements.begin(), requirements.end(), files.begin(), files.end(), inserter(filesDiff, filesDiff.begin())); p.Reqs(filesDiff); filesDiff.clear(); files = plugin.Incs(); set_symmetric_difference(incompatibilities.begin(), incompatibilities.end(), files.begin(), files.end(), inserter(filesDiff, filesDiff.begin())); p.Incs(filesDiff); list<Message> msgs1 = plugin.Messages(); list<Message> msgs2 = messages; msgs1.sort(); msgs2.sort(); list<Message> mDiff; set_symmetric_difference(msgs2.begin(), msgs2.end(), msgs1.begin(), msgs1.end(), inserter(mDiff, mDiff.begin())); p.Messages(mDiff); set<Tag> bashTags = plugin.Tags(); set<Tag> tagDiff; set_symmetric_difference(tags.begin(), tags.end(), bashTags.begin(), bashTags.end(), inserter(tagDiff, tagDiff.begin())); p.Tags(tagDiff); set<PluginDirtyInfo> dirtyInfo = plugin.DirtyInfo(); set<PluginDirtyInfo> dirtDiff; set_symmetric_difference(_dirtyInfo.begin(), _dirtyInfo.end(), dirtyInfo.begin(), dirtyInfo.end(), inserter(dirtDiff, dirtDiff.begin())); p.DirtyInfo(dirtDiff); set<Location> locations = plugin.Locations(); set<Location> locationsDiff; set_symmetric_difference(_locations.begin(), _locations.end(), locations.begin(), locations.end(), inserter(locationsDiff, locationsDiff.begin())); p.Locations(locationsDiff); return p; }
/* * Expand a token sequence * If skip_defined is true then the defined() keyword is not processed * The caller is used for registering invocations from one macro to another * This is an implementation of Dave Prosser's algorithm, listed in * X3J11/86-196 */ PtokenSequence macro_expand(PtokenSequence ts, bool get_more, bool skip_defined, const Macro *caller) { PtokenSequence r; // Return value if (DP()) cout << "Expanding: " << ts << endl; while (!ts.empty()) { const Ptoken head(ts.front()); ts.pop_front(); if (head.get_code() != IDENTIFIER) { // Only attempt to expand identifiers (not e.g. string literals) r.push_back(head); continue; } if (skip_defined && head.get_code() == IDENTIFIER && head.get_val() == "defined") { // Skip the arguments of the defined operator, if needed PtokenSequence da(gather_defined_operator(ts)); r.push_back(head); r.splice(r.end(), da); continue; } const string name = head.get_val(); mapMacro::const_iterator mi(Pdtoken::macros_find(name)); if (!Pdtoken::macro_is_defined(mi)) { // Nothing to do if the identifier is not a macro r.push_back(head); continue; } const Macro& m = mi->second; if (head.hideset_contains(m.get_name_token())) { // Skip the head token if it is in the hideset if (DP()) cout << "Skipping (head is in HS)" << endl; r.push_back(head); continue; } if (DP()) cout << "replacing for " << name << " tokens " << ts << endl; PtokenSequence removed_spaces; if (!m.is_function) { // Object-like macro Token::unify((*mi).second.name_token, head); HideSet hs(head.get_hideset()); hs.insert(m.get_name_token()); PtokenSequence s(subst(m, m.value, mapArgval(), hs, skip_defined, caller)); ts.splice(ts.begin(), s); caller = &m; } else if (fill_in(ts, get_more, removed_spaces) && ts.front().get_code() == '(') { // Application of a function-like macro Token::unify((*mi).second.name_token, head); mapArgval args; // Map from formal name to value if (DP()) cout << "Expanding " << m << " inside " << caller << "\n"; if (caller && caller->is_function) // Macro to macro call Call::register_call(caller->get_mcall(), m.get_mcall()); else // Function to macro call Call::register_call(m.get_mcall()); ts.pop_front(); Ptoken close; if (!gather_args(name, ts, m.formal_args, args, get_more, m.is_vararg, close)) continue; // Attempt to bail-out on error HideSet hs; set_intersection(head.get_hideset().begin(), head.get_hideset().end(), close.get_hideset().begin(), close.get_hideset().end(), inserter(hs, hs.begin())); hs.insert(m.get_name_token()); PtokenSequence s(subst(m, m.value, args, hs, skip_defined, caller)); ts.splice(ts.begin(), s); caller = &m; } else { // Function-like macro name lacking a ( if (DP()) cout << "splicing: [" << removed_spaces << ']' << endl; ts.splice(ts.begin(), removed_spaces); r.push_back(head); } } return (r); }
void MDLSurface_read( Surface& surface, const byte* buffer, const char* name ){ mdlHeader_t header; PointerInputStream inputStream( buffer ); istream_read_mdlHeader( inputStream, header ); for ( int i = 0; i < header.numskins; ++i ) { switch ( istream_read_int32_le( inputStream ) ) { case MDL_SKIN_SINGLE: inputStream.seek( header.skinwidth * header.skinheight ); break; case MDL_SKIN_GROUP: int numskins = istream_read_int32_le( inputStream ); inputStream.seek( numskins * ( 4 + ( header.skinwidth * header.skinheight ) ) ); break; } } Array<mdlSt_t> mdlSts( header.numverts ); for ( Array<mdlSt_t>::iterator i = mdlSts.begin(); i != mdlSts.end(); ++i ) { ( *i ).onseam = istream_read_int32_le( inputStream ); ( *i ).s = istream_read_int32_le( inputStream ); ( *i ).t = istream_read_int32_le( inputStream ); } Array<mdlTriangle_t> mdlTriangles( header.numtris ); for ( Array<mdlTriangle_t>::iterator i = mdlTriangles.begin(); i != mdlTriangles.end(); ++i ) { ( *i ).facesfront = istream_read_int32_le( inputStream ); ( *i ).vertindex[0] = istream_read_int32_le( inputStream ); ( *i ).vertindex[1] = istream_read_int32_le( inputStream ); ( *i ).vertindex[2] = istream_read_int32_le( inputStream ); } { bool found = false; for ( int i = 0; i < header.numframes && found == false; i++ ) { switch ( istream_read_int32_le( inputStream ) ) { case MDL_FRAME_SINGLE: inputStream.seek( MDL_FRAME_SIZE ); found = true; break; case MDL_FRAME_GROUP: int numframes = istream_read_int32_le( inputStream ); //inputStream.seek( ( MDL_XYZNORMAL_SIZE * 2 ) + ( numframes * 4 ) ); inputStream.seek( ( MDL_XYZNORMAL_SIZE * 4 ) + ( numframes * 4 ) + 16 );//group min_vec3 + max_vec3 + timings_float[numframes] + frame min_vec3 + max_vec3 + name_char[16] found = true; break; } } } Array<mdlXyzNormal_t> mdlXyzNormals( header.numverts ); for ( Array<mdlXyzNormal_t>::iterator i = mdlXyzNormals.begin(); i != mdlXyzNormals.end(); ++i ) { inputStream.read( ( *i ).v, 3 ); inputStream.read( &( *i ).lightnormalindex, 1 ); } { VertexBuffer<mdlVertex_t> mdl_vertices; { UniqueVertexBuffer<mdlVertex_t> inserter( mdl_vertices ); for ( Array<mdlTriangle_t>::iterator i = mdlTriangles.begin(); i != mdlTriangles.end(); ++i ) { surface.indices().insert( inserter.insert( mdlVertex_t( ( *i ).vertindex[0], ( *i ).facesfront ) ) ); surface.indices().insert( inserter.insert( mdlVertex_t( ( *i ).vertindex[1], ( *i ).facesfront ) ) ); surface.indices().insert( inserter.insert( mdlVertex_t( ( *i ).vertindex[2], ( *i ).facesfront ) ) ); } } { surface.vertices().reserve( mdl_vertices.size() ); for ( VertexBuffer<mdlVertex_t>::iterator i = mdl_vertices.begin(); i != mdl_vertices.end(); ++i ) { surface.vertices().push_back( MDLVertex_construct( header, mdlXyzNormals[( *i ).m_vertindex], mdlSts[( *i ).m_vertindex], ( *i ).m_facesfront == MDL_FACES_FRONT ) ); } } } surface.setShader( name ); surface.updateAABB(); }
void ReindexGeometry(FCDGeometryPolygons* polys, FCDSkinController* skin) { // Given geometry with: // positions, normals, texcoords, bone blends // each with their own data array and index array, change it to // have a single optimised index array shared by all vertexes. FCDGeometryPolygonsInput* inputPosition = polys->FindInput(FUDaeGeometryInput::POSITION); FCDGeometryPolygonsInput* inputNormal = polys->FindInput(FUDaeGeometryInput::NORMAL); FCDGeometryPolygonsInput* inputTexcoord = polys->FindInput(FUDaeGeometryInput::TEXCOORD); size_t numVertices = polys->GetFaceVertexCount(); assert(inputPosition->GetIndexCount() == numVertices); assert(inputNormal ->GetIndexCount() == numVertices); assert(inputTexcoord->GetIndexCount() == numVertices); const uint32* indicesPosition = inputPosition->GetIndices(); const uint32* indicesNormal = inputNormal->GetIndices(); const uint32* indicesTexcoord = inputTexcoord->GetIndices(); assert(indicesPosition); assert(indicesNormal); assert(indicesTexcoord); // TODO - should be optional, because textureless meshes aren't unreasonable FCDGeometrySourceList texcoordSources; polys->GetParent()->FindSourcesByType(FUDaeGeometryInput::TEXCOORD, texcoordSources); FCDGeometrySource* sourcePosition = inputPosition->GetSource(); FCDGeometrySource* sourceNormal = inputNormal ->GetSource(); const float* dataPosition = sourcePosition->GetData(); const float* dataNormal = sourceNormal ->GetData(); if (skin) { #ifndef NDEBUG size_t numVertexPositions = sourcePosition->GetDataCount() / sourcePosition->GetStride(); assert(skin->GetInfluenceCount() == numVertexPositions); #endif } uint32 stridePosition = sourcePosition->GetStride(); uint32 strideNormal = sourceNormal ->GetStride(); std::vector<uint32> indicesCombined; std::vector<VertexData> vertexes; InserterWithoutDuplicates<VertexData> inserter(vertexes); for (size_t i = 0; i < numVertices; ++i) { std::vector<FCDJointWeightPair> weights; if (skin) { FCDSkinControllerVertex* influences = skin->GetVertexInfluence(indicesPosition[i]); assert(influences != NULL); for (size_t j = 0; j < influences->GetPairCount(); ++j) { FCDJointWeightPair* pair = influences->GetPair(j); assert(pair != NULL); weights.push_back(*pair); } CanonicaliseWeights(weights); } std::vector<uv_pair_type> uvs; for (size_t set = 0; set < texcoordSources.size(); ++set) { const float* dataTexcoord = texcoordSources[set]->GetData(); uint32 strideTexcoord = texcoordSources[set]->GetStride(); uv_pair_type p; p.first = dataTexcoord[indicesTexcoord[i]*strideTexcoord]; p.second = dataTexcoord[indicesTexcoord[i]*strideTexcoord + 1]; uvs.push_back(p); } VertexData vtx ( &dataPosition[indicesPosition[i]*stridePosition], &dataNormal [indicesNormal [i]*strideNormal], uvs, weights ); size_t idx = inserter.add(vtx); indicesCombined.push_back((uint32)idx); } // TODO: rearrange indicesCombined (and rearrange vertexes to match) to use // the vertex cache efficiently // (<http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html> etc) FloatList newDataPosition; FloatList newDataNormal; FloatList newDataTexcoord; std::vector<std::vector<FCDJointWeightPair> > newWeightedMatches; for (size_t i = 0; i < vertexes.size(); ++i) { newDataPosition.push_back(vertexes[i].x); newDataPosition.push_back(vertexes[i].y); newDataPosition.push_back(vertexes[i].z); newDataNormal .push_back(vertexes[i].nx); newDataNormal .push_back(vertexes[i].ny); newDataNormal .push_back(vertexes[i].nz); newWeightedMatches.push_back(vertexes[i].weights); } // (Slightly wasteful to duplicate this array so many times, but FCollada // doesn't seem to support multiple inputs with the same source data) inputPosition->SetIndices(&indicesCombined.front(), indicesCombined.size()); inputNormal ->SetIndices(&indicesCombined.front(), indicesCombined.size()); inputTexcoord->SetIndices(&indicesCombined.front(), indicesCombined.size()); for (size_t set = 0; set < texcoordSources.size(); ++set) { newDataTexcoord.clear(); for (size_t i = 0; i < vertexes.size(); ++i) { newDataTexcoord.push_back(vertexes[i].uvs[set].first); newDataTexcoord.push_back(vertexes[i].uvs[set].second); } texcoordSources[set]->SetData(newDataTexcoord, 2); } sourcePosition->SetData(newDataPosition, 3); sourceNormal ->SetData(newDataNormal, 3); if (skin) { skin->SetInfluenceCount(newWeightedMatches.size()); for (size_t i = 0; i < newWeightedMatches.size(); ++i) { skin->GetVertexInfluence(i)->SetPairCount(0); for (size_t j = 0; j < newWeightedMatches[i].size(); ++j) skin->GetVertexInfluence(i)->AddPair(newWeightedMatches[i][j].jointIndex, newWeightedMatches[i][j].weight); } } }
am_Error_e CAmRouter::findBestWay(am_sinkID_t sinkID, am_sourceID_t sourceID, std::vector<am_RoutingElement_s> & listRoute, std::vector<am_RoutingElement_s>::iterator routeIterator, std::vector<am_gatewayID_t>::iterator gatewayIterator) { am_Error_e returnError = E_NOT_POSSIBLE; std::vector<am_ConnectionFormat_e> listConnectionFormats; std::vector<am_ConnectionFormat_e> listMergeConnectionFormats; std::vector<am_ConnectionFormat_e> listPriorityConnectionFormats; std::vector<am_RoutingElement_s>::iterator nextIterator = routeIterator + 1; //get best connection format listPossibleConnectionFormats(routeIterator->sourceID, routeIterator->sinkID, listConnectionFormats); //if we have not just started, we need to take care about the gateways... if (routeIterator != listRoute.begin()) { //since we have to deal with Gateways, there are restrictions what connectionFormat we can take. So we need to take the subset of connections that are restricted: std::vector<am_ConnectionFormat_e> listRestrictedConnectionFormats; std::insert_iterator<std::vector<am_ConnectionFormat_e> > inserter(listMergeConnectionFormats, listMergeConnectionFormats.begin()); std::vector<am_RoutingElement_s>::iterator tempIterator(routeIterator); tempIterator--; listRestrictedOutputFormatsGateways(*gatewayIterator, (tempIterator)->connectionFormat, listRestrictedConnectionFormats); std::sort(listRestrictedConnectionFormats.begin(), listRestrictedConnectionFormats.end()); //todo: this might be not needed if we use strictly sorted input set_intersection(listConnectionFormats.begin(), listConnectionFormats.end(), listRestrictedConnectionFormats.begin(), listRestrictedConnectionFormats.end(), inserter); gatewayIterator++; } else { listMergeConnectionFormats = listConnectionFormats; } am_Route_s route; route.sinkID = sinkID; route.sourceID = sourceID; route.route = listRoute; //let the controller decide: mpControlSender->getConnectionFormatChoice(routeIterator->sourceID, routeIterator->sinkID, route, listMergeConnectionFormats, listPriorityConnectionFormats); //we have the list sorted after prios - now we try one after the other with the next part of the route std::vector<am_ConnectionFormat_e>::iterator connectionFormatIterator = listPriorityConnectionFormats.begin(); //here we need to check if we are at the end and stop if (nextIterator == listRoute.end()) { if (!listPriorityConnectionFormats.empty()) { routeIterator->connectionFormat = listPriorityConnectionFormats.front(); return (E_OK); } else return (E_NOT_POSSIBLE); } for (; connectionFormatIterator != listPriorityConnectionFormats.end(); ++connectionFormatIterator) { routeIterator->connectionFormat = *connectionFormatIterator; if ((returnError = findBestWay(sinkID, sourceID, listRoute, nextIterator, gatewayIterator)) == E_OK) { break; } } return (returnError); }
void Rule::cal_positive_body_m(set<int>& s, set<int>& r) { set_difference(this->body_lits.begin(), this->body_lits.end(), s.begin(), s.end(), inserter(r, r.begin())); }
// ***************************************************************** // GenerateCategories() // ***************************************************************** vector<CategoriesData>* FieldClassification::GenerateCategories(CString fieldName, FieldType fieldType, vector<VARIANT*>& srcValues, tkClassificationType ClassificationType, long numClasses, long& errorCode) { CComVariant minValue, maxValue; minValue.vt = VT_EMPTY; maxValue.vt = VT_EMPTY; long numShapes = srcValues.size(); /* we won't define intervals for string values */ if (ClassificationType != ctUniqueValues && fieldType == STRING_FIELD) { errorCode = tkNOT_UNIQUE_CLASSIFICATION_FOR_STRINGS; return NULL; } if ((numClasses <= 0 || numClasses > 1000) && (ClassificationType != ctUniqueValues)) { errorCode = tkTOO_MANY_CATEGORIES; return NULL; } if (ClassificationType == ctStandardDeviation) { errorCode = tkINVALID_PARAMETER_VALUE; return NULL; } // natural breaks aren't designed to work otherwise if (numShapes < numClasses && ClassificationType == ctNaturalBreaks) { numClasses = numShapes; } // values in specified range should be classified bool useRange = minValue.vt != VT_EMPTY && maxValue.vt != VT_EMPTY && fieldType == DOUBLE_FIELD; if (useRange) //fieldType == DOUBLE_FIELD) { double max, min; dVal(minValue, min); dVal(maxValue, max); minValue.vt = VT_R8; maxValue.vt = VT_R8; minValue.dblVal = min; maxValue.dblVal = max; } //bool useRange = minValue.vt == VT_R8 && maxValue.vt == VT_R8 && fieldType != STRING_FIELD; std::vector<CategoriesData>* result = new std::vector<CategoriesData>; if (ClassificationType == ctUniqueValues) { std::set<CComVariant> dict; CComVariant val; for (long i = 0; i < numShapes; i++) { VariantCopy(&val, srcValues[i]); if (useRange && (val.dblVal < minValue.dblVal || val.dblVal > maxValue.dblVal)) continue; if (dict.find(val) == dict.end()) dict.insert(val); } /* creating categories */ std::vector<CComVariant> values; copy(dict.begin(), dict.end(), inserter(values, values.end())); for (int i = 0; i < (int)values.size(); i++) { CategoriesData data; data.minValue = values[i]; data.maxValue = values[i]; result->push_back(data); } dict.clear(); values.clear(); } else if (ClassificationType == ctEqualSumOfValues) { CComVariant val; // sorting the values std::vector<double> values; double totalSum = 0, dValue; for (int i = 0; i < numShapes; i++) { VariantCopy(&val, srcValues[i]); if (useRange && (val.dblVal < minValue.dblVal || val.dblVal > maxValue.dblVal)) continue; dVal(val, dValue); val.Clear(); values.push_back(dValue); totalSum += dValue; } sort(values.begin(), values.end()); double step = totalSum / (double)numClasses; int index = 1; double sum = 0; for (int i = 0; i < (int)values.size(); i++) { sum += values[i]; if (sum >= step * (double)index || i == numShapes - 1) { CategoriesData data; if (index == numClasses) data.maxValue = values[values.size() - 1]; else if (i != 0) data.maxValue = (values[i] + values[i - 1]) / 2; else data.maxValue = values[0]; if (index == 1) data.minValue = values[0]; else data.minValue = (*result)[result->size() - 1].maxValue; result->push_back(data); index++; } } } else if (ClassificationType == ctEqualIntervals) { CComVariant vMin, vMax; if (useRange) { vMin = minValue; vMax = maxValue; } else { GetMinValue(srcValues, vMin, true); GetMinValue(srcValues, vMax, false); } double dMin, dMax; dVal(vMin, dMin); dVal(vMax, dMax); vMin.Clear(); vMax.Clear(); /* creating classes */ double dStep = (dMax - dMin) / (double)numClasses; while (dMin < dMax) { CategoriesData data; data.minValue = dMin; data.maxValue = dMin + dStep; result->push_back(data); dMin += dStep; } } else if (ClassificationType == ctEqualCount) { CComVariant vMin, vMax; if (useRange) { vMin = minValue; vMax = maxValue; } else { GetMinValue(srcValues, vMin, true); GetMinValue(srcValues, vMax, false); } double dMin, dMax; dVal(vMin, dMin); dVal(vMax, dMax); vMin.Clear(); vMax.Clear(); // sorting the values std::vector<double> values; for (int i = 0; i < numShapes; i++) { VariantCopy(&vMin, srcValues[i]); dVal(vMin, dMin); vMin.Clear(); values.push_back(dMin); } sort(values.begin(), values.end()); /* creating classes */ int i = 0; int count = numShapes / numClasses; for (int i = 0; i < numShapes; i += count) { dMin = values[i]; if (i + count < numShapes) dMax = values[i + count]; else dMax = values[numShapes - 1]; CategoriesData data; data.minValue = dMin; data.maxValue = dMax; result->push_back(data); } values.clear(); } else if (ClassificationType == ctNaturalBreaks) { CComVariant vMin; double dMin; // sorting the values std::vector<double> values; for (int i = 0; i < numShapes; i++) { VariantCopy(&vMin, srcValues[i]); if (useRange && (vMin.dblVal < minValue.dblVal || vMin.dblVal > maxValue.dblVal)) continue; dVal(vMin, dMin); vMin.Clear(); values.push_back(dMin); } sort(values.begin(), values.end()); CJenksBreaks breaks(&values, numClasses); if (breaks.Initialized()) { breaks.Optimize(); std::vector<long>* startIndices = breaks.get_Results(); //std::vector<int>* startIndices = breaks.TestIt(&values, numClasses); if (startIndices) { for (unsigned int i = 0; i < startIndices->size(); i++) { CategoriesData data; data.minValue = values[(*startIndices)[i]]; if (i == startIndices->size() - 1) data.maxValue = values[values.size() - 1]; else data.maxValue = values[(*startIndices)[i + 1]]; result->push_back(data); } delete startIndices; } } } // TODO: implement this as well; then it can be used in table class //else if (ClassificationType == ctStandardDeviation) // ------------------------------------------------------ // generating text expressions // ------------------------------------------------------ if (ClassificationType == ctUniqueValues) { USES_CONVERSION; for (int i = 0; i < (int)result->size(); i++) { //CString strExpression; CString strValue; CComVariant* val = &(*result)[i].minValue; switch (val->vt) { case VT_BSTR: strValue = OLE2CA(val->bstrVal); (*result)[i].name = strValue; (*result)[i].expression = "[" + fieldName + "] = \"" + strValue + "\""; break; case VT_R8: strValue.Format("%g", val->dblVal); (*result)[i].name = strValue; (*result)[i].expression = "[" + fieldName + "] = " + strValue; break; case VT_I4: strValue.Format("%i", val->lVal); (*result)[i].name = strValue; (*result)[i].expression = "[" + fieldName + "] = " + strValue; break; } } } else //if (ClassificationType == ctEqualIntervals || ClassificationType == ctEqualCount) { // in case % is present, we need to put to double it for proper formatting fieldName.Replace("%", "%%"); for (int i = 0; i < (int)result->size(); i++) { CategoriesData* data = &((*result)[i]); CString strExpression, strName, sFormat; if (i == 0) { data->minValue.dblVal = floor(data->minValue.dblVal); } else if (i == result->size() - 1) { data->maxValue.dblVal = ceil(data->maxValue.dblVal); } CString upperBound = (i == result->size() - 1) ? "<=" : "<"; switch (data->minValue.vt) { case VT_R8: sFormat = "%g"; data->name = Utility::FormatNumber(data->minValue.dblVal, sFormat) + " - " + Utility::FormatNumber(data->maxValue.dblVal, sFormat); data->expression.Format("[" + fieldName + "] >= %f AND [" + fieldName + "] " + upperBound + " %f", data->minValue.dblVal, data->maxValue.dblVal); break; case VT_I4: sFormat = "%i"; data->name = Utility::FormatNumber(data->minValue.dblVal, sFormat) + " - " + Utility::FormatNumber(data->maxValue.dblVal, sFormat); data->expression.Format("[" + fieldName + "] >= %i AND [" + fieldName + "] " + upperBound + " %i", data->minValue.lVal, data->maxValue.lVal); break; } } } if (result->size() > 0) { return result; } else { delete result; return NULL; } }
int main() { set<int> A,B,C,Acpy; aed::set<int> AA,BB,CC,AAcpy; int N=1024*256, m=3, M=100; double avdepth = 0.0, avdepthlv=0.0; for (int k=0; k<M; k++) { AA.clear(); for (int j=0; j<N; j++) { int x = irand(m*N); AA.insert(x); } double ad,adlv; avheight(AA.tree(),ad,adlv); cout << "ad: " << ad << " ,adlv: " << adlv << endl; avdepth += ad; avdepthlv += adlv; } cout << "avrg depth: " << avdepth/double(M) << endl; cout << "min. avrg depth: " << log2(double(N))-1 << endl; cout << "avrg depth leaves: " << avdepthlv/double(M) << endl; cout << "min. avrg depth leaves: " << log2(double(N)) << endl; #if 0 cout << "insertando "; for (int j=0; j<N; j++) { int x = irand(m*N); cout << x << endl; A.insert(x); AA.insert(x); x = irand(m*N); B.insert(x); BB.insert(x); } cout << endl; print_tree(AA.tree()); assert(are_equal(AA,A)); assert(are_equal(BB,B)); set_print(A); set_print(AA); #define VER_ABB(T) \ cout << #T " is abb: " << abb_p(T.tree()) << endl; \ assert(abb_p(T.tree())) VER_ABB(AA); VER_ABB(BB); for (int j=0; j<m*N; j++) { bool inA = (A.find(j)!=A.end()); bool inAA = (AA.find(j)!=AA.end()); if (inA != inAA) cout << "in A: " << inA << "in AA: " << inAA << endl; } Acpy = A; AAcpy = AA; assert(are_equal(AAcpy,Acpy)); VER_ABB(AAcpy); for (int j=0; j<m*N; j++) { A.erase(2*j); AA.erase(2*j); } assert(are_equal(AA,A)); cout << "Eliminados los elementos pares\n"; set_print(A); set_print(AA); VER_ABB(AA); A = Acpy; AA = AAcpy; cout << "Recupera elementos\n"; set_print(A); set_print(AA); assert(are_equal(AA,A)); VER_ABB(AA); cout << "B\n"; set_print(B); set_print(BB); VER_ABB(BB); aed::set_union(AA,BB,CC); C.clear(); set_union(A.begin(),A.end(), B.begin(),B.end(),inserter(C,C.begin())); assert(are_equal(CC,C)); VER_ABB(CC); cout << "C = A union B\n"; set_print(C); set_print(CC); aed::set_intersection(AA,BB,CC); C.clear(); set_intersection(A.begin(),A.end(), B.begin(),B.end(),inserter(C,C.begin())); assert(are_equal(CC,C)); VER_ABB(CC); cout << "C = A intersection B\n"; set_print(C); set_print(CC); aed::set_difference(AA,BB,CC); C.clear(); set_difference(A.begin(),A.end(), B.begin(),B.end(),inserter(C,C.begin())); assert(are_equal(CC,C)); VER_ABB(CC); cout << "C = A - B\n"; set_print(C); set_print(CC); aed::set_difference(BB,AA,CC); C.clear(); set_difference(B.begin(),B.end(), A.begin(),A.end(),inserter(C,C.begin())); assert(are_equal(CC,C)); VER_ABB(CC); cout << "C = B - A \n"; set_print(C); set_print(CC); #endif }
int main() { ColoredGraph<GraphVertex,TriColor> gr; set<GraphVertex,less<GraphVertex> > groupsall, filesall,functionsall; set<GraphVertex,less<GraphVertex> > groupssome, filessome,functionssome,S; set<GraphVertex,less<GraphVertex> > groupsnot, filesnot,functionsnot; ifstream ifs1("groups.txt"); ifstream ifs2("files.txt"); ifstream ifs3("files.txt"); ifstream ifs4("choices.txt"); cerr << "reading groups"; readDoubleColumnGraph(ifs1,groupsall,gr,true); cerr << ", files"; readDoubleColumnGraph(ifs2,filesall,gr,true); cerr << ", functions\n"; readDoubleColumnGraph(ifs3,functionsall,gr,false); readSingleColumn(ifs4,gr); #if 1 ifstream ifs5("depends.txt"); list<list<string> > dbllist; readMultiColumns(ifs5,dbllist); #endif bool todo = true; while(todo) { todo = false; gr.ColorChildComponents(TriColor::s_one,TriColor::s_two); list<GraphVertex> L(gr.getColored(TriColor::s_two)); copy(L.begin(),L.end(),inserter(S,S.begin())); #if 1 todo = addElements(gr,TriColor::s_one,S,dbllist); cerr << "addelements give " << todo << '\n'; #endif }; cerr << "Here is the set after the loop:\n"; printset(cerr,S,","); set_intersection(S.begin(),S.end(),groupsall.begin(),groupsall.end(), inserter(groupssome,groupssome.begin())); set_intersection(S.begin(),S.end(),filesall.begin(),filesall.end(), inserter(filessome,filessome.begin())); set_intersection(functionsall.begin(),functionsall.end(),S.begin(),S.end(), inserter(functionssome,functionssome.begin())); set_difference(groupsall.begin(),groupsall.end(),S.begin(),S.end(), inserter(groupsnot,groupsnot.begin())); set_difference(filesall.begin(),filesall.end(),S.begin(),S.end(), inserter(filesnot,filesnot.begin())); set_difference(functionsall.begin(),functionsall.end(),S.begin(),S.end(), inserter(functionsnot,functionsnot.begin())); cerr << "all groups:\n"; printset(cerr,groupsall,", "); cerr << "\nall files:\n"; printset(cerr,filesall,", "); cerr << "\nall functions:\n"; printset(cerr,functionsall,", "); cerr << "\n\n\n"; cerr << "groups (not):\n"; printset(cerr,groupsnot,", "); cerr << "\nfiles (not):\n"; printset(cerr,filesnot,", "); cerr << "\nfunctions(not):\n"; printset(cerr,functionsnot,", "); cerr << "\n\n\n"; cerr << "groups:\n"; printset(cerr,groupssome,", "); cerr << "\nfiles:\n"; printset(cerr,filessome,", "); cerr << "\nfunctions:\n"; printset(cerr,functionssome,", "); cerr << "Staring creation of the file Makefile.mark\n"; ofstream ofs("Makefile.mark"); ofs << "p9clist = "; printset(ofs,filessome,".o \\\n",".o \n"); ofs.close(); cerr << "Ended creation of the file Makefile.mark\n"; cerr << "Staring creation of the file Makefile.cp\n"; ofstream ofs2("Makefile.cp"); ofs2 << "cp "; printset(ofs2,filessome,".[hc]pp copyplace/ \n cp ",".[hc]pp copyplace/ \n"); ofs2.close(); cerr << "Ended creation of the file Makefile.cp\n"; };
vector<set<int> >electre::distillate(set<int> A, bool down) { set<int>::iterator it = A.begin(); set<int>::iterator it2 = A.begin(); set<int> D = A; // find max credibility set<int>::iterator it1 = D.begin(); double max_cred = 0.0; while (it1 != D.end()) { set<int>::iterator it2 = it1; it2++; while (it2 != D.end()) { double c1 = cred_matrix[matloc(*it1, *it2)]; double c2 = cred_matrix[matloc(*it2, *it1)]; // printf ("c1 %f c2 %f\n", c1, c2); if (c1 > max_cred) max_cred = c1; if (c2 > max_cred) max_cred = c2; it2++; } it1++; } double cutlevel = max_cred; do { // first, lower the cutting level double cut_thr = cutlevel - s(cutlevel); cutlevel = 0.0; // then find the highest cutting level below the threshold it1 = D.begin(); while (it1 != D.end()) { set<int>::iterator it2 = it1; it2++; while (it2 != D.end()) { double c1 = cred_matrix[matloc(*it1, *it2)]; double c2 = cred_matrix[matloc(*it2, *it1)]; // printf ("c1 %f c2 %f\n", c1, c2); if ((c1 > cutlevel) && (c1 < cut_thr)) cutlevel = c1; if ((c2 > cutlevel) && (c2 < cut_thr)) cutlevel = c2; it2++; } it1++; } // printf ("cut_thr %f\n", cut_thr); //printf ("cutlevel %f\n", cutlevel); if (cutlevel <= 0.0) break; vector<int> quals (D.size()); int maxormin = calculate_qualifications(D, quals, cutlevel, down); set<int> nset; set<int>::iterator ai = D.begin(); for (unsigned int i=0;i<quals.size();i++) { if (quals[i] == maxormin) nset.insert(*ai); ai++; // printf ("quals %d %d\n", i, quals[i]); } D = nset; } while (D.size() > 1); set<int> diffset; set_difference(A.begin(), A.end(), D.begin(), D.end(), inserter(diffset, diffset.begin())); vector<set<int> > res; res.push_back(D); if (diffset.size() > 0) { vector<set<int> > dists = distillate(diffset, down); for (unsigned int i=0;i<dists.size();i++) res.push_back(dists[i]); } return res; }
inline OutputContainer& split(SequenceContainer& seq, DelimiterContainer& deli, OutputContainer& out) { split(seq.begin(), seq.end(), deli.begin(), deli.end(), inserter(out, out.end())); return out; }
vector<set<int> >electre::distillate(bool down) { double lam_k = 0.0; double lam_k1 = 0.0; // int r = 0; set<int> A; vector<set<int> > D; vector<set<int> > C; vector<int> quals(get_no_alts()); for (int i=0;i<get_no_alts();i++) A.insert(i); do { int k = 0; D.resize(k+1); D[k] = A; set<int>::iterator it = A.begin(); // lam_k = max(...) while (it != A.end()) { int ind1 = *it; set<int>::iterator it2 = ++it; while (it2 != A.end()) { int ind2 = *it2; double credval = cred_matrix[matloc(ind1, ind2)]; if (credval > lam_k) lam_k = credval; credval = cred_matrix[matloc(ind2, ind1)]; if (credval > lam_k) lam_k = credval; it2++; } } // begin inner repeat do { set<int>::iterator it = D[k].begin(); double diff = lam_k - s(lam_k); lam_k1 = 0.0; // lam_k+1 = max(...) while (it != D[k].end()) { int ind1 = *it; set<int>::iterator it2 = ++it; while (it2 != D[k].end()) { int ind2 = *it2; double credval = cred_matrix[matloc(ind1, ind2)]; if (credval > lam_k1 && credval < diff) lam_k1 = credval; credval = cred_matrix[matloc(ind2, ind1)]; if (credval > lam_k1 && credval < diff) lam_k1 = credval; it2++; } } // calc qualification scores int maxormin = calculate_qualifications(D[k], quals, lam_k, down); set<int> nset; for (unsigned int i=0;i<quals.size();i++) { if (quals[i] == maxormin) nset.insert(i); } D.resize(k+2); D[k+1] = nset; k++; lam_k = lam_k1; } while (D[k].size() != 1 && lam_k != 0.0); C.push_back(D[k]); set<int> diffset; set_difference (A.begin(), A.end(), D[k].begin(), D[k].end(), inserter(diffset, diffset.begin())); A = diffset; } while (A.size() != 0); return C; }
void trace_plot(const graph_t<NodeCount> & graph, const ObservationIteratorT & observation_begin, const ObservationIteratorT & observation_end, OutputIteratorT & output_it, size_t num_samples) { Q<NodeCount> q; for(size_t i = 0; i < NodeCount; ++i) { for(size_t j = 0; j < num_edges; ++j) { D_over_stop_state<NodeCount, ObservationIteratorT> d(graph, state_t(i, edges[j]), observation_begin, observation_end); std::vector< probability_t > weighted_samples(num_samples / (NodeCount * num_edges), probability_t(0)); for(size_t k = 0; k < smooth_samples; ++k) { sigma_t sigma(random_sigma<NodeCount>()); // <sigma_t, Q<NodeCount>, D_over_stop_state<NodeCount, ObservationIteratorT>, sampler<sigma_t, probability_t, OutputIteratorT> > std::vector< std::pair<sigma_t, probability_t> > samples; std::back_insert_iterator< std::vector< std::pair<sigma_t, probability_t> > > inserter(samples); sampler<sigma_t, probability_t, std::back_insert_iterator< std::vector< std::pair<sigma_t, probability_t> > > > s(inserter, 0, 1); metropolis_hastings(sigma, q, d, s, num_samples / (NodeCount * num_edges)); //std::cerr << "asdf4, state: " << i << ", " << edges[j] << ", num_samples: " << samples.size() << " of " << (num_samples / (NodeCount * num_edges)) << std::endl; for(size_t i = 0; i < samples.size(); ++i) weighted_samples[i] += samples[i].second; } for(size_t i = 0; i < weighted_samples.size(); ++i) weighted_samples[i] /= smooth_samples; output_it = weighted_samples; ++output_it; } } }
template <typename PointT> void pcl::ExtractIndices<PointT>::applyFilterIndices (std::vector<int> &indices) { if (indices_->size () > input_->points.size ()) { PCL_ERROR ("[pcl::%s::applyFilter] The indices size exceeds the size of the input.\n", getClassName ().c_str ()); indices.clear (); removed_indices_->clear (); return; } if (!negative_) // Normal functionality { indices = *indices_; if (extract_removed_indices_) { // Set up the full indices set std::vector<int> full_indices (input_->points.size ()); for (int fii = 0; fii < static_cast<int> (full_indices.size ()); ++fii) // fii = full indices iterator full_indices[fii] = fii; // Set up the sorted input indices std::vector<int> sorted_input_indices = *indices_; std::sort (sorted_input_indices.begin (), sorted_input_indices.end ()); // Store the difference in removed_indices removed_indices_->clear (); set_difference (full_indices.begin (), full_indices.end (), sorted_input_indices.begin (), sorted_input_indices.end (), inserter (*removed_indices_, removed_indices_->begin ())); } } else // Inverted functionality { // Set up the full indices set std::vector<int> full_indices (input_->points.size ()); for (int fii = 0; fii < static_cast<int> (full_indices.size ()); ++fii) // fii = full indices iterator full_indices[fii] = fii; // Set up the sorted input indices std::vector<int> sorted_input_indices = *indices_; std::sort (sorted_input_indices.begin (), sorted_input_indices.end ()); // Store the difference in indices indices.clear (); set_difference (full_indices.begin (), full_indices.end (), sorted_input_indices.begin (), sorted_input_indices.end (), inserter (indices, indices.begin ())); if (extract_removed_indices_) removed_indices_ = indices_; } }
int main(int argc, const char **argv) { srand(time(NULL)); const size_t num_samples = 10000, burn_in = 5, sampling_interval = 5; const size_t NodeCount = 12; typename graph_t<NodeCount>::connection_t map[][NodeCount] = /*{ { "", "L", "0", "R" }, { "0","", "R", "L" }, { "0", "R","", "L" }, { "R", "0", "L","" }, };*/ { {"", "0", "R","","","","","","", "L","","" }, { "0","", "L", "R","","","","","","","","" }, { "0", "L","", "R","","","","","","","","" }, {"", "L", "R","","","","","","","","", "0" }, {"","","","","", "R","","", "L","", "0","" }, {"","","","", "R","","", "L", "0","","","" }, {"","","","","","","", "R","","", "L", "0" }, {"","","","","", "0", "R","","","", "L","" }, {"","","","", "R", "L","","","", "0","","" }, { "0","","","","","","","", "L","","", "R" }, {"","","","", "R","", "0", "L","","","","" }, {"","","", "L","","", "R","","", "0","","" }, }; graph_t<NodeCount> graph; graph.parse(map); const size_t observation_length = 100; typedef std::vector<edge_t> observation_sequence_t; observation_sequence_t observation; const state_t state(generate_observation_sequence<NodeCount>(graph, observation_length, std::back_insert_iterator<observation_sequence_t>(observation))); std::cerr << "observation sequence:"; std::copy(observation.begin(), observation.end(), std::ostream_iterator<edge_t>(std::cerr, ", ")); std::cerr << "stop state is: " << state << std::endl; //std::cerr << "previous:" << graph.previous(state_t(0, '0'), 0) << std::endl; typedef std::vector< std::pair<sigma_t, probability_t> > sigma_sequence_t; sigma_sequence_t sigmas; std::back_insert_iterator<sigma_sequence_t> inserter(sigmas); sample_sigmas<NodeCount>(graph, observation.begin(), observation.end(), inserter, num_samples, burn_in, sampling_interval); /*std::cerr << "sigmas:" << std::endl; probability_t p(0); for(sigma_sequence_t::iterator it = sigmas.begin(); it != sigmas.end(); ++it) { std::cerr << "(" << it->first << ", " << it->second << "), "; p += it->second; }*/ //std::cerr << "state_probability: " << state_probability<NodeCount>(state, graph, observation.begin(), observation.end(), sigmas.begin(), sigmas.end()) << std::endl; std::vector< std::pair<state_t, probability_t> > sorted_states; probability_t total_prob(0); for(size_t i = 0; i < NodeCount; ++i) { for(size_t j = 0; j < num_edges; ++j) { probability_t prob = state_probability<NodeCount>(state_t(i, edges[j]), graph, observation.begin(), observation.end(), sigmas.begin(), sigmas.end()); //std::cerr << "state_probability: " << prob << " for stop_state: " << state_t(i, edges[j]) << std::endl; total_prob += prob; sorted_states.push_back(std::make_pair(state_t(i, edges[j]), prob)); } } std::cerr << "total_prob: " << total_prob << std::endl; std::sort(sorted_states.begin(), sorted_states.end(), state_probability_sort_comp()); for(std::vector< std::pair<state_t, probability_t> >::const_iterator it = sorted_states.begin(); it != sorted_states.end(); ++it) { std::cerr << "probability: " << it->second << " for state: " << it->first; if (it->first.v == state.v && it->first.e == state.e) std::cerr << " [ answer ]"; std::cerr << std::endl; } /* * trace plot */ std::vector<std::vector< probability_t > > traces; std::back_insert_iterator< std::vector<std::vector< probability_t > > > traces_inserter(traces); trace_plot(graph, observation.begin(), observation.end(), traces_inserter, num_samples); //std::cerr << "plot done" << std::endl; std::fstream file("plot.py", std::ios_base::out); /* pl.semilogy([ prob / length for prob in p ]) #break pl.xlabel('interval') pl.ylabel('log(probability) + k') pl.title('Convergence plot') pl.grid(True) pl.savefig(filename, bbox_inches = 0) pl.show() */ file << "import pylab as pl" << std::endl << "pl.xlabel('interval')\npl.ylabel('log(probability) + k')\npl.title('Convergence plot')\npl.grid(True)" << std::endl; for(std::vector<std::vector< probability_t > >::const_iterator it = traces.begin(); it != traces.end(); ++it) { file << "pl.semilogy([ "; for(std::vector< probability_t >::const_iterator jt = it->begin(); jt != it->end() -1; ++jt) file << *jt << ", "; file << *(it->end() - 1) << " ])" << std::endl; } file << "pl.show()" << std::endl; file.close(); }
void SettingsTree::setImpl(const std::string &key, const SettingValue &value) { Inserter inserter(key, value); boost::apply_visitor(inserter, myTree); }
void DialogSelection::Process(wxCommandEvent&) { std::set<AssDialogue*> matches; try { matches = process( from_wx(match_text->GetValue()), case_sensitive->IsChecked(), match_mode->GetSelection(), select_unmatching_lines->GetValue(), apply_to_comments->IsChecked(), apply_to_dialogue->IsChecked(), dialogue_field->GetSelection(), con->ass); } catch (agi::Exception const&) { Close(); return; } int action = selection_change_type->GetSelection(); SubtitleSelection old_sel, new_sel; if (action != ACTION_SET) con->selectionController->GetSelectedSet(old_sel); wxString message; size_t count = 0; switch (action) { case ACTION_SET: new_sel = matches; switch (count = new_sel.size()) { case 0: message = _("Selection was set to no lines"); break; case 1: message = _("Selection was set to one line"); break; default: message = wxString::Format(_("Selection was set to %u lines"), (unsigned)count); } break; case ACTION_ADD: set_union(old_sel.begin(), old_sel.end(), matches.begin(), matches.end(), inserter(new_sel, new_sel.begin())); switch (count = new_sel.size() - old_sel.size()) { case 0: message = _("No lines were added to selection"); break; case 1: message = _("One line was added to selection"); break; default: message = wxString::Format(_("%u lines were added to selection"), (unsigned)count); } break; case ACTION_SUB: set_difference(old_sel.begin(), old_sel.end(), matches.begin(), matches.end(), inserter(new_sel, new_sel.begin())); switch (count = old_sel.size() - new_sel.size()) { case 0: message = _("No lines were removed from selection"); break; case 1: message = _("One line was removed from selection"); break; default: message = wxString::Format(_("%u lines were removed from selection"), (unsigned)count); } break; case ACTION_INTERSECT: set_intersection(old_sel.begin(), old_sel.end(), matches.begin(), matches.end(), inserter(new_sel, new_sel.begin())); switch (count = old_sel.size() - new_sel.size()) { case 0: message = _("No lines were removed from selection"); break; case 1: message = _("One line was removed from selection"); break; default: message = wxString::Format(_("%u lines were removed from selection"), (unsigned)count); } break; } if (count == 0) wxMessageBox(message, _("Selection"), wxOK | wxCENTER, this); else StatusTimeout(message); if (new_sel.size() && !new_sel.count(con->selectionController->GetActiveLine())) con->selectionController->SetActiveLine(*new_sel.begin()); con->selectionController->SetSelectedSet(new_sel); AssDialogue *new_active = con->selectionController->GetActiveLine(); if (new_sel.size() && !new_sel.count(new_active)) new_active = *new_sel.begin(); con->selectionController->SetSelectionAndActive(new_sel, new_active); Close(); }
FCBlock Reasoner::getBlockFromQuery(Literal constantsQuery, Literal &boundQuery, std::vector<uint8_t> *posJoins, std::vector<Term_t> *possibleValuesJoins) { uint8_t nconstants = (uint8_t) constantsQuery.getTupleSize(); VTuple constantsTuple = constantsQuery.getTuple(); std::shared_ptr<FCInternalTable> table; if (nconstants == 0) { table = std::shared_ptr<FCInternalTable>(new SingletonTable(0)); } else { SegmentInserter inserter(nconstants); Term_t tuple[3]; uint8_t nPosToCopy = 0; uint8_t posToCopy[3]; assert(boundQuery.getTupleSize() <= 3); for (uint8_t i = 0; i < (uint8_t) boundQuery.getTupleSize(); ++i) { if (!boundQuery.getTermAtPos(i).isVariable()) { posToCopy[nPosToCopy++] = i; tuple[i] = boundQuery.getTermAtPos(i).getValue(); } } //Add the input tuples if (posJoins != NULL) { const uint8_t addSize = (uint8_t) posJoins->size(); for (size_t i = 0; i < possibleValuesJoins->size(); i += addSize) { for (uint8_t j = 0; j < addSize; ++j) { tuple[posJoins->at(j)] = possibleValuesJoins->at(i + j); } inserter.addRow(tuple, posToCopy); } } else { inserter.addRow(tuple, posToCopy); } std::shared_ptr<const Segment> seg; if (inserter.isSorted()) { seg = inserter.getSegment(); } else { seg = inserter.getSegment()->sortBy(NULL); } table = std::shared_ptr<FCInternalTable>( new InmemoryFCInternalTable(nconstants, 0, true, seg)); //change the constantsQuery if (possibleValuesJoins != NULL && possibleValuesJoins->size() > 1) { uint8_t varId = 1; for (uint8_t i = 0; i < nconstants; ++i) { if (!inserter.getSegment()->getColumn(i)->isConstant()) { constantsTuple.set(VTerm(varId++, 0), i); } } } } //iteration==1 return FCBlock(1, table, Literal(constantsQuery.getPredicate(), constantsTuple), NULL, 0, true); }
Py::Object projectToSVG(const Py::Tuple& args, const Py::Dict& keys) { static char* argNames[] = {"topoShape", "direction", "type", "tolerance", "vStyle", "v0Style", "v1Style", "hStyle", "h0Style", "h1Style", NULL}; PyObject *pcObjShape = 0; PyObject *pcObjDir = 0; const char *extractionTypePy = 0; ProjectionAlgos::ExtractionType extractionType = ProjectionAlgos::Plain; const float tol = 0.1f; PyObject* vStylePy = 0; ProjectionAlgos::XmlAttributes vStyle; PyObject* v0StylePy = 0; ProjectionAlgos::XmlAttributes v0Style; PyObject* v1StylePy = 0; ProjectionAlgos::XmlAttributes v1Style; PyObject* hStylePy = 0; ProjectionAlgos::XmlAttributes hStyle; PyObject* h0StylePy = 0; ProjectionAlgos::XmlAttributes h0Style; PyObject* h1StylePy = 0; ProjectionAlgos::XmlAttributes h1Style; // Get the arguments if (!PyArg_ParseTupleAndKeywords( args.ptr(), keys.ptr(), "O!|O!sfOOOOOO", argNames, &(TopoShapePy::Type), &pcObjShape, &(Base::VectorPy::Type), &pcObjDir, &extractionTypePy, &tol, &vStylePy, &v0StylePy, &v1StylePy, &hStylePy, &h0StylePy, &h1StylePy)) throw Py::Exception(); // Convert all arguments into the right format TopoShapePy* pShape = static_cast<TopoShapePy*>(pcObjShape); Base::Vector3d directionVector(0,0,1); if (pcObjDir) directionVector = static_cast<Base::VectorPy*>(pcObjDir)->value(); if (extractionTypePy && string(extractionTypePy) == "ShowHiddenLines") extractionType = ProjectionAlgos::WithHidden; if (vStylePy) copy(Py::Dict(vStylePy), inserter(vStyle, vStyle.begin())); if (v0StylePy) copy(Py::Dict(v0StylePy), inserter(v0Style, v0Style.begin())); if (v1StylePy) copy(Py::Dict(v1StylePy), inserter(v1Style, v1Style.begin())); if (hStylePy) copy(Py::Dict(hStylePy), inserter(hStyle, hStyle.begin())); if (h0StylePy) copy(Py::Dict(h0StylePy), inserter(h0Style, h0Style.begin())); if (h1StylePy) copy(Py::Dict(h1StylePy), inserter(h1Style, h1Style.begin())); // Execute the SVG generation ProjectionAlgos Alg(pShape->getTopoShapePtr()->getShape(), directionVector); Py::String result(Alg.getSVG(extractionType, tol, vStyle, v0Style, v1Style, hStyle, h0Style, h1Style)); return result; }
void pcl::ExtractIndices<pcl::PCLPointCloud2>::applyFilter (PCLPointCloud2 &output) { if (keep_organized_) { output = *input_; if (negative_) { // Prepare the output and copy the data for (size_t i = 0; i < indices_->size (); ++i) for (size_t j = 0; j < output.fields.size(); ++j) memcpy (&output.data[(*indices_)[i] * output.point_step + output.fields[j].offset], &user_filter_value_, sizeof(float)); } else { // Prepare a vector holding all indices std::vector<int> all_indices (input_->width * input_->height); for (int i = 0; i < static_cast<int>(all_indices.size ()); ++i) all_indices[i] = i; std::vector<int> indices = *indices_; std::sort (indices.begin (), indices.end ()); // Get the diference std::vector<int> remaining_indices; set_difference (all_indices.begin (), all_indices.end (), indices.begin (), indices.end (), inserter (remaining_indices, remaining_indices.begin ())); // Prepare the output and copy the data for (size_t i = 0; i < remaining_indices.size (); ++i) for (size_t j = 0; j < output.fields.size(); ++j) memcpy (&output.data[remaining_indices[i] * output.point_step + output.fields[j].offset], &user_filter_value_, sizeof(float)); } if (!pcl_isfinite (user_filter_value_)) output.is_dense = false; return; } if (indices_->empty () || (input_->width * input_->height == 0)) { output.width = output.height = 0; output.data.clear (); // If negative, copy all the data if (negative_) output = *input_; return; } if (indices_->size () == (input_->width * input_->height)) { // If negative, then return an empty cloud if (negative_) { output.width = output.height = 0; output.data.clear (); } // else, we need to return all points else output = *input_; return; } // Copy the common fields (header and fields should have already been copied) output.is_bigendian = input_->is_bigendian; output.point_step = input_->point_step; output.height = 1; // TODO: check the output cloud and assign is_dense based on whether the points are valid or not output.is_dense = false; if (negative_) { // Prepare a vector holding all indices std::vector<int> all_indices (input_->width * input_->height); for (int i = 0; i < static_cast<int>(all_indices.size ()); ++i) all_indices[i] = i; std::vector<int> indices = *indices_; std::sort (indices.begin (), indices.end ()); // Get the diference std::vector<int> remaining_indices; set_difference (all_indices.begin (), all_indices.end (), indices.begin (), indices.end (), inserter (remaining_indices, remaining_indices.begin ())); // Prepare the output and copy the data output.width = static_cast<uint32_t> (remaining_indices.size ()); output.data.resize (remaining_indices.size () * output.point_step); for (size_t i = 0; i < remaining_indices.size (); ++i) memcpy (&output.data[i * output.point_step], &input_->data[remaining_indices[i] * output.point_step], output.point_step); } else { // Prepare the output and copy the data output.width = static_cast<uint32_t> (indices_->size ()); output.data.resize (indices_->size () * output.point_step); for (size_t i = 0; i < indices_->size (); ++i) memcpy (&output.data[i * output.point_step], &input_->data[(*indices_)[i] * output.point_step], output.point_step); } output.row_step = output.point_step * output.width; }
void SipperMediaG711Codec::_startCommandProcessing() { std::string currcommand; if(_commandList.size() != 0) { currcommand = _commandList.front(); _commandList.pop_front(); if(currcommand.size() == 0) { _startCommandProcessing(); return; } } else { currcommand = "PLAY_REPEAT 0 0"; } SipperMediaPortable::trim(currcommand); logger.logMsg(TRACE_FLAG, 0, "Processing command [%s].\n", currcommand.c_str()); CommandVec playcommand; std::string delimiter = " "; std::insert_iterator<CommandVec> inserter(playcommand, playcommand.begin()); SipperMediaTokenizer(currcommand, delimiter, inserter); if(playcommand.size() == 0) { _startCommandProcessing(); return; } std::string loccommand = playcommand[0]; SipperMediaPortable::toUpper(playcommand[0]); if(playcommand[0] == "SLEEP") { std::string duration("0"); if(playcommand.size() > 1) { duration = playcommand[1]; } playcommand.clear(); playcommand.push_back("PLAY_REPEAT"); playcommand.push_back("0"); playcommand.push_back(duration); } else if((playcommand[0] != "PLAY") && (playcommand[0] != "PLAY_REPEAT")) { playcommand.clear(); playcommand.push_back("PLAY_REPEAT"); playcommand.push_back(loccommand); playcommand.push_back("0"); } while(playcommand.size() < 3) { playcommand.push_back("0"); } if(playcommand[0] == "PLAY") { _repeatFlag = false; } else { _repeatFlag = true; } audioContentHolder.setObj(SipperMediaFileLoader::getInstance().loadFile(playcommand[1])); _offset = 0; int duration = atoi(playcommand[2].c_str()); if(duration == 0) { _wakeupTime.tv_sec = 0x7FFFFFFF; _wakeupTime.tv_usec = 0; } else { SipperMediaPortable::getTimeOfDay(&_wakeupTime); _wakeupTime.tv_sec += duration; } }
static void FriendSet( const string *fs, int count ) { copy( fs, fs+count, inserter( friendset, friendset.end() )); }
void MSwithLevelFP::UpdateMSINFO( MSNODE* msnode_, double numticktime, double ticktime){ msnode = msnode_; /**************************************************/ POLAXIS temp_polar = msnode->msdata.cart2pol((*BSOxy_)[0], msnode->msdata.position); double angle = temp_polar.th; if(angle>=PI/3) angle = temp_polar.th - floor(temp_polar.th / (PI/3) )*(PI/3); else if (angle < 0) angle = temp_polar.th + (floor(fabs(temp_polar.th) / (PI/3))+1) * (PI/3); if(temp_polar.r <= R * sin(PI/3) / sin((2 * PI / 3)-angle)) //check if the position is inside the cell; //use the triangle proportion rule: sin(theta) is propotional //to the length of facing side msnode->msdata.temp_test = 1; else msnode->msdata.temp_test = 0; /**************************************************/ if( IsOnStreet(msnode->msdata.position) ){ msnode->msdata.on_street = 1; }else if( IsOnStreet(msnode->msdata.position) ){ msnode->msdata.on_street = 0; } /*********************check sector*****************************/ /*********************加快程式運作*****************************/ if(msnode->msdata.femto_mode==0) RSSI_ServingBS=MacroRSSI(msnode->msdata.ssector,msnode->msdata.scell,1); else if(msnode->msdata.femto_mode==1) RSSI_ServingBS=FemtoRSSI(msnode->msdata.sFS,2); /***********************掃描&換手決策***************************/ BSINFO optimumFemtoTarget; //Serving is macro & Period scan if( ( (int)(numticktime - msnode->msdata.ScanStartTickTime)%((int)(msnode->msdata.ScanPeriod/ticktime))==0&&msnode->msdata.femto_mode==0 )) { //printf("Serving:Macro\tPeriod Scan\n"); MacroScan(); UpdateFP(); extern double MeanNumInList; extern long int countList; extern double ListMissRateTotal; getNeighborFemtoList(); vector<int> NeighborListBySys; vector<int> intersectionResult; for(int i=0; i < msnode->msdata.fs_near_num; i++) { NeighborListBySys.push_back(msnode->msdata.FS_NEAR[i]); } sort(NeighborListBySys.begin(),NeighborListBySys.end()); MeanNumInList+= getFemtoListByFP(); sort(FemtoListByFP.begin(),FemtoListByFP.end()); set_intersection(FemtoListByFP.begin(),FemtoListByFP.end(),NeighborListBySys.begin(),NeighborListBySys.end(),inserter(intersectionResult,intersectionResult.begin())); if(FemtoListByFP.size()!=0){ extern Record ReMissRate; ReMissRate.InsertData(100*(FemtoListByFP.size()-intersectionResult.size())/FemtoListByFP.size()); ListMissRateTotal += ((FemtoListByFP.size()-intersectionResult.size())/FemtoListByFP.size()); countList++; } optimumFemtoScan(); optimumFemtoTarget = DecideTargetCell(2); Femtolist.clear(); //printf("getNeighborFemtoList:%d\n",getFemtoListByFP()); FemtoScan(); HandoverDecision(); extern double OptimumTargetmissCount; if(FemtoListByFP.size()!=0) if(optimumFemtoTarget.BSTYPE!=0) if(find_if( Femtolist.begin(), Femtolist.end(),findBSID(optimumFemtoTarget.BSID) ) == Femtolist.end()) {OptimumTargetmissCount++;} //Serving is macro && treigger scan }else if ( (msnode->msdata.femto_mode==0) && (RSSI_ServingBS < -100) ){ //printf("Serving:macro\ttrigger Scan\tRSSI:%f\n",MacroRSSI(msnode->msdata.ssector,msnode->msdata.scell,1)); MacroScan(); UpdateFP(); extern double MeanNumInList; extern long int countList; extern double ListMissRateTotal; getNeighborFemtoList(); vector<int> NeighborListBySys; vector<int> intersectionResult; for(int i=0; i < msnode->msdata.fs_near_num; i++) { NeighborListBySys.push_back(msnode->msdata.FS_NEAR[i]); } sort(NeighborListBySys.begin(),NeighborListBySys.end()); MeanNumInList+= getFemtoListByFP(); sort(FemtoListByFP.begin(),FemtoListByFP.end()); set_intersection(FemtoListByFP.begin(),FemtoListByFP.end(),NeighborListBySys.begin(),NeighborListBySys.end(),inserter(intersectionResult,intersectionResult.begin())); if(FemtoListByFP.size()!=0){ extern Record ReMissRate; ReMissRate.InsertData(100*(FemtoListByFP.size()-intersectionResult.size())/FemtoListByFP.size()); ListMissRateTotal += ((FemtoListByFP.size()-intersectionResult.size())/FemtoListByFP.size()); countList++; } optimumFemtoScan(); optimumFemtoTarget = DecideTargetCell(2); Femtolist.clear(); //printf("getNeighborFemtoList:%d\n",getFemtoListByFP()); FemtoScan(); HandoverDecision(); extern double OptimumTargetmissCount; if(FemtoListByFP.size()!=0) if(optimumFemtoTarget.BSTYPE!=0) if(find_if( Femtolist.begin(), Femtolist.end(),findBSID(optimumFemtoTarget.BSID) ) == Femtolist.end()) {OptimumTargetmissCount++;} //Serving is femto && trigger scan }else if( (msnode->msdata.femto_mode==1) && (RSSI_ServingBS < -95)){ //printf("Serving:femto\ttrigger Scan\tRSSI:%f\n",FemtoRSSI(msnode->msdata.sFS,2)); MacroScan(); UpdateFP(); extern double MeanNumInList; extern long int countList; extern double ListMissRateTotal; getNeighborFemtoList(); vector<int> NeighborListBySys; vector<int> intersectionResult; for(int i=0; i < msnode->msdata.fs_near_num; i++) { NeighborListBySys.push_back(msnode->msdata.FS_NEAR[i]); } sort(NeighborListBySys.begin(),NeighborListBySys.end()); MeanNumInList+= getFemtoListByFP(); sort(FemtoListByFP.begin(),FemtoListByFP.end()); set_intersection(FemtoListByFP.begin(),FemtoListByFP.end(),NeighborListBySys.begin(),NeighborListBySys.end(),inserter(intersectionResult,intersectionResult.begin())); if(FemtoListByFP.size()!=0){ extern Record ReMissRate; ReMissRate.InsertData(100*(FemtoListByFP.size()-intersectionResult.size())/FemtoListByFP.size()); ListMissRateTotal += ((FemtoListByFP.size()-intersectionResult.size())/FemtoListByFP.size()); countList++; } optimumFemtoScan(); optimumFemtoTarget = DecideTargetCell(2); Femtolist.clear(); //printf("getNeighborFemtoList:%d\n",getFemtoListByFP()); FemtoScan(); HandoverDecision(); extern double OptimumTargetmissCount; if(FemtoListByFP.size()!=0) if(optimumFemtoTarget.BSTYPE!=0) if(find_if( Femtolist.begin(), Femtolist.end(),findBSID(optimumFemtoTarget.BSID) ) == Femtolist.end()) {OptimumTargetmissCount++;} } extern double outage; if((msnode->msdata.femto_mode==0) && (RSSI_ServingBS < -100)) { printf("MS%d\tBlocking!!Position:(%f,%f)\t%s\tBlock %d\n",msnode->msdata.ID,msnode->msdata.position.x,msnode->msdata.position.y,IsOnStreet(msnode->msdata.position)?"街道":"房子",WhichBlock(msnode->msdata.position)); extern int outNum; outNum++; //printf("Outage!!!!!%f\n",outage); outage++; } else if( (msnode->msdata.femto_mode==1) && (RSSI_ServingBS < -100)) { printf("MS%d\tBlocking!!Position:(%f,%f)\t%s\tBlock %d\n",msnode->msdata.ID,msnode->msdata.position.x,msnode->msdata.position.y,IsOnStreet(msnode->msdata.position)?"街道":"房子",WhichBlock(msnode->msdata.position)); extern int outNum; outNum++; //printf("Outage!!!!!%f\n",outage); outage++; } if((msnode->msdata.femto_mode==0) && (RSSI_ServingBS >= -100)) { extern int macroNum; macroNum++; } if( (msnode->msdata.femto_mode==1) && (RSSI_ServingBS >= -100)) { extern int femtoNum; femtoNum++; } //msdata //Macrolist.clear(); //Femtolist.clear(); }
template<class T> std::set<T> GetSetIntersection( const std::set<T>& a, const std::set<T>& b ) { std::set<T> c; set_intersection( a.begin(), a.end(), b.begin(), b.end(), inserter( c, c.begin() ) ); return c; }
void OsamaAI::performAttack(GameGridLayer* playerGrid) { //For test purposes std::list<Point2D<int>> hitPoints; std::string line; std::ifstream file("/Users/pavel/Desktop/TowerDefence-Cocos2d-x/TowerDefence/OsamaCoords.txt"); if (file.is_open()) { while ( std::getline(file,line) ) { std::vector<std::string> x = split(line, ' '); if(line[0]=='#'||line.length()==0) continue; hitPoints.push_back(Point2D<int>(std::stoi(x[0]),std::stoi(x[1]))); } file.close(); } switch(state) { case State::searching: { //Point2D<int> point { rand()%10, rand() % 10}; Point2D<int> point ( hitPoints.front() ); hitPoints.pop_front(); //Osama do not hit a cells that are boundary to destroyed ships while (doesIntersectsWithBoundary(point)) { point = {rand()%10, rand()%10}; //generate new coordinates } if(!playerGrid->isCellTested(point.x, point.y)) { CellState cellState = memoryMatrix[point.x][point.y] = playerGrid->hitCell(point.x, point.y); switch(cellState) { case CellState::Hit: { startingPoint = point; if(point.x==0) usedDirections.insert(Direction::left); if(point.y==0) usedDirections.insert(Direction::down); if(point.x==9) usedDirections.insert(Direction::right); if(point.y==9) usedDirections.insert(Direction::up); shotsVector.push_back(point); pointsSet.insert(point); state = State::discoveringDirection; //transitionate to a new state } break; case CellState::Destroyed: //write ship coord and boundary into a set //it's and 1 deck ship otherwise we should hit from another state insertPointAndFillAdjacentPoints(point, point); break; default: pointsSet.insert(point); } } } break; //We're moving to that state if we have discovered a ship case State::discoveringDirection: { const Point2D<int> lastShot = shotsVector.back(); std::set<Direction> allDirections {Direction::up, Direction::down, Direction::left, Direction::right}; unusedDirections.clear(); std::vector<Direction> vec1 (begin(usedDirections), end(usedDirections)); std::vector<Direction> vec2 (begin(allDirections ), end(allDirections )); std::sort(begin(vec1), end(vec1), [](const Direction& d1, const Direction& d2) { return (static_cast<int>(d1) < static_cast<int>(d2)); }); std::sort(begin(vec2), end(vec2), [](const Direction& d1, const Direction& d2) { return (static_cast<int>(d1) < static_cast<int>(d2)); }); std::set_symmetric_difference(begin(vec1), end(vec1), begin(vec2), end (vec2), inserter(unusedDirections, unusedDirections.begin())); for(Direction direction: unusedDirections) { Point2D<int> vector{0,0}; this->choosenDirection = direction; switch(direction) { case Direction::up: vector = {0,1}; break; case Direction::down: vector = {0,-1}; break; case Direction::left: vector = {-1,0}; break; case Direction::right: vector = {1,0}; break; } Point2D<int> newShot = lastShot + vector; CellState cellState = CellState::Empty; cellState = playerGrid->hitCell(newShot.x, newShot.y); if(cellState==CellState::Hit) { //right direction was choosen. continue to destroy ship in that direction state = State::destroyingShip; break; } else if(cellState==CellState::Destroyed) { //we destroyed a ship with that shot. //store him in a matrix //store it bounds insertPointAndFillAdjacentPoints(startingPoint, newShot); state = State::searching; break; } else if(cellState==CellState::Miss) { //choose another direction //recall the shot //shotsVector.push_back(newShot); usedDirections.insert(direction); break; } } } break; case State::destroyingShip: { Point2D<int> vector{0,0}; const Point2D<int> lastShot = shotsVector.back(); switch(choosenDirection) { case Direction::up: vector = {0,1}; break; case Direction::down: vector = {0,-1}; break; case Direction::left: vector = {-1,0}; break; case Direction::right: vector = {1,0}; break; } Point2D<int> newShot = lastShot + vector; shotsVector.push_back(newShot); auto cellState = playerGrid->hitCell(newShot.x, newShot.y); switch(cellState) { case CellState::Destroyed: state = State::searching; //Osama destroyed the ship break; default: break; } } break; } }