Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- http://www.careercup.com/question?id=14942777
- From the set of natural integer numbers
- Let x = 1234 = {1, 2, 3, 4}
- Let y = 2410 = {2, 4, 1, 0}
- Write an algorithm to compute the rearrangement of x that is closest to y but still greater than y. Both x and y have the same number of digits.
- So in the example above, the answer would be { 2, 4, 1, 3 } = 2413 which is greater than y = 2410 and closer than any other arrangements of x.
- */
- typedef std::vector<int> vec;
- typedef std::unordered_map<int,int> hashtable;
- typedef std::set<int> intset;
- hashtable from_vec(const vec & x)
- {
- hashtable ret;
- for(size_t i = 0; i < x.size(); ++i)
- {
- ++ret[x[i]];
- }
- return ret;
- }
- vec from_table(const hashtable & ht, const int v)
- {
- vec ret;
- hashtable::iterator it = ht.begin();
- for(; it != ht.end(); ++it)
- {
- if(it->second > 0) { ret.push_back(it->first); }
- }
- return ret;
- }
- // finds a vector of digits from x that as a number is greater than y
- vec slightly_greater(const vec & y, const vec & x)
- {
- vec ret;
- hashtable Xh = from_vec(x);
- hashtable::iterator it, end = X.end();
- const size_t L = y.size();
- size_t i;
- // first find all equal digits
- for(i = 0; i < L; ++i)
- {
- it = Xh.find(y[i]);
- if(it == end || it->second == 0) { break; }
- ret.push_back(y[i]);
- --it->second;
- }
- // find smallest digit D greater than y[i]
- size_t pos = size_t(-1);
- vec remain = from_hashtable(Xh);
- sort(remain.begin(), remain.end());
- for(size_t k = 0; k < remain.size(); ++k)
- {
- if( remain[k] > y[i])
- {
- pos = k;
- ret.push_back(remain[k]);
- break;
- }
- }
- // D not found -> x is no valid
- if(pos == size_t(-1)) { error(); }
- for(k = 0; k < remain.size(); ++k)
- {
- if( k != pos) { ret.push_back(remain[k]); }
- }
- return ret;
- }
Advertisement
Add Comment
Please, Sign In to add comment