Commit 4f43db76 by Andrew Dahl

Solved Problem 24

parent 9d709178
Showing with 61 additions and 0 deletions
Question:
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
Answer: 2783915460
#include <iostream>
#include <list>
#include <string>
using namespace std;
const int GOAL = 1000000;
const int NUM = 10;
int fact(int num) {
for(int i = num - 1; i > 1; i--)
num *= i;
return num;
}
int main() {
int int_list[] = {0,1,2,3,4,5,6,7,8,9};
list<int> numbers (int_list,int_list+10);
list<int>::iterator it;
int left = GOAL;
int turn;
int count;
int last = NUM;
string final = "";
while(numbers.size() > 1) {
turn = 0;
for(count = 1; count < last; count++)
if(fact(count+1) >= left) {
last = count;
break;
}
turn = left/fact(count);
if(left % fact(count) == 0)
turn--;
left -= turn*fact(count);
it = numbers.begin();
for(int i = 0; i <= turn && it != numbers.end(); i++) {
if(i == turn) {
final += ((char)*it + 48);
numbers.remove(*it);
}
it++;
}
}
final += ((char)*numbers.begin() + 48);
cout << final << endl;
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment