Reputation: 4681
I have a relatively small std::unordered_map<char, int>
of only 8 characters. However, I would like to iterate through them and set each character to a value 0-9.
The chars are d, e, m, n, o, r, s, y
.
I COULD do something along the lines of:
std::unordered_map<char, int> letters;
for(int d = 0; d < 10; ++d)
for(int e = 0; e < 10; ++e)
for(int m = 0; m < 10; ++m)
// continued
letters['d'] = d; // etc...
But this does not seem prudent at all, and becomes more and more tedious as the letter count increases. There must be a better way of doing this.
Upvotes: 0
Views: 110
Reputation: 4265
If i got you right, you want to iterate through every possible combination, how the values 0-9 can be assigned to 8 letters.
In this case a nice property of our numbers comes to mind: we use a decimal system. So you are looking for ever number with 8 digits and then pair every digit with a letter:
00000000 - 99999999
|||||||| ||||||||
demnorsy demnorsy
Of course you can do the same with other numbers of digits, but its very easy to see the idea in decimal.
So the easy way is:
std::unordered_map<char, int> letters;
std::vector<char> chars= {'d', 'e', 'm', 'n', 'o', 'r', 's', 'y'};
for (int N=0; N<pow(10,chars.size()); ++N){
for(int i=0; i<chars.size();++i)
letters[chars[i]] = (N/pow(10,i))%10; //integer division
//whatever you want to do with your permutation, do it here
}
Upvotes: 2