C language basic algorithm collection

1. Combination of stamps

        A person has four 3-cent stamps and three 5-cent stamps. How many different postage rates can be obtained with one or more of these stamps?

Algorithm idea:    

        To analyze the problem mathematically, the postage of stamps with different numbers and denominations can be calculated by the following formula:

        S = 3 * i + 4 *j

Where i is the number of 3-cent stamps, j is the number of 5-cent stamps.

        According to the requirements of the topic, 0, 1, 2, 3, and 4 stamps can be taken for 3-point stamps, and 0, 1, 2, and 3 stamps can be taken for 5-point stamps. Combining by adopting the exhaustive method, the postage after the combination of these stamps with different denominations and different numbers can be calculated.

int a[27];

int main(){
    int i,j,k,s,n=0;
    for(i=0;i<=4;i++){
        for(j=0;j<=3;j++){
            s=i*3 + j*5;
            for(k=0;a[k];k++){
                if(s == a[k])break;
            }
            if(!a[k] && s){a[k]=s;n++;}
        }
    }
    printf("%d kinds:",n);
    for(k=0;a[k];k++)
        printf("%2d",a[k]);
}

2. Date conversion (array)

        Given a certain year, month and day, convert it to the day of the year and output it.

Algorithm idea:

        The algorithm is very simple. If the given month is i, then add up the number of days in each month of 1, 2, 3, ..., i-1, and add the specified day. But for leap year, the number of days in February is 29 days, so it is necessary to determine whether a given year is a leap year. In order to realize this algorithm, it is necessary to set a list of days in a month and give the number of days in each month, taking into account leap years and peace years In this case, this table can be set as a two-dimensional array with 2 rows and 13 columns, in which the elements of each row corresponding to the first row (columns 1 to 12 are valid) are the number of days in each month in an ordinary year, and the second row corresponds to the leap year The number of days in the month.

#include<stdio.h>

int day_of_year(day_tab,year,month,day){
    int day_tab[][13];
    int year,month,day;
    int i,j;
    //判定这闰年还是平年,i=0为平年,i=1为闰年
    i = (year%4 == 0 && year%100 != 0) || year%400 == 0;
    for(j=1;j<=month;j++){
        day += day_tab[i][j];
    }
    return day;
}

int main(){
    static int day_tab[2][13]={
        {0,31,28,31,30,31,30,31,31,30,31,30,31},
        {0,31,29,31,30,31,30,31,31,30,31,30,31}
    };
    int y,m,d;
    scanf("%d%d%d",&y,&m,&d);
    printf("%d\n",day_of_year(day_tab,y,m,d));
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_39312146/article/details/131712249