在 C++ 中查找序列的基周期

Find base period of sequence in C++

For a sequence of numbers a1, a2,...,an, we say that there is a period if 1≤p<n and if it holds that it is ai=ai+p for all values for which this equality makes sense.

For example, the sequence of numbers 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 has period 5, because ai=ai+5 for all values such that both indices i and i+5 are within the allowable range (i.e. for 1 to 7 inclusive). The same sequence also has a period of 10. Next, we say that the sequence of numbers is periodic if it exists at least one number that is the period of that sequence, with the smallest such number being called the base sequence period. If such a number does not exist, the sequence is not periodic. For example, the above the sequence of numbers is periodic with the base period 5, while the sequence of numbers 4, 5, 1, 7, 1, 5 is not periodic.

#include <iostream>
#include <vector>

int period(std::vector<double> vektor) {
  int p;
  for (int i : vektor) {
    for (int j : vektor) {
      if (vektor[i] == vektor[j])
        p = j;
    }
  }
  return p;
}

int main() {
  std::vector<double> vektor{1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3};
  std::cout << period(vektor);
  return 0;
}

你能帮我修复这段代码吗?这个returns3作为序列的基期

对于初学者来说,当所有初始值设定项都具有 int.[=19= 类型时,您不清楚为什么使用值类型为 double 而不是类型 int 的向量]

函数 period 应通过常量引用接受向量。

变量p没有初始化。因此,该函数可以 return 一个不确定的值。

基于范围的 for 循环并不像您想象的那样 return 在容器中建立索引

for (int i : vektor) {

它return存储在双精度类型的矢量对象中。

所以if语句中的条件

if (vektor[i] == vektor[j])

没有意义。

函数可以像下面的演示程序所示那样。

#include <iostream>
#include <vector>

size_t period( const std::vector<double> &v )
{
    size_t p = 0;

    for (size_t i = 1; !p && i < v.size(); i++)
    {
        size_t j = 0;

        while (j < v.size() - i && v[j] == v[j + i]) ++j;

        if ( j + i == v.size() ) p = i;
    }

    return p;
}

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

程序输出为

5