Codiqo

Learn C++ · lesson 53 of 61 · about 11 minutes

Project: All the Orderings

List every way to arrange some letters, by choosing one letter and arranging the rest.

What you'll learn

  • Build answers up as the recursion goes deeper
  • Try every choice at each step
  • Avoid repeating choices that were already used

Planning the route

Before the last part of the adventure, the hero plans a route through the rooms still to explore. The player types the rooms until done, and the adventure lists every order to visit them, like hall > tower > vault, then how many routes there are. That's the orderings problem below with rooms instead of letters: routes tries each room next, recurses on the rooms that are left, and prints a route when none are left. More than 4 rooms would mean too many routes to read, so the adventure says so.

The idea

How many ways can you arrange the letters abc? There are 6: abc, acb, bac, bca, cab and cba.

Recursion finds them all. To arrange some letters:
1. Pick each letter in turn to go first
2. Arrange the remaining letters after it, recursively
3. When no letters remain, one full arrangement is ready to print

Every ordering

#include <iostream>
#include <string>

void orderings(const std::string& done, const std::string& left) {
    if (left.empty()) {
        std::cout << done << "\n";
        return;
    }
    for (std::size_t i = 0; i < left.size(); i++) {
        std::string rest = left.substr(0, i) + left.substr(i + 1);
        orderings(done + left[i], rest);
    }
}

int main() {
    orderings("", "abc");
}

Output

abc
acb
bac
bca
cab
cba

Counting them

With n letters there are n choices for the first, n - 1 for the next, and so on: n × (n - 1) × ... × 1, which is n factorial. That grows fast: 10 letters already have 3,628,800 orderings.

Just counting

#include <iostream>

long long count_orderings(int n) {
    if (n <= 1) return 1;
    return n * count_orderings(n - 1);
}

int main() {
    std::cout << count_orderings(3) << " " << count_orderings(10) << "\n";
}

Output

6 3628800

Counting through a reference

The route planner counts the routes as it prints them. Every call needs to add to the same count, so routes takes it as int& routeCount: a reference to the one variable in main. Without the &, each call would get its own copy, and the count in main would stay 0.

One counter shared by every call

#include <iostream>

void countDown(int n, int& calls) {
    calls++;
    if (n > 0) countDown(n - 1, calls);
}

int main() {
    int calls = 0;
    countDown(4, calls);
    std::cout << calls << " calls\n";
}

Output

5 calls

Tip

This style, where each call tries every choice and recurses on what's left, is called backtracking. It also solves puzzles like Sudoku.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.