Judgment and circulation - Practical ending 1 (dichotomy, coin tossing, etc.)

catalogue

1. Leading expression

2. Find the factorial of n:  

3. Find the sum of factorials of 1 ~ 10

4. Find a specific number in an ordered array (dichotomy)

5. Demonstrate that multiple characters converge from both ends to the middle

6. Coin tossing game

Supplement:   Setting of random number

1. Leading expression

  Resolution:

      Calculate the expression result first, that is, judge the logic result of i==1 first. The result is true and output in% d format. The true expression is 1 and output.

      Examination: priority calculation of expressions

2. Find the factorial of n:  

  Your current level is enough to control the code. I won't explain it in detail:

Function encapsulation:

 

3. Find the sum of factorials of 1 ~ 10

In the last question, we wrote the function of finding n factorials. Finding the sum of factorials is just adding the factorials each time

Resolution:  

        Because we have written a function to find the factorial of n, requiring the sum of several factorials is nothing more than calling the factorial function many times and adding the obtained numbers.

        So now the problem to deal with is, how to call the function repeatedly? Obviously, we need a loop to make multiple calls to the function. So how do we sum after the call? Our supplementary function AddFact is the function implementation of calling and summing functions.

        Enter an n value to calculate the factorial sum from 1 to N. of course, you can change the conditions in the for loop to achieve the factorial sum of some numbers you want.   After entering the for loop, execute the statement and assign the values of num and MyFact(i) to num. since you want the return value of MyFact, you naturally need to call this function first. Because i enters the loop for the first time as 1, you call MyFact (1) and return the factorial of 1, so num=1! (because num is initialized to 0 and omitted directly), the next cycle i becomes 2, call MyFact (2) and return the factorial of 2. Therefore, assign num after the first assignment and the factorial of 2 to num. at this time, num=1+ 2!, By analogy, we will finally find the factorial sum of 1 ~ 10.

        The first function is only responsible for finding the factorial of n, and the second function is responsible for further processing. We call this processing method program modularization (convenient for later modification and maintenance). To use a function, we need to define a function to realize the function, but we can't use it directly without defining it. We call it process oriented.

      If we want to change the function, such as finding the factorial difference of several numbers, we just need to change the second function to subtraction.

    

4. Find a specific number in an ordered array (dichotomy)

        If we find out whether the number 9 exists in the array, it is obvious that 9 does exist, but if there are 10000 numbers and 10 million numbers in the array, can we see it with our eyes (brother toutie, please put down your claws (manual funny)), but the computer can easily find it. How to implement this program?

        The first method (Mei's method): we can enumerate violently and directly compare the number we are looking for with the number in the array one by one. Yes or no, but obviously, this method is relatively inefficient. After all, the number you are looking for may be the first ten million elements. Let's explain the second method here.

        The second method (half search method / half search method): we have specified that the array is an ordered array, and we only discuss the ordered array at this time. Here we take ascending order as an example.

        For example, if we want to find the number 9, we directly let 9 follow the middle element of the array (or slightly deviate. In an even array, it is generally one element to the left or right). If 9 is smaller than the middle element, because it is arranged in ascending order, the middle element must be smaller than all the elements behind the middle element, and 9 is smaller than the middle element, Note 9 is definitely not in the second half of the array, so it is either in the first half of the array or does not exist. Therefore, we only need to find in the first half of the array next time and throw away the second half directly, which greatly improves the efficiency. By analogy, we only need to compare with the middle elements in the remaining numbers, We call this dichotomy.

The implementation is shown in the figure below (with detailed notes)

//Use dichotomy to find specific numbers in an ordered array
#pragma warning(disable:4996)
#include<stdio.h>
int Find(int arr[], int who, int size)//We need to know the number to find, the original array, and the size of the array
{
    int left = 0;//left is defined as the leftmost subscript of the search range, that is, the subscript of the 0th element
    int right = size - 1;//right is defined as the rightmost subscript of the search range, that is, the subscript of the last element
    //Because the subscript of the first element is 0, the subscript of the last element is size-1
    while (left <= right)//When left==right, it means that there is only one number left in the search range, which may be the number to be searched, so you can take etc. if the number is still not the number to be searched, it means that there is no such number in the array
    {
        int mid = (left + right) / 2;//Because we need to use the subscript of the intermediate element, we define it here
        if (who > arr[mid])
        {
            //If the element to be found is larger than the middle element, you only need to find the right half of the array
            left = mid;//Assign the subscript of the intermediate element to left, that is, the leftmost range of the next search starts from mid.
            left++;//Because we have compared who and mid, we no longer need to start with mid, so we start with mid+1 element
        }
        else if (who < arr[mid])
        {
            //If the element to be found is smaller than the middle element, you only need to find the left half of the array
            right = mid;//Assign the subscript of the intermediate element to left, that is, the rightmost range of the next search starts from mid.
            right--;//Because we have compared who and mid, we no longer need to start with mid, so we start with mid-1 elements
        }
        else//Description who==arr[mid], that is, the number has been found
        {
            return mid;//Returns the subscript of the element
        }
    }
    return -1;//From the while loop, it indicates the number of lookups in the array and returns a negative value
}
int main()
{
    int arr[10] = { 1,5,7,9,15,25,43,56,65,70 };//Ascending array
    int size = sizeof(arr) / sizeof(arr[0]);//Calculate the total space occupied by the array
    int who;//who is the number we want to find
    scanf("%d", &who);
    int sub = Find(arr, who, size);//The Find function is a function that implements the binary search function
    //sub is the return value of the function, and the return value is the subscript
    if (sub >= 0)//If the return value of the array is non negative, it indicates that the number exists
    {
        printf("The number exists, and its subscript in the array is %d\n", sub);
    }
    else//The return value is negative, indicating that the number does not exist
    {
        printf("The number does not exist\n");
    }
    return 0;
}

(note that the code block can slide. Don't think you can't see it, hhh)

be careful:

      For Int type division, when defining mid, we use int mid=(left+right)/2. We talked about the '/' operator in the operator section, which is the rounding principle of zero term, that is, 8 / 2 = 4,7 / 2 = 3, - 7 / 2 = - 3

5. Demonstrate that multiple characters converge from both ends to the middle

Such as the example demonstration of hello     

        h####o

        he##lo

         hello

The implementation is shown in the figure below:

//Demonstrate that multiple characters converge from both ends to the middle

#pragma warning(disable:4996)

#include<stdio.h>

#include<windows.h>

int main()

{

//You need a string first

char arr1[] = "hello world! nice to meet you!!";

char arr2[] = "###############################";

//Because it converges from both ends to the middle, we need subscripts at both ends

int left = 0;

int right = strlen(arr2) - 1;

   //Strlen calculates the length of the string, so strlen-1 is the subscript of the last element

while(left <= right)

{

arr2[left] = arr1[left];

arr2[right] = arr1[right];

printf("%s\r", arr2);

left++;

right--;

Sleep(1000);

}

return 0;

}



be careful:

one   Here we use strlen to find the length of the string. However, it is also possible to use sizeof to find the opening space, but because the end flag of the string is' / 0 'by default, the size calculated by sizeof also includes the size of' / 0 ', so the size of the space calculated by sizeof is 1 more than the length calculated by strlen, and - 2 can be used as the subscript

two   ‘/ r 'we said in the escape that the cursor returns to the beginning of the line. If you continue to output, the previous content will be overwritten. Because the number of words is the same every time, the code will be overwritten every time.

3. The sleep function (s is in uppercase) needs to refer to the header file window.s to pause. The pause unit is milliseconds (1s = 1000ms)

6. Coin tossing game

//Coin tossing game

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

int main()

{

srand((unsigned long)time(NULL));

//Used to set random numbers

int a[2] = { 0 };

//Create an array with two int type elements. The two elements in the array represent the number of positive and negative respectively

for (int i = 0; i < 100; i++)//Number of random throws

{

a[rand () % 2]++;

//If the result of a random number remaining 2 must be 0 or 1, this line of code means that a random element in the array + 1, that is, the front and back sides are random + 1

}

printf("Up : %d\nDown : %d\n", a[0], a[1]);

//Up refers to the front; Down means the reverse

return 0;

}

Supplement:   Setting of random number

  The setting function of random number is rand, and the required header file is stdlib.h. It is used to generate a random number, but the generation of the random number is sequential. The generation of rand random number will first fix the starting point of a random number (called seed) (each number represents the order of a random number), and then generate a random number. When the starting point remains unchanged, The order of the generated random numbers is also unchanged.

    This is the result of the first run. Now after I rerun:

 

      Look!

      Both runs have the same random number, so this is not the real random number we want.

  (note that the analysis can be analyzed if there is a foundation. Don't mind Xiaobai. Just remember the writing method of random value)

        If we want the random value to change constantly, we must let its random starting point (seed) change constantly, so that the random order will also change constantly, and naturally it will become a real random number. What is used as the seed of rand? We need something that is constantly changing. Obviously, time is constantly changing, so we introduce time (NULL). A pointer should have been placed in time(). We don't consider others (just remember), just stay empty,

        time (NULL) returns the number of seconds from 0:00 midnight on New Year's day, 1970 to the present.

          Because the current time is constantly changing, the return value of time (NULL) is constantly changing. Therefore, we can take time (NULL) as the seed of rand (). How can we set the seed? Here we need to introduce another function srand (), which is used to set a seed.

        However, the type requirement in srand () is unsigned long int (int can be omitted), while the return value type of time (NULL) is a long integer, and the type does not match. Therefore, we need to use forced type conversion

          Writing (unsigned long) time (null) means that the return value type of time () is forcibly converted to the unsigned long type. Therefore, the complete setting of random value seed is srand((unsigned)   long)time(NULL));

After setting, rand is a real random number

After the random number is set, we can simulate the random front and back of coins falling

      Well, that's all for this article. Practice is the essence of programming. I believe that if you understand the above code principles, you will gain a little (uncertain little expression)!

        In the next article, we will explain a small practical project (guessing numbers game)

      Look! Programming is not very difficult (hold your head), and it's still very interesting. After learning so much, we can write our own games! See you next!

      If you have doubts, just leave a comment. I will often read it, and others can help solve them. Come on, everybody!

Tags: C Back-end

Posted on Wed, 17 Nov 2021 10:15:35 -0500 by syd