Finding minimum and maximum values of an unknown continuous loop

algorithm, c++, while-loop

Solution

If I understand correctly, you want to have the minimum and maximum for a given time frame. The solution you use keep the minimum and maximum since the beginning of the program.

Depending on your needs, you have several solutions: for instance, you can simply reset the min and max from time to time, like @dirkgently suggested. If you want a moving range, so that at any point in time you have the min and max of the `n` last measurements, then you will have to use a more complex solution. The only one I can think of is keeping the measurements in a FIFO container:

std::deque<int> lastRawXs;
const int frameSize = 100; // only keep the last 100 measures    

while (true)
{
    // Keeps generating new RawX,Y and Z values
    Function(&RawX, &RawY, &RawZ);// 

    if (lastRawXs.size() >= frameSize)
    {
        lastRawXs.pop_front();
    }
    lastRawXs.push_back(RawX);

    typedef std::deque<int>::const_iterator iterator;
    std::pair<iterator, iterator> minMaxRawX =
        boost::minmax_element(lastRawXs.begin(), lastRawXs.end());

    Output("MinRawX:%0.2f", *minMaxRawX.first);
    Output("MaxRawX:%0.2f", *minMaxRawX.second);
}

Edit: Here is an alternative (better) solution using a circular buffer:

const int frameSize = 100;
std::circular_buffer<int> lastRawXs(frameSize);

while (true)
{
    Function(&RawX, &RawY, &RawZ); // keeps generating new RawX,Y and Z values

    lastRawXs.push_back(RawX); // overwrites old measures if buffer is full

    typedef std::circular_buffer<int>::const_iterator iterator;
    std::pair<iterator, iterator> minMaxRawX =
        boost::minmax_element(lastRawXs.begin(), lastRawXs.end());

    Output("MinRawX:%0.2f", *minMaxRawX.first);
    Output("MaxRawX:%0.2f", *minMaxRawX.second);
}

Problem

I am trying to find the minimum and maximum values for the continuous while loop given below, but somehow I am unable to get the logic right. Kindly let me know where I am going wrong. ``` while (true) { Function(&RawX, &RawY, &RawZ);// Keeps generating new RawX,Y and Z values if(MaxRawX < RawX) MaxRawX = RawX; if(MinRawX > RawX) MinRawX = RawX; Output("MaxRawX:%0.2f",MaxRawX); } ``` The problem that I am facing with the above algorithm is that the values of RawX, RawY and RawZ are continuously changing. For eg: at one point, I have values ranging from -46 to -35. I want my program to display MinRawX as -46 and MaxRawX as -35. At some other point, I might have values in between 201 to 215, where I want it to display MaxRawX as 215 and MinRawX as 201. Its basically some sensor angle data I receive from my hardware. I am sure I am doing something wrong here considering this being very basic but can't figure it out. Any suggestions?

Original source