Data Structure and algorithm simulation algorithm C ++ implementation, data structure and algorithm Algorithm
Simulation Algorithm: simulates the entire process. By changing the parameters of the model in mathematics, you can observe the changes in the process state caused by these parameters.
Algorithm concept: use random functions to simulate unpredictable situations in nature. (Srand () and rand () functions generate random numbers)
The simulation algorithm completes the entire process, and the program runs as described in the question. Example 1: The computer that guesses the number generates a random integer of 1-. The user guesses that each guess gives a different prompt. Code:
# Include <iostream> # include <stdlib. h> # include <time. h> using namespace std; int main () {srand (time (NULL); int count = 0; int num = rand () % 100 + 1; int guess; cout <"Enter the predicted value:"; cin> guess; do {if (guess> num) {count ++; cout <"the value you guessed is greater than \ n"; cout <"Enter the predicted value again:"; cin> guess;} else if (guess <num) {count ++; cout <"Your guess is less than \ n"; cout <"Enter the predicted value again:"; cin >>> guess ;}} while (guess! = Num); count ++; cout <"guessed it! \ N "; cout <" guessed "<count <" Times \ n "; return 0 ;}
Running result:
Example 2: in a simulated dice game, the user enters the number of participants and the number of dice. Then, the computer randomly generates the points of each dice and counts the points of each dice.
Code:
# Include <iostream> # include <stdlib. h> # include <time. h> using namespace std; void play (int n) {int I, m = 0, t = 0; for (I = 0; I <n; I ++) {t = rand () % 6 + 1; m + = t; cout <"no." <(I + 1) <"Number of dice:" <t <"\ n" ;}cout <"Total" <m <"Point \ n ";} int main () {int people, numbers; do {srand (time (NULL); cout <"Enter the number of participants:"; cin> people; if (people = 0) break; cout <"Enter the number of dice:"; cin> numbers; if (numbers = 0) break; for (int I = 0; I <people; I ++) {cout <"no." <(I + 1) <"the dice thrown by a player is: \ n "; play (numbers) ;}} while (1); return 0 ;}
Running result:
Note:
Use of C ++ to generate random numbers
1) provide a seed for srand (), which is an unsigned int type;
2) call rand (), which returns a random number (between 0 and RAND_MAX) based on the seed value provided to srand );
3) call rand () multiple times as needed to continuously obtain new random numbers;
4) at any time, srand () can be provided with a new seed to further "randomize" the output results of rand.
General expression formula for generating random numbers within a certain range
To obtain a random integer of [a, B), use (rand () % (B-a) +;
To obtain a random integer of [a, B], use (rand () % (B-a + 1) +;
To obtain a random INTEGER (a, B], use (rand () % (B-a) + a + 1;
General Formula: a + rand () % n; where a is the starting value and n is the Integer Range.