How to generate all unique 2-digit permutations from a given 3-digit number in C++

1 Answer

0 votes
#include <iostream>
#include <unordered_set>
#include <string>

std::unordered_set<std::string> generate_2_digit_permutations_from_3_digit_number(const std::string& threeDigitNumber) {
    std::unordered_set<std::string> twoDigitPermutations;
    
    // Generate all two_digit_permutations of three_digit_number
    for (size_t i = 0; i < threeDigitNumber.length(); i++) {
        for (size_t j = 0; j < threeDigitNumber.length(); j++) {
            if (i != j) {
                twoDigitPermutations.insert(std::string(1, threeDigitNumber[i]) + std::string(1, threeDigitNumber[j]));
            }
        }
    }
    
    return twoDigitPermutations;
}

int main() {
    std::string threeDigitNumber = "185";
    
    std::unordered_set<std::string> twoDigitPermutations = generate_2_digit_permutations_from_3_digit_number(threeDigitNumber);
    
    for (const auto& permutation : twoDigitPermutations) {
        std::cout << permutation << " ";
    }
    std::cout << std::endl;
}



/*
run:

58 51 85 81 15 18 

*/

 



answered Jun 16, 2024 by avibootz
...