2

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.

#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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

2 Answers2

0

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You could try checking your answer in rotations of modulo(%) period, as in the smallest period, which in this case is 5.

juhikushwah
  • 33
  • 1
  • 8