Advertisement
joric

arbitrary_pos.cpp

Feb 25th, 2017
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. // convert integer to an arbitrary position system
  2. // enumerate/generate password dictionary in lexicographic order
  3.  
  4. #include <iostream>
  5. #include <string.h>
  6. #include <algorithm>
  7. using namespace std;
  8.  
  9. char* conv(int x, char* dict, char* buf, int alpha=0) {
  10.     int i = 0;
  11.     int n = strlen(dict);
  12.     if (alpha) x++;
  13.     do {
  14.         if (alpha) x--;
  15.         buf[i++] = dict[x % n];
  16.         x /= n;
  17.     } while (x);
  18.     buf[i] = 0;
  19.     reverse(buf, buf+i);
  20.     return buf;
  21. }
  22.  
  23. int rconv(char * buf, char * dict, int alpha=0) {
  24.     int i = 0;
  25.     int n = strlen(dict);
  26.     int k = strlen(buf);
  27.     int x = 0;
  28.     int pos = 1;
  29.     if (alpha) x--;
  30.     for (int i=k-1; i>=0; i--) {
  31.         int index = strchr(dict, buf[i])-dict;
  32.         if (alpha) index++;
  33.         x += index*pos;
  34.         pos *= n;
  35.     }
  36.     return x;
  37. }
  38.  
  39. int main() {
  40.     char dict[] = "abc";
  41.     char buf1[256];
  42.     char buf2[256];
  43.     for (int i=0; i<20; i++) {
  44.         conv(i, dict, buf1, 0);
  45.         conv(i, dict, buf2, 1);
  46.         int x = rconv(buf1, dict, 0);
  47.         int y = rconv(buf2, dict, 1);
  48.         cout << i << "\t"
  49.             << buf1 << "\t" << x << "\t"
  50.             << buf2 << "\t" << y << "\t" << endl;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement