Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if number is period of sequence in C++

I need to check if number is a period of sequence.

EXAMPLE: { 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 }

Periods are 5 and 10. Base period is 5 because it is the smallest period.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>
#include <vector>
int p=0;
int period(std::vector<double>v , int x)
{
    int p = 0;
    for (int i = 1; !p && i < v.size(); i++)
    {
        int j = 0;
        while (j < v.size() - i && v[j] == v[j + i]) ++j;
        if ( j + i == v.size() ) p = i;
    }
    if(p!=x)
    return false;
    return true;
}

int main()
{
    std::vector<double> v = { 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 };
    std::cout << period( v,10 ) << '\n';
}

My code checks if number is equal to base period. How could I check if it is equal to any of the periods and in that case return true?

>Solution :

The function can be defined the following way

bool period( const std::vector<double> &v , size_t n )
{
    bool is_period = false;

    if ( n < v.size() )
    {
        size_t j = 0;
        while ( j < v.size() - n && v[j] == v[j + n]) ++j;
        is_period = j + n == v.size();
    }

    return is_period;
}

Here is a demonstration program.

#include <iostream>
#include <vector>

bool period( const std::vector<double> &v, size_t n )
{
    bool is_period = false;

    if (n < v.size())
    {
        size_t j = 0;
        while (j < v.size() - n && v[j] == v[j + n]) ++j;
        is_period = j + n == v.size();
    }

    return is_period;
}

int main()
{
    std::vector<double> v = { 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 };

    if (period( v, 5 )) std::cout << 5 << " is a period\n";
    if (period( v, 10 )) std::cout << 10 << " is a period\n";
}

The program output is

5 is a period
10 is a period
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading