Thread: memory game
View Single Post
Join Date: Sep 2004
Posts: 7,742
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 739
Team Colleague
Narue's Avatar
Narue Narue is online now Online
Code Goddess

Re: memory game

 
0
  #4
Nov 20th, 2008
So you want to populate the board with random numbers in the range of [0, 18) and disallow more than two of a kind? I'd say use a frequency table for the range since it's small, and repeat getting the random number until you find one that doesn't go beyond the limit:
  1. #include <cstdlib>
  2. #include <iomanip>
  3. #include <iostream>
  4.  
  5. int main()
  6. {
  7. using namespace std;
  8.  
  9. int board[6][6];
  10. int freq[18] = {0};
  11.  
  12. for ( int i = 0; i < 6; i++ ) {
  13. for ( int j = 0; j < 6; j++ ) {
  14. int r;
  15.  
  16. do
  17. r = rand() % 18;
  18. while ( freq[r] >= 2 );
  19.  
  20. ++freq[r];
  21. board[i][j] = r;
  22. }
  23. }
  24.  
  25. for ( int i = 0; i < 6; i++ ) {
  26. for ( int j = 0; j < 6; j++ )
  27. cout<< left << setw ( 3 ) << board[i][j];
  28. cout<<'\n';
  29. }
  30. }
The frequency table holds a count of all of the values in your range.
I'm here to prove you wrong.
Reply With Quote