0
#include <iostream>
#include <cmath>
#include <numeric>
#include <vector>
#include <algorithm>

bool isPointWithinSphere(std::vector<int> point, const double &radius) {

    std::transform(point.begin(), point.end(), point.begin(), [](auto &x)    {return std::pow(x,2);});

    return std::sqrt(std::accumulate(point.begin(), point.end() + 1, 0,     std::plus<int>())) <= radius;   
}


int countLatticePoints(std::vector<int> &point, const double &radius, const     int &dimension, int count = 0) {


     for(int i = -(static_cast<int>(std::floor(radius))); i <= static_cast<int>(std::floor(radius)); i++) {
        point.push_back(i);

        if(point.size() == dimension){
            if(isPointWithinSphere(point, radius)) count++;
        }else count = countLatticePoints(point, radius, dimension, count);

        point.pop_back();
    }

    return count;
}

MAIN

int main() {
std::vector<int> vec {};
std::cout << countLatticePoints(vec, 2.05, 2) << std::endl;
std::cout << countLatticePoints(vec, 1.5, 3) << std::endl;
std::cout << countLatticePoints(vec, 25.5, 1) << std::endl;
std::cout << countLatticePoints(vec, 2.05, 2) << std::endl;
}

The above program run returns the following results:

13
19
51
 9

I'm trying to understand why my first function call using the same input parameters returns 13 (correct answer) as the result, yet when I call the function again at a later time with the same exact input arguments, I get 9 as the answer ?

Can't think of any reason this should happen.

1 Answer 1

2

std::accumulate works from [first, last). This means it does not include last, so that it is easy to read an entire collection. You dont want to use point.end() + 1 as that means it will try to process point.end().

Doing so means you are reading outside of the vector boundaries and causes undefined behavior.

Change the line to

return std::sqrt(std::accumulate(point.begin(), point.end(), 0,     std::plus<int>())) <= radius;   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.