00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026 #include "RandomLib/Random.hpp"
00027 #include <iostream>
00028 #include <iomanip>
00029 #include <sstream>
00030 #include <vector>
00031
00032 #define RANDOMPERMUTATION_CPP "$Id: RandomPermutation.cpp 6490 2008-11-10 21:53:54Z ckarney $";
00033 RCSID_DECL(RANDOMPERMUTATION_CPP);
00034
00035 void usage(const std::string name, int retval) {
00036 ( retval == 0 ? std::cout : std::cerr )
00037 << "Usage: " << name
00038 << " [-o] [-d] [-x] [-s seed] [-v] [-h] [num]\n\
00039 \n\
00040 Print a random permutation of numbers from 0 thru num-1\n\
00041 on standard output. num is supplied on the command line\n\
00042 as a decimal number (default is 100). Optional arguments\n\
00043 -o, -d, and -x selection octal, decimal, and hexadecimal\n\
00044 output base (default decimal). -s seed sets the seed.\n\
00045 -v prints seed on standard error. -h prints this help.\n";
00046 exit(retval);
00047 }
00048
00049 int main(int argc, char* argv[]) {
00050 try{
00051 unsigned n = 100;
00052 unsigned base = 10;
00053 bool verbose = false;
00054 bool seedgiven = false;
00055 std::string seed;
00056 std::string arg;
00057 int m = 0;
00058 while (++m < argc) {
00059 arg = std::string(argv[m]);
00060 if (arg[0] != '-')
00061 break;
00062 if (arg == "-o")
00063 base = 8;
00064 else if (arg == "-d")
00065 base = 10;
00066 else if (arg == "-x")
00067 base = 16;
00068 else if (arg == "-v")
00069 verbose = true;
00070 else if (arg == "-s") {
00071 seedgiven = true;
00072 if (++m == argc)
00073 usage(argv[0], 1);
00074 seed = std::string(argv[m]);
00075 } else if (arg == "-h")
00076 usage(argv[0], 0);
00077 else
00078 usage(argv[0], 1);
00079 }
00080 if (m == argc - 1) {
00081 std::istringstream str(arg);
00082 str >> n;
00083 } else if (m != argc)
00084 usage(argv[0], 1);
00085
00086 unsigned k = 0;
00087 for (unsigned i = n - 1; i; i /= base) k++;
00088
00089 std::vector<unsigned> a(n);
00090 for (unsigned i = n; i--;) a[i] = i;
00091
00092 RandomLib::Random r = seedgiven ? RandomLib::Random(seed) :
00093 RandomLib::Random(RandomLib::Random::SeedVector());
00094 if (verbose)
00095 std::cerr << "Seed: " << r.SeedString() << "\n";
00096 std::random_shuffle(a.begin(), a.end(), r);
00097
00098 std::cout << std::setfill('0')
00099 << (base == 16 ? std::hex : (base == 8 ? std::oct : std::dec));
00100 for (unsigned i = n; i--;)
00101 std::cout << std::setw(k) << a[i] << "\n";
00102
00103 return 0;
00104 }
00105 catch (...) {
00106 std::cerr << "Unexpected error" << "\n";
00107 }
00108 }