runnig

Slightly greater

Jan 17th, 2013
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. /*
  2.  
  3. http://www.careercup.com/question?id=14942777
  4. From the set of natural integer numbers
  5. Let x = 1234 = {1, 2, 3, 4}
  6. Let y = 2410 = {2, 4, 1, 0}
  7.  
  8. 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.
  9.  
  10. 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.
  11.  
  12. */
  13.  
  14. typedef std::vector<int> vec;
  15. typedef std::unordered_map<int,int> hashtable;
  16. typedef std::set<int> intset;
  17.  
  18. hashtable from_vec(const vec & x)
  19. {
  20.     hashtable ret;
  21.     for(size_t i = 0; i < x.size(); ++i)
  22.     {
  23.         ++ret[x[i]];
  24.     }
  25.     return ret;
  26. }
  27.  
  28. vec from_table(const hashtable & ht, const int v)
  29. {  
  30.     vec ret;
  31.    
  32.     hashtable::iterator it = ht.begin();
  33.    
  34.     for(; it != ht.end(); ++it)
  35.     {
  36.         if(it->second > 0) { ret.push_back(it->first); }
  37.     }
  38.     return ret;
  39. }
  40.  
  41. // finds a vector of digits from x that as a number is greater than y
  42. vec slightly_greater(const vec & y, const vec & x)
  43. {
  44.     vec ret;
  45.    
  46.     hashtable Xh = from_vec(x);
  47.     hashtable::iterator it, end = X.end();
  48.        
  49.     const size_t L = y.size();
  50.     size_t i;
  51.    
  52.     // first find all equal digits
  53.     for(i = 0; i < L; ++i)
  54.     {
  55.         it = Xh.find(y[i]);
  56.         if(it == end || it->second == 0) { break; }    
  57.         ret.push_back(y[i]);
  58.         --it->second;      
  59.     }
  60.  
  61.     // find smallest digit D greater than y[i]
  62.    
  63.     size_t pos = size_t(-1);
  64.     vec remain = from_hashtable(Xh);
  65.     sort(remain.begin(), remain.end());
  66.    
  67.    
  68.     for(size_t k = 0; k < remain.size(); ++k)
  69.     {
  70.         if( remain[k] > y[i])
  71.         {
  72.             pos = k;
  73.             ret.push_back(remain[k]);
  74.             break;         
  75.         }
  76.     }
  77.    
  78.     // D not found -> x is no valid
  79.     if(pos == size_t(-1)) { error(); }
  80.  
  81.     for(k = 0; k < remain.size(); ++k)
  82.     {
  83.         if( k != pos) { ret.push_back(remain[k]); }
  84.     }
  85.    
  86.     return ret;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment