All about flooble | fun stuff | Get a free chatterbox | Free JavaScript | Avatars
 perplexus dot info

 9 random digits (Posted on 2003-05-02)
Suppose you want to make a random 9 digit number, using every number from 1 to 9 exactly once. You have a process called random(top) that gives a random number up to top (if top was 5, it would give random numbers from 1 to 5)

a) How could you do this?

b) If top couldn't be more than 9, how could you do this using random(top) only 9 times (or less)?

 See The Solution Submitted by Gamer Rating: 3.4000 (5 votes)

Comments: ( Back to comment list | You must be logged in to post comments.)
 C++ solution | Comment 5 of 20 |

struct MyRand {
typedef std::vector<int>::difference_type DType;

DType operator()(DType max) {
return random(max) - 1;
}
};

int foo() {
std::vector<int> digits;

for (int i = 1; i <= 9; ++i)
digits.push_back(i);

MyRand myRand;
std::random_shuffle(digits.begin(), digits.end(), myRand);

int result(0);

for (int i = 0; i < 9; ++i)
result = result * 10 + digits[i];

return result;
}
 Posted by friedlinguini on 2003-05-02 10:28:52

 Search: Search body:
Forums (0)