Sunday, July 12, 2009

What is the most efficient method for my program in C++?

I need to have the computer decide on a pair of numbers for position coordinates. The numbers that make up the coordinates are limited to 0,1, 2. Example:





(0,1), (1,1),(0,2) ..... (1,2)





In case the coordinate has already been used once, I can not reuse that coordinate.





I was thinking about using a random number generator with a modulus like this





x = rand()%3 and y = rand()%3





That would create random coordinates. However if the coordinate was already used, I would have to refer back to random and get new random coordinates. If that is used, I would have to refer back to it again.





By my method, I would have to refer back to random quite a few times in worst case scenario so is there a better more efficient way.





P.S. To tell the truth, this is a tic-tac-toe program.

What is the most efficient method for my program in C++?
You could Have an array that starts out with all 9 positions, choose one at random, then remove it from the list and choose from the smaller list the next time.
Reply:Ken H's suggestion is good. In fact, since it's for Tic-Tac-Toe, why not do this:





char board[3][3];





And use that as the board? The random # generator is problematic, because technically it might never finish, although it probably would eventually.
Reply:All other answers are better, but you could also try precalculated lists.





You can also program some analysis instead of randomly play. For example, 1st turn: try the center, 2nd turn: try center edge, 3rd turn: check if I have to block, check if I wasn't blocked, etc. Kinda easier if you play against yourself in paper and write down what you are thinking.





To make it more human, instead of doing something, assign a percent or possibility to each decision. Kinda like, block=90%, play here = 75%, etc. So, the desicion routine will block, if it has to, 90% of the times.
Reply:Ken H idea is cool.


Also you could choose random numbers, then save it into an array, then with a for and a if statment, check if you've used the number or not. it's simple, but it's more coding
Reply:If you just want to march through the whole thing, you could...





- Create a list/set of all 9 coordinates


- rand() % 9, select and remove that coordinate.


- rand() % 8, select from remaining 8 coordinates and remove


- rand() % 7, select from remaining 7 coordinates and remove


etc. until you have 1 coordinate left.





With this method, you're rand()'ing on a collection of only possible values, with no chance of collision. Since the loop is a known size, you can "unroll" it to eliminate branches (old-school optimizations). The coordinates that you extract can then be saved to another list of "guesses."


No comments:

Post a Comment