我决定编写输出 Collatz 树的代码。那可能必须等待另一个问题;当前的问题是:
我们只想计算给定数字的 Collatz 序列一次,然后使用 memoization。这就是我希望在我的代码中实现的:
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
int collatzize(int x)
{
x % 2 == 0 ? x /= 2 : x = 3 * x + 1;
return x;
}
map<int, vector<int>> collatz_tree;
void tree_fill(int n)
{
vector<int> chain;
chain.resize(n);
chain[0] = n;
int tmp = n;
int counter = 1;
while (tmp != 1)
{
if (collatz_tree.find(tmp) != collatz_tree.end())
//something
tmp = collatzize(tmp);
chain[counter] = tmp;
counter++;
}
int x = 0;
chain.erase(remove_if(chain.begin(), chain.end(), [x] (int thing) {return thing == x; }), chain.end());
collatz_tree.emplace(make_pair(n, chain));
}
int output(int a)
{
for (auto it = collatz_tree[a].begin(); it != collatz_tree[a].end(); it++)
cout << *it << "\n" << "|" << "\n";
return 0;
}
int main()
{
int num;
cin >> num;
for (int i = 2; i < num; i++)
tree_fill(i);
output(num);
return 0;
}
这个想法是这样的:对于给定的数字,计算序列,检查每一步我们是否已经达到了一个我们已经知道序列的数字。如果我们有,那么只需将相应的向量附加到当前向量。
例子:
我们应该早点得到{5, {5,16,8,4,2,1}}
。所以,当我们计算一个序列时,比如说,13,我们应该做{13, {13,40,20,10, paste_vector_for_5_here}}
.
问题是:考虑到整个 collatz 树是作为 ? 实现的,最好的方法是什么map<int, vector<int>>
?
附言
我的 lambda 很笨拙:我对它们还不是很好。