如何从具有最大值的序列中找到起始编号

How do I find the starting number from the sequence with the Max Value

在我的代码中,我从头到尾计算了 运行ge 的 Collaz 序列。我 运行 代码和所有内容都正确打印,除了具有最大值的序列的起始元素。我调试并看到我的最大值是正确的,但是我最终打印了具有最大值的序列起始编号的末尾。我尝试重置 i 我也尝试查看我的 if 语句是否有问题

理想情况下,一旦正确,它应该看起来像这样 示例程序:

开始:1

结束:6

最大值:16 (3)

这是我的代码

int main()
{
  // This declare the int start and end and prints them to the user as well as takes what the user gives 
  int start, end;
  std::cout << "Start: ";
  std::cin >> start;
  std::cout << "End: ";
  std::cin >> end;

  // Here a vector called sequences is created. This holds a Collatz Sequences
  std::vector<CollatzSequence> sequences;
  int i = start;
  while (i <= end)
  {
    sequences.push_back(CollatzSequence(i));
    i = i + 1;
  }

  {
    // A vector is made to hold the collatz sequences
    std::vector<int> maxValues;
    i = 0;
    while (i < sequences.size())
    {
      maxValues.push_back(sequences[i].getMax());
      i = i + 1;
    }
    // Here this declares varibles as intagers
    int max = maxValues[0];
    int maxIndex = 0;
    {
      // The i (index) is declare as  integer
      int i = 1;
      // While i is less then the size of the vector maxValues
      while (i < maxValues.size())
      {
        // If true (the element at maxValue is greater then the max)
        if (maxValues[i] > max)
          // max value will be that element
          max = maxValues[i];
          // maxIndex will be the idex at maxValue or address
          maxIndex = maxValues[i];
        // i is then incremented which mean it will go through the sequence at each address
        i = i + 1;
      }
      std::cout << "Max Value: " << max << " (" << sequences[maxIndex].getStart() << ")\n";
    }
  }

这里是我定义函数的地方

CollatzSequence::CollatzSequence(int start)
 int CollatzSequence::getMax()
{
  int max = getNumbers()[0];
  {
    for (int i = 1; i < getNumbers()[i]; i++)
      if (getNumbers()[i] > max)
        max = getNumbers()[i];
  }
  return max;
}
int CollatzSequence::getStart()
{
  int start = getNumbers()[0];
  return start;
}


std::vector<int> const & CollatzSequence::getNumbers()
{
  return numbers;
}

如果您看到错误但我没有看到或者我做错了什么,请告诉我。我尝试只 post 需要什么而不是 post 4 个文件。谢谢你的时间。

我猜你现在自己解决了这个问题。但无论如何,让我们回答这个问题,这样它就不会成为 0 个答案。

错误在那一行:

// maxIndex will be the idex at maxValue or address
maxIndex = maxValues[i];

你存储的不是索引,而是值。这可能是一个很大的价值,因此超出了范围。

正确的解法是:

// maxIndex will be the idex at maxValue or address
maxIndex = i;

应该可以。

为了好玩,我使用算法库创建了 "more-modern-C++" 个元素的解决方案。请看:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

// Collatz Sequence and its max value
struct CollatzSequence {

    CollatzSequence() {}

    // This will construct the collatez sequence and calculate the max value
    explicit CollatzSequence(unsigned int value); 

    // Values of the Collatz Sequence
    std::vector<unsigned int> data{};

    // The maximum value of all values of the Collatz sequence
    unsigned int maxValue{ 1U };
};

// Constructor for the Collatz Sequence. Will calculate all values of the sequence and the maxim value
CollatzSequence::CollatzSequence(unsigned int value) {

    // We calculate values as long as we did not find 1, always the last vale 
    // (There is no mathematicla evidence that this is always true)
    while (value > 1U) {

        // Store the current calculated value
        data.push_back(value);

        // Check, if this is the biggest value so far, and, if so, store it
        maxValue = std::max(value, maxValue);

        // Calculate next value in the row according to the Collatz Sequence rules
        value = ((value & 1U) == 0) ? (value >> 1U) : (3U * value + 1U);
    }
    // Always add 1 as the last element. This we do not need to calculate
    data.push_back(1U);
}

int main() {

    // Inform user to enter start end end value
    std::cout << "Calculate Collatz sequences. Please specify a range, a start and a end value:\n";

    // Read the start value and check, if this worked
    if (unsigned int rangeStart{}; std::cin >> rangeStart) {

        // Now read end value and check, if a correct range has been specified
        if (unsigned int rangeEnd{}; (std::cin >> rangeEnd) && rangeStart <= rangeEnd) {

            // Create a vector for Collatz Sequences. Allocate sufficent elements for the specified range
            std::vector<CollatzSequence> sequences(rangeEnd - rangeStart + 1);

            // Create all requested sequences
            std::generate(sequences.begin(), sequences.end(), [i = rangeStart]()mutable { return CollatzSequence(i++); });

            // Get the max element 
            std::vector<CollatzSequence>::iterator mve = max_element(sequences.begin(), sequences.end(),
                [](const CollatzSequence& cs1, const CollatzSequence& cs2) { return cs1.maxValue < cs2.maxValue; });

            // Show result to the world
            std::cout << "Max Value: " << mve->maxValue << " (" << mve->data[0] << ")\n";
        }
        else {
            std::cerr << "\n*** Error: Invalid range specified\n";
        }
    }
    else {
        std::cerr << "\n*** Error: Could not get start value for range\n ";
    }
    return 0;
}