Search code examples
qtc++11hash

What was the name of this algorithm the recursive algorithm?


It is necessary to build all combinations for value keys:

INPUT:

data["key1"] = {"value1", "value2", "value3"};
data["key2"] = {"value4", "value5"};
data["key3"] = {"value6"};

OUTPUT:

"value1"   "value4"   "value6"
"value1"   "value5"   "value6"
"value2"   "value4"   "value6"
"value2"   "value5"   "value6"
"value3"   "value4"   "value6"
"value3"   "value5"   "value6

"

For this I have a recursive function, a recursive combination. What was the name of this algorithm that was used there?

#include <QMap>
#include <QList>
#include <QString>
#include <QDebug>

typedef QMap<QString, QList<QString>> SubPluralsShema;

void recursiveCombination(const SubPluralsShema& data, QStringList currentCombination, const QStringList& keys, int keyIndex) {
    if (keyIndex == keys.size()) {
        for (const QString& value : currentCombination) {
            qDebug() << value << " ";
        }
        qDebug() << "\n";
        return;
    }

    const QString& key = keys[keyIndex];
    const QList<QString>& values = data[key];

    for (const QString& value : values) {
        currentCombination.append(value);
        recursiveCombination(data, currentCombination, keys, keyIndex + 1);
        currentCombination.removeLast();
    }
}

int main() {
    SubPluralsShema data;

    // Fill the data structure for the example
    data["key1"] = {"value1", "value2", "value3"};
    data["key2"] = {"value4", "value5"};
    data["key3"] = {"value6"};

    QStringList keys = {"key1", "key2", "key3"};
    QStringList currentCombination;

    recursiveCombination(data, currentCombination, keys, 0);

    return 0;
}

I don't understate why it code: "currentCombination.removeLast();"


Solution

  • First just focus on the for-loop of the top-level call of recursiveCombination() (keyIndex=0):

    • It adds value1 to the list.
    • Calls the recursiveCombination() with keyIndex=1 and pass the currentCombination by value, therefore your local currentCombination will hold only value1 at returning.
    • Now your next iteration wants to deal with value2, therefore you need to remove value1 from the list.

    In general, the loop adds a value from the current list (data[keys[keyIndex]]) to currentCombination and calls recursiveCombination() to deal with the rest of the keys. Before it starts the next iteration of the loop, that value needs to be removed.