public List<Integer> closestKValues(TreeNode root, double target, int k) {
     Deque<TreeNode> leftS = new ArrayDeque<TreeNode>();
     Deque<TreeNode> rightS = new ArrayDeque<TreeNode>();
     findNearest(root, target, leftS, true);
     findNearest(root, target, rightS, false);
     List<Integer> res = new ArrayList<Integer>();
     while (res.size() < k) {
         boolean use_left = false;
         boolean use_right = false;
         if (leftS.isEmpty()) {
             use_right = true;
         } else if (rightS.isEmpty()) {
             use_left = true;
         } else if (leftS.peek().val == rightS.peek().val) {
             use_left = use_right = true;
         } else if (target - leftS.peek().val < rightS.peek().val - target) {
             use_left = true;
         } else {
             use_right = true;
         }
         res.add(use_left ? leftS.peek().val : rightS.peek().val);
         if (use_left) {
             TreeNode node = leftS.pop();
             node = node.left;
             while (node != null) {
                 leftS.push(node);
                 node = node.right;
             }
             while (!leftS.isEmpty() && leftS.peek().val > target) {
                 leftS.pop();
             }
         }
         if (use_right) {
             TreeNode node = rightS.pop();
             node = node.right;
             while (node != null) {
                 rightS.push(node);
                 node = node.left;
             }
             while (!rightS.isEmpty() && rightS.peek().val < target) {
                 rightS.pop();
             }
         }
     }
     return res;
 }
Exemple #2
0
        BVHSceneNode* BVHSceneTree::findNearest(BVHSceneNode* node, uint64_t const& morton) const
        {
            if(morton < node->morton)
            {
                if(node->left)
                {
                    return findNearest(node->left, morton);
                }
            }
            else if(morton > node->morton)
            {
                if(node->right)
                {
                    return findNearest(node->right, morton);
                }
            }

            return node;
        }
