Skip to main content
GameDev.net gamedev.net
🔒 Locked

rand puzzle

Started by Cafall Oct 21, 2000 at 9:24 AM 3 replies 350+ views
Original Post
Cafall
Cafall
Hey I'm making a little puzzle game, I need to get 6 random numbers, there can't be more then 2 of the same number, there are 4 different numbers that you can get, and you can't get 0, this is what I'm doing now: while(number == 0) number = rand()%5 but that sometimes give the same number more than 2 times.. How can i limit it to 2? Edited by - cafall on 10/21/00 9:25:50 AM
acw83
acw83
You could always write your own rand function, or if you use the standard one you could check the result using a bunch of if statements to see if two are already taken. Also, are you seeding the random number generator with different values each time you start your program?
TV
TV
That was me up there. I hit back, and that takes away my password... grr...
Well, at least this post won''t look like I am just trying to increase rank.

- Travois
Stoffel
Stoffel
Another algorithm idea:
Keep an array of number/frequency pairs. The number part is the actual number (1 through 4 in your case), and the frequency is how many times it''s been picked. If a number is picked twice, swap it with the last legal element in the array, then only look up to the end-1. This should give you a good general solution that isn''t hard_coded:
(some pseudo-code here, don''t try to compile. )
    
pair<int, int> num_array[4]; // first = num, second = freq

// initialize num_array, probably could be put in function
for (int i=0; i<4; i++)
num_array<i>.first = i+1;

// note: pair constructor sets num_array[i].second to 0

// set up loop variables

int max_idx = 4; // 1-based max legal index (using mod, so 1-based)
int nums_to_pick = 6;
const int max_of_same_num = 2;
vector rand_numbers; // list of numbers to build

while (max_idx && nums_to_pick)
{
int idx = rand () % max_id; // get random index

rand_numbers.push_back (num_array [idx].first); // add to list

if (--nums_to_pick == 0)
continue; // done picking numbers

num_array[idx].second++; // record number as being picked

if (num_array[idx].seocnd == max_of_same_num)
{
// got X of same number, need to swap out entries
// can decrease max_id first since it''s 1-based and index

// is zero-based

max_id--;
swap (num_array[idx], num_array[max_id];
}
}

if (!max_id && nums_to_pick)
cout << "ERROR: can''t pick that many numbers without at least "
<< max_of_same_num << "of each number" << endl;
}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.