0

Ive decided to write code that'd output a Collatz tree. That'd probably have to wait for another question; the current question is this:

We want to calculate the Collatz sequence for a given number only once, and then use memoization. That's what I wish to implement in my code:

#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;
}

The idea is this: for a given number, calculate the sequence, checking every step whether we've reached a number that we already know the sequence for. If we have, then just append the respective vector to the current vector.

Example:

Early on we should get {5, {5,16,8,4,2,1}}. So, when we calculate a sequence for, say, 13, we should do {13, {13,40,20,10, paste_vector_for_5_here}}.

The question is: what is the best way to do this, considering that the whole collatz tree is implemented as a map<int, vector<int>> ?

P.S.

My lambda is clumsy: I'm not very good with them yet.

Chiffa
  • 1,486
  • 2
  • 19
  • 38
  • Writing code like your `collatzize` function will not make you any friends. Will you self be able to understand it at a quick glance in a couple of months time? – Some programmer dude Nov 05 '14 at 09:31
  • 1) It's a quick and dirty solution; 2) At the moment it's for my eyes only. Whenever this code turns into something beautiful I intend it to be, I will probably put comments everywhere they need to be. – Chiffa Nov 05 '14 at 09:33

0 Answers0