Exemple #3
0
void NodeImporter::importSubmarineCableEdgesWaypoints() {
    std::unique_ptr<SubmarineCable> sc(new SubmarineCable(_dbFilename));

    while (sc->hasNext()) {
        SubmarineCableEdge edge = sc->getNext();
        if (edge.coord1 == edge.coord2)
            continue;

        GeographicNode_Ptr n1(new SeaCableNode(_nodenumber, edge.coord1.first, edge.coord1.second));
        ++_nodenumber;
        // find nearest node
        GeographicNode_Ptr nearestNode = findNearest(n1);

        SeaCableLandingPoint* slp = dynamic_cast<SeaCableLandingPoint*>(nearestNode.get());
        CityNode* cnp = dynamic_cast<CityNode*>(nearestNode.get());

        GeographicNode_Ptr nnP(new GeographicNode(*nearestNode));
        double dist = GeometricHelpers::sphericalDist(n1, nnP);
        if (!((slp || (cnp && cnp->isSeaCableLandingPoint())) && dist < NodeImporter::DIST_TRESHOLD))
            addNode(n1);
        else {
            auto rtn = _fallbackProjection.insert(std::make_pair(edge.coord1, nearestNode->coord()));
            assert(rtn.second == false || _fallbackProjection.at(edge.coord1) == nearestNode->coord());
        }

        GeographicNode_Ptr n2(new SeaCableNode(_nodenumber, edge.coord2.first, edge.coord2.second));
        ++_nodenumber;
        // find nearest node
        nearestNode = findNearest(n2);
        slp = dynamic_cast<SeaCableLandingPoint*>(nearestNode.get());
        cnp = dynamic_cast<CityNode*>(nearestNode.get());
        nnP = GeographicNode_Ptr(new GeographicNode(*nearestNode));
        dist = GeometricHelpers::sphericalDist(n2, nnP);
        if (!((slp || (cnp && cnp->isSeaCableLandingPoint())) && dist < NodeImporter::DIST_TRESHOLD))
            addNode(n2);
        else {
            auto rtn = _fallbackProjection.insert(std::make_pair(edge.coord2, nearestNode->coord()));
            assert(rtn.second == false || _fallbackProjection.at(edge.coord2) == nearestNode->coord());
        }
    }
}
void Nrand1DEPopulation::mutate(const int idx)
{
	int nearest=findNearest(idx,0,0,4);
	vector<int>a(this->m_popsize);
	Global::msp_global->initializeRandomArray<vector<int>>(a,this->m_popsize);
    int j=0;
    while(a[j]!=idx){j++;}
    int r1,r2;
    r1=a[(j+1)%this->m_popsize];
    r2=a[(j+2)%this->m_popsize];
	this->m_pop[idx]->mutate(m_F,&this->m_pop[nearest]->self(),&this->m_pop[r1]->self(),&this->m_pop[r2]->self());
}
Exemple #5
0
void Foam::searchableSphere::findNearest
(
    const pointField& samples,
    const scalarField& nearestDistSqr,
    List<pointIndexHit>& info
) const
{
    info.setSize(samples.size());

    forAll(samples, i)
    {
        info[i] = findNearest(samples[i], nearestDistSqr[i]);
    }
Exemple #6
0
int main(int argc, char* argv[]) {
	auto pNodeFactory = new NodeFactory();
	auto pKDTree = new KDTree(pNodeFactory);
	auto pPoint1 = new Point(1.2, 2.4);
	auto pPoint2 = new Point(1.3,4.3);
	auto pPoint3 = new Point(1.1, 6.2);
	auto pPoint4 = new Point(1.1,2.3);
	pKDTree->add(pPoint1);
	pKDTree->add(pPoint2);
	pKDTree->add(pPoint3);
	Point* pResult = pKDTree->findNearest(pPoint4);
	std::cout << pResult->getX() << ", " << pResult->getY() << std::endl;
	return 0;
}
Exemple #7
0
 Int MSSpectrum::findNearest(MSSpectrum::CoordinateType mz, MSSpectrum::CoordinateType tolerance) const
 {
   if (ContainerType::empty()) return -1;
   Size i = findNearest(mz);
   const double found_mz = this->operator[](i).getMZ();
   if (found_mz >= mz - tolerance && found_mz <= mz + tolerance)
   {
     return static_cast<Int>(i);
   }
   else
   {
     return -1;
   }
 }
bool ccIndexedTransformationBuffer::getInterpolatedTransformation(	double index,
																	ccIndexedTransformation& trans,
																	double maxIndexDistForInterpolation/*=DBL_MAX*/) const
{
	const ccIndexedTransformation *t1 = nullptr;
	const ccIndexedTransformation *t2 = nullptr;

	if (!findNearest(index, t1, t2))
		return false;

	if (t1)
	{
		double i1 = t1->getIndex();
		if (i1 == index)
		{
			trans = *t1;
		}
		else
		{
			assert(i1 < index);
			if (i1 + maxIndexDistForInterpolation < index) //trans1 is too far
				return false;

			if (t2)
			{
				double i2 = t2->getIndex();
				if (i2 - maxIndexDistForInterpolation > index) //trans2 is too far
					return false;

				//interpolate
				trans = ccIndexedTransformation::Interpolate(index, *t1, *t2);
			}
			else
			{
				//we don't interpolate outside of the buffer 'interval'
				return false;
			}
		}
	}
	else if (t2)
	{
		if (t2->getIndex() != index) //trans2 is too far
			return false;

		trans = *t2;
	}

	return true;
}
Exemple #9
0
int main()
{
  // A list of points.
  struct Point ptList[ PT_LIMIT ];

  // Read all the points
  int len = readPoints( ptList );

  // find the closest pair.
  struct Pair pair = findNearest( ptList, len );
  
  // Report it.
  printf( "%s and %s are closest\n", ptList[ pair.a ].name, ptList[ pair.b ].name );

  return 0;
}
Exemple #10
0
  Int MSSpectrum::findNearest(MSSpectrum::CoordinateType mz, MSSpectrum::CoordinateType tolerance_left,
                              MSSpectrum::CoordinateType tolerance_right) const
  {
    if (ContainerType::empty()) return -1;

    // do a binary search for nearest peak first
    Size i = findNearest(mz);

    const double nearest_mz = this->operator[](i).getMZ();

    if (nearest_mz < mz)
    {
      if (nearest_mz >= mz - tolerance_left)
      {
        return i; // success: nearest peak is in left tolerance window
      }
      else
      {
        if (i == this->size() - 1) return -1; // we are at the last peak which is too far left
        // Nearest peak is too far left so there can't be a closer peak in the left window.
        // There still might be a peak to the right of mz that falls in the right window
        ++i;  // now we are at a peak exactly on or to the right of mz
        const double next_mz = this->operator[](i).getMZ();
        if (next_mz <= mz + tolerance_right) return i;
      }
    }
    else
    {
      if (nearest_mz <= mz + tolerance_right)
      {
        return i; // success: nearest peak is in right tolerance window
      }
      else
      {
        if (i == 0) return -1; // we are at the first peak which is too far right
        --i;  // now we are at a peak exactly on or to the right of mz
        const double next_mz = this->operator[](i).getMZ();
        if (next_mz >= mz - tolerance_left) return i;
      }
    }

    // neither in the left nor the right tolerance window
    return -1;
  }
Exemple #11
0
void NodeImporter::importSeacableLandingPoints() {
    // add submarine cable landingpoints
    std::unique_ptr<LandingPointReader> lpr(new LandingPointReader(_dbFilename));

    while (lpr->hasNext()) {
        SeaCableLandingPoint next = lpr->getNext();
        next.setId(_nodenumber);
        ++_nodenumber;
        GeographicNode_Ptr lp(new SeaCableLandingPoint(next));

        // find nearest node
        GeographicNode_Ptr nnP = findNearest(lp);
        double dist = GeometricHelpers::sphericalDist(lp, nnP);
        if (dist > NodeImporter::DIST_TRESHOLD)
            addNode(lp);
        else {
            CityNode* cnp = dynamic_cast<CityNode*>(nnP.get());
            if (cnp)
                cnp->setSeaCableLandingPoint();
        }
    }
}
void Logstalgia::logic(float t, float dt) {

    float sdt = dt * settings.simulation_speed;

    //increment clock
    elapsed_time += sdt;
    currtime = starttime + (long)(elapsed_time);
   
    if(settings.stop_time && currtime > settings.stop_time) {
        currtime = settings.stop_time;
    }
    
    if(mousehide_timeout>0.0f) {
        mousehide_timeout -= dt;
        if(mousehide_timeout<0.0f) {
            SDL_ShowCursor(false);
        }
    }

    infowindow.hide();

    if(end_reached && balls.empty()) {
        appFinished = true;
        return;
    }

    //if paused, dont move anything, only check what is under mouse
    if(paused) {

        for(auto& it: paddles) {
            Paddle* paddle = it.second;

            if(paddle->mouseOver(infowindow, mousepos)) {
                break;
            }
        }

        for(RequestBall* ball : balls) {
            if(ball->mouseOver(infowindow, mousepos)) {
                break;
            }
        }

        if(!ipSummarizer->mouseOver(infowindow,mousepos)) {
            for(Summarizer* s: summarizers) {
                if(s->mouseOver(infowindow, mousepos)) break;
            }
        }

        return;
    }

    //next will fast forward clock to the time of the next entry,
    //if the next entry is in the future
    if(next || (!settings.disable_auto_skip && balls.empty())) {
        if(!queued_entries.empty()) {
            LogEntry* le = queued_entries.front();

            long entrytime = le->timestamp;
            if(entrytime > currtime) {
                elapsed_time = entrytime - starttime;
                currtime = starttime + (long)(elapsed_time);
            }
        }
        next = false;
    }

    //recalc spawn speed each second by
    if(currtime != lasttime) {

        //dont bother reading the log if we dont need to
        if(queued_entries.empty() || queued_entries.back()->timestamp <= currtime) {
            readLog();
        }

        profile_start("determine new entries");

        int items_to_spawn=0;

        for(LogEntry* le : queued_entries) {

            if(le->timestamp > currtime) break;

            items_to_spawn++;

            addStrings(le);
        }

        profile_stop();

        //debugLog("items to spawn %d\n", items_to_spawn);

        if(items_to_spawn > 0) {

            profile_start("add new strings");

            //re-summarize
            ipSummarizer->summarize();

            for(Summarizer* s : summarizers) {
                s->summarize();
            }

            profile_stop();

            profile_start("add new entries");

            float item_offset = 1.0 / (float) (items_to_spawn);

            int item_no = 0;

            while(!queued_entries.empty()) {

                LogEntry* le = queued_entries.front();

                if(le->timestamp > currtime) break;

                float pos_offset   = item_offset * (float) item_no++;
                float start_offset = std::min(1.0f, pos_offset);

		addBall(le, start_offset);

                queued_entries.pop_front();
            }

        }

        //update date
        if(total_entries>0) {
            char datestr[256];
            char timestr[256];

            struct tm* timeinfo = localtime ( &currtime );
            strftime(datestr, 256, "%A, %B %d, %Y", timeinfo);
            strftime(timestr, 256, "%X", timeinfo);

            displaydate = datestr;
            displaytime = timestr;
        } else {
            displaydate = "";
            displaytime = "";
        }

        lasttime=currtime;

        profile_stop();
    } else {
        //do small reads per frame if we havent buffered the next second
        if(queued_entries.empty() || queued_entries.back()->timestamp <= currtime+1) {
            readLog(50);
        }
    }

    std::list<Paddle*> inactivePaddles;

    //update paddles
    for(auto& it: paddles) {

        std::string paddle_token = it.first;
        Paddle*           paddle = it.second;

        if(settings.paddle_mode > PADDLE_SINGLE && !paddle->moving() && !paddle->visible()) {

            bool token_match = false;

            //are there any requests that will match this paddle?
            for(RequestBall* ball : balls) {

                if(   (settings.paddle_mode == PADDLE_VHOST && ball->le->vhost == paddle_token)
                   || (settings.paddle_mode == PADDLE_PID   && ball->le->pid   == paddle_token)) {
                    token_match = true;
                    break;
                }
            }

            //mark this paddle for deletion, continue
            if(!token_match) {
                inactivePaddles.push_back(paddle);
                continue;
            }
        }

        // find nearest ball to this paddle
        if( (retarget || !paddle->getTarget())) {

            RequestBall* ball = findNearest(paddle, paddle_token);

            if(ball != 0) {
                paddle->setTarget(ball);
            } else if(!paddle->moving()) {
                paddle->setTarget(0);
            }
        }

        paddle->logic(sdt);
    }

    retarget = false;

    profile_start("check ball status");

    // NOTE: special handling for this iterator as items are being removed
    for(auto it = balls.begin(); it != balls.end();) {

        RequestBall* ball = *it;

        highscore += ball->logic(sdt);

        if(ball->isFinished()) {
            it = balls.erase(it);
            removeBall(ball);
        } else {
            it++;
        }
    }

    profile_stop();

    profile_start("ipSummarizer logic");
    ipSummarizer->logic(dt);
    profile_stop();

    profile_start("updateGroups logic");
    updateGroups(dt);
    profile_stop();


    screen_blank_elapsed += dt;

    if(screen_blank_elapsed-screen_blank_interval > screen_blank_period)
        screen_blank_elapsed = 0.0f;

    //update font alpha
    font_alpha = 1.0f;

    if(screen_blank_elapsed>screen_blank_interval) {
        font_alpha = std::min(1.0f, (float) fabs(1.0f - (screen_blank_elapsed-screen_blank_interval)/(screen_blank_period*0.5)));
        font_alpha *= font_alpha;
    }
}
Exemple #13
0
void NodeImporter::importSubmarineCableEdges(BaseTopology_Ptr base_topo) {
    // add submarine cables waypoints
    std::unique_ptr<SubmarineCable> sc(new SubmarineCable(_dbFilename));

    unsigned int skipped = 0;

    int lastLinkID = -1;
    GeographicPositionTuple posFirst;
    GeographicPositionTuple posLast;
    std::vector<GeographicNode_Ptr> edgePositions;

    while (sc->hasNext()) {
        SubmarineCableEdge edge = sc->getNext();

        if (edge.coord1 == edge.coord2) {
            ++skipped;
            continue;
        }

        if(edge.linkID != lastLinkID) {
            for(GeographicNode_Ptr n1 : edgePositions) {
                bool n1OK = fabs(fabs(n1->lon()) - 180.0) < 1.0;

                for(GeographicNode_Ptr n2 : edgePositions) {
                    if(n1 == n2 || n2->id() < n1->id())
                        continue;

                    bool n2OK = fabs(fabs(n2->lon()) - 180.0) < 1.0;

                    if(n1OK && n2OK && GeometricHelpers::sphericalDistToKM(GeometricHelpers::sphericalDist(n1, n2)) < 4) {
                        Graph::Node u;
                        Graph::Node v;

                        u = base_topo->getGraph()->nodeFromId(n1->id());
                        v = base_topo->getGraph()->nodeFromId(n2->id());

                        if(lemon::findEdge(*base_topo->getGraph(), u, v) != lemon::INVALID)
                            continue;

                        GeographicEdge_Ptr edge_ptr(new SeaCableEdge);
                        assert(u != v);
                        base_topo->addEdge(u, v, edge_ptr);
                        BOOST_LOG_TRIVIAL(info) << "Add extra edge on link:" << edge.linkID << " (" << n1->id() << "," << n2->id() << ")";
                    }
                }
            }
            edgePositions.clear();
            lastLinkID = edge.linkID;
        }

        GeographicPositionTuple c1 = std::make_pair(edge.coord1.first, edge.coord1.second);
        GeographicPositionTuple c2 = std::make_pair(edge.coord2.first, edge.coord2.second);

        if (_fallbackProjection.find(c1) != _fallbackProjection.end())
            c1 = _fallbackProjection.at(c1);
        if (_fallbackProjection.find(c2) != _fallbackProjection.end())
            c2 = _fallbackProjection.at(c2);
        if (c1 == c2) {
            ++skipped;
            continue;
        }

        GeographicNode_Ptr c1N(new GeographicNode(500, edge.coord1.first, edge.coord1.second));
        GeographicNode_Ptr c2N(new GeographicNode(500, edge.coord2.first, edge.coord2.second));

        GeographicNode_Ptr n1 = findNearest(c1N);
        GeographicNode_Ptr n2 = findNearest(c2N);

        edgePositions.push_back(n1);
        edgePositions.push_back(n2);

        Graph::Node u;
        Graph::Node v;

        u = base_topo->getGraph()->nodeFromId(n1->id());
        v = base_topo->getGraph()->nodeFromId(n2->id());

        GeographicEdge_Ptr edge_ptr(new SeaCableEdge);
        assert(u != v);
        base_topo->addEdge(u, v, edge_ptr);
    }

    BOOST_LOG_TRIVIAL(info) << "SubmarineCables: Skipped " << skipped
                            << " edge entries due to mapping to same Coordinate or invalid database info.";
}
Exemple #14
0
        void BVHSceneTree::insertObject(SceneObject* object)
        {
            if(object)
            {
                const uint64_t morton = Math::MortonCode::calculate(object->getBoundsAABB(false).getCenter());

                BVHSceneNode* newLeafNode = new BVHSceneNode();
                newLeafNode->morton = morton;
                newLeafNode->object = object;
                newLeafNode->type   = SceneNodeType::Leaf;


                if(m_AllObjects.size() < 2)
                {
                    //----------------------------------------------------
                    // Insert into the root

                    if(m_Root == nullptr)
                    {
                        m_Root = new BVHSceneNode();
                        m_Root->type = SceneNodeType::Root;
                    }

                    newLeafNode->parent = m_Root;

                    if(m_Root->left == nullptr)
                    {
                        m_Root->left = newLeafNode;
                    }
                    else
                    {
                        if(m_Root->left->morton < morton)
                        {
                            m_Root->right = newLeafNode;
                        }
                        else
                        {
                            m_Root->right = m_Root->left;
                            m_Root->left = newLeafNode;
                        }
                    }
                }
                else
                {
                    //----------------------------------------------------
                    // Insert into an arbitrary node

                    // Get the nearest leaf node
                    BVHSceneNode* nearestLeafNode = findNearest(m_Root, morton);
                    BVHSceneNode* nearestParent = dynamic_cast<BVHSceneNode*>(nearestLeafNode->parent);

                    // Insert our new leaf into the internal parent of the one we just found.
                    // The parent will already have two children. So we will need to create
                    // a new internal node as three children can not belong to a single parent.

                    BVHSceneNode* newInternalNode = new BVHSceneNode();
                    newInternalNode->type = SceneNodeType::Internal;
                    newInternalNode->parent = nearestParent;

                    // One of the three children will remain direct descendents of the parent,
                    // the other two children will move to be descendents of the new internal.

                    // The left-most child (smallest morton code) will remain as the direct descendent (left).
                    // The other two, will move to the new internal and place in order of their morton value.

                    if(newLeafNode->morton <= nearestParent->left->morton)
                    {
                        newInternalNode->left = nearestParent->left;
                        newInternalNode->right = nearestParent->right;

                        nearestParent->left = newLeafNode;
                    }
                    else if(newLeafNode->morton <= nearestParent->right->morton)
                    {
                        newInternalNode->left = newLeafNode;
                        newInternalNode->right = nearestParent->right;
                    }
                    else
                    {
                        newInternalNode->left = nearestParent->right;
                        newInternalNode->right = newLeafNode;
                    }

                    nearestParent->right = newInternalNode;

                    // Refit the morton codes

                    newInternalNode->morton = (newInternalNode->left->morton + newInternalNode->right->morton) / 2;
                    nearestParent->morton = (nearestParent->left->morton + nearestParent->right->morton) / 2;

                    // Bounds are fit by the caller method. No need to do so here.
                }
            }
        }