Week 9: array + pointer + string

Posted by jokullsolberg on Sat, 02 Oct 2021 00:29:09 +0200

1. Transpose of two-dimensional array matrix

Title:

Please write a function to transpose an integer matrix of m*n. Note: Please store the transposed data in the two-dimensional array before outputting the two-dimensional array. Three transposes are required using the following three functions:

void Transpose1(int a[][N], int at[][M], int m, int n);

void Transpose2(int (*a)[N], int (*at)[M], int m, int n); // Row pointer

void Transpose3(int *a, int *at, int m, int n); // Column pointer

[input form] matrix length, width and matrix element value
[output form] matrix after calling three functions to transpose
[sample input]

3 4

1 2 3 4

4 5 6 7

7 8 9 0

[sample output]

1 4 7

2 5 8

3 6 9

4 7 0

1 4 7

2 5 8

3 6 9

4 7 0

1 4 7

2 5 8

3 6 9

4 7 0

[friendly note] note that the third transpose method uses the total number of original rows and columns when calculating the number of rows and columns.

code:

#include <stdio.h>
#include <iostream>
using namespace std;

#define M 100
#define N 100

void Input (int a[M][N], int m, int n)
{
    for (int i = 0; i < m; i ++)
    {
        for (int j = 0; j < n; j ++)
        {
            scanf ("%d", &a[i][j]);
        }

    }
}

void Output (int at[M][N], int m, int n)
{
    printf ("\n");
    printf ("\n");
    for (int i = 0; i < m; i ++)
    {
        for (int j = 0; j < n; j ++)
        {
            printf ("%d ", at[i][j]);
        }
     printf ("\n");
    }

}

void Transpose1 (int a[][N], int at[][M], int m, int n)
{
    for (int i = 0; i < m; i ++)
    {
        for (int j = 0; j < n; j ++)
        {
            at[j][i] = a[i][j];
        }
    }
}

void Transpose2 (int (*a)[N], int (*at)[M], int m, int n)
{
    for (int i = 0; i < m; i ++)
    {
        for (int j = 0; j < n; j ++)
        {
            *(*(at + j) + i) = *(*(a + i) + j);
        }
    }
}

void Transpose3 (int *a, int *at, int m, int n)
{
    for (int i = 0; i < m; i ++)
    {
        for (int j = 0; j < n; j ++)
        {
            *(at + M * j + i) = *(a + N * i + j);
        }
    }
}

int main()
{
    int a[M][N];
    int at[N][M];
    int m, n;
    scanf("%d %d", &m, &n);
    Input(a, m, n);
    Transpose1(a, at, m, n);
    Transpose2(a, at, m, n);
    Transpose2(a, at, m, n);
    Output(at, n, m);
    Output(at, n, m);
    Output(at, n, m);
}

2. N-ary string representation of integer

Title:

Write the function itob(n,s,b) to convert the integer n into a string based on B and store it in S. Write a program, use the function itob(n,s,b) to convert the input integer n into the string s, and output s. The converted string is output from the highest non-zero bit. If n is a negative number, the first character of the output string is' - '. B is any natural value greater than 1 and less than 37. When b=2, the output characters can only be '0' and '1'; When b=16, the output string may contain characters' 0 '-' 9 ',' a '-' f '(the letters are output in lowercase).
[input form] the console inputs integers n and b, where n can be negative. N and b are separated by spaces
[output form] the console outputs the converted string s
[example input] 5 2
[sample output] 101
[example description] the binary of 5 is 101

code:

#include <iostream>
#include <cstring>
#define N 1000
using namespace std;

void itob(int n, char *s, int b)
{
    for(int i = 0; ; i ++)
    {
        if(n < 0)
        {
            n = -n;
        }
        int y = n % b;
        if(y <= 9)s[i] = y + '0'; //The output s[i] is the character corresponding to ASCII
        if(y > 9)s[i] = y - 10 + 'a';
        n = n / b;
        if(n == 0)
        {
            s[i + 1] = '\0';
            break;
        }
    }
}

int main()
{
    int n, b;
    cin >> n >> b;
    char s[N];
    itob(n, s, b);
    int len = strlen(s);
    if(n < 0) cout << '-';
    for(int i = len - 1; i >= 0; i --)
    {
        cout << s[i];
    }
    return 0;
}

3. Delete the same data in integers (one-dimensional array cyclic sorting)

Title:

First sort the data stored in the one-dimensional array from small to large (bubbling, selection, insertion and quick sorting), then delete the same data in the sequence, keep only one, and finally output the data in the array. Be sure to design your own functions to realize sorting function, deletion function, array element input and number statistics function, array element output function, etc.

Tip: when deleting, you can apply for another array to store the results, and use len to represent the new length.

for(i = sequential loop of subscripts of the original one-dimensional array, the original length is n)

{put a[i] into the new array b[len];len + +;

for(j = loop back from i+1)

{if a[j]!=a[i], jump out; otherwise, continue with i++,j + +}

}

[input form] some random data. Input - 1 represents the end of input

[output form] the result after deletion. Note: there is a space after the last data

[example input] 9 9 0 32 2 78 2 8 5 3 1 9 0 2 6 6 7 - 1

[example output] 0 1 2 3 5 6 7 8 9 32 78

code:

#include <stdio.h>
#define N 100

int Scanf(int num[])
{
    int i = 0;
    do{
    	scanf("%d", &num[i]);
    	i ++;
    }while(num[i - 1] != -1);
    return i - 1;
}

void DataSort(int num[], int n)
{
    int i, j, k, temp;
    for(i = 0; i < n - 1; i ++)
    {
        k = i;
        for(j = i + 1; j < n; j ++)
        {
            if(num[j] < num[k])
                k = j;
        }

        if(k != i)
        {
            temp = num[k];
            num[k] = num[i];
            num[i] = temp;
        }
    }
}

int Delete(int num[], int len)
{
    int i;
    for(i = 0; i < len; i ++)
    {
        if(num[i] == num[i + 1])
        {
            for(int j = i + 1; j < len; j ++)
            {
                num[j] = num[j + 1];

            }
        i --;
        len --;
        }
    }
	return len;
}

int Printf(int num[], int n)
{
    for(int i = 0; i < n; i ++)
    printf("%d ", num[i]);
}

int main()
{
    int num[N], x, y;
    x = Scanf(num);
    DataSort(num, x);
    y = Delete(num, x);
    Printf(num, y);
}

4. Maximum point of two-dimensional array

Title:

Find the "maximum point" of the two-dimensional integer array. The * * "maximum point" * * of the two-dimensional array is defined as: a number is the maximum value of the row and the column. Note: there may be multiple "maximum points" on a row or column.

Please design the function:

void Read(int *p, int m, int n); obtain the value of two-dimensional array data elements;

int MaxPoint(int (*p)[N], int m, int n, int *result); obtain the maximum point of the two-dimensional array and store the result in the two-dimensional array pointed to by result. The return value of the function represents the number of maximum points.

Two two-dimensional arrays are defined in the main function. One is used to store the original data of n rows and m columns, and the other is used to store the results of the maximum point. Each column represents the value of the maximum point, the row where the maximum point is located, and the column where the maximum point is located.

[input form]

Read in a two-dimensional array from the console.

The first row has only two positive integers n and M separated by spaces (n, m < = 10). N represents the number of rows of the two-dimensional array and M represents the number of columns of the two-dimensional array.

Then input the elements of the two-dimensional array on the subsequent n lines. Each line has m integers separated by several spaces, representing all the elements of the two-dimensional array on this line.

[output form]

Output the * maximum point * of the two-dimensional array to the console in the order of row subscript and column subscript from small to large. For each row, output the * * maximum point * * value first, and then output the corresponding number of rows and columns (rows and columns are counted from 1), separated by a space.

[sample input]

3 4

8 60 7 100

10 498 12 49

-71 132 4 85

[sample output]

100 1 4
498 2 2

[example description]

A two-dimensional array with three rows and four columns is input. The element 100 in the first row and the fourth column is the largest element in the first row and the largest element in the fourth column, so this element is the "maximum point" and output 100 1 4. Similarly, the element 498 in the second row and the second column is also the largest element in the second row and the largest element in the second column, so this element is also the "maximum point" , output 498 2.

code:

#include <iostream>
using namespace std;

#define N 100

void Read(int *p, int m, int n)
{
    int i, j;
    for(i = 0; i < m; i ++)
    {
        for(j = 0; j < n; j ++)
        {
            cin >> p[i * 100 + j];
        }
    }
}

int MaxPoint(int (*p)[N], int m, int n, int *result)
{
    int a = 0;
    for(int i = 0; i < m; i ++)
    {
        int maxnum = -999;
        int mj = 0;
        for(int j = 0; j < n; j ++)
        {
            if(*(*(p + i) + j) > maxnum)
            {
                maxnum = *(*(p + i) + j);
                mj = j;
                int z = 0;
                int k = 0;
                for(; k < m; k ++)
               {
                   if(*(*(p + k) + mj) <= *(*(p + i) + mj))
                         z ++;
                }
                if(z == k)
                {
                    int q = 0;
                    result[a * 3 + q] = *(*(p + i) + mj);
                    result[a * 3 + q + 1] = i;
                    result[a * 3 + q + 2] = mj;
                    a ++;
                }
            }
        }

    }
    return a;
}

void Output(int *p, int m)
{
    int i, j;
    for(i = 0; i < m; i ++)
    {
        for(j = 0; j < 3; j ++)
        {
            cout << p[i * 100 + j] << " ";
        }
        cout << endl;
    }
}

int main()
{
    int num[100][100], result[100][100];
    int m, n, x;
    cin >> m >> n;
    Read(*num, m, n);
    x = MaxPoint(num, m, n, *result);
    cout << x;
    Output(*result, x);
    return 0;
}

5. String problem

Title:

Please write a function to count the number of occurrences of the substring Substr in the parent string Str. the prototype of the function is as follows, and the return value is the number of occurrences:

int Count(char *Str, char *Substr);

[example description] the first line is the parent string and the second line is the substring

Number of occurrences of [sample input]

abcbcbc

bcb
[sample output]

2

code:

#include <stdio.h>
#include <string.h>

#define N 100

int Count(char *s, char *str)
{
    int k = 0;
    char *a ;
    char *b ;
    while(*s != '\0')
    {
       a = s;
       b = str;
       while(*a == *b && *a != '\0' && *b != '\0')
       {
           a ++;
           b ++;
       }
       if(*b == '\0')
       {
           k ++;
       }
           s ++;
    }
    return k;
}

int main()
{
    char Str[N], Substr[N];
    int x;
    gets(Str);
    gets(Substr);
    x = Count(Str, Substr);
    printf("%d", x);
    return 0;
}

6. Number in string

Title:

Enter a string containing numeric and non numeric characters. For example, a123x456 17960?302tab5876, store the consecutive numbers as an integer in an array a in turn. For example, 123 is stored in a[0], 456 is stored in a[1]... Count the total number of integers and output these integers. If the input string contains spaces, you can use cin.getline(str,30, '\ n') Receive string, where str is char str[50].

[sample input]

a123x456 17960?302tab5876

[sample output]

5

123 456 17960 302 5876

code:

#include <iostream>
using namespace std;

char str[50];

int main()
{
    cin.getline(str, 50);
    char* p = str;
    int sum = 0;
    int i = 0;
    int num = 0;
    for (i = 0; p[i] != '\0'; ++ i) 
    {
        if ((i - 1) >= 0 && (p[i] < '0' || p[i] > '9'))
        {
            if (p[i - 1] >= '0' && p[i - 1] <= '9')
                sum ++;
        }
    }
    if (p[i - 1] >= '0' && p[i - 1] <= '9')
        sum ++;
    cout << sum << " \n";
    int flag = 0;//Suppose it was a letter
    for (i = 0; p[i] != '\0'; ++ i)
    {
        if (p[i] >= '0' && p[i] <= '9')
        {
            if (flag == 0)
                flag = 1;
            if (p[i] == '0' && p[i + 1] == '0')
                ;
            else
                cout << p[i];

        }
        else 
        {
            if (flag == 0)
                ;
            else 
            {
                cout << " ";
                flag = 0;
            }
        }
    }
    return 0;
}

7. Student achievement statistics

Title:

Use the structure type to write a program to input the student number, name, gender and scores of four courses of five students, and then calculate and output the student information and average score. It is required to define the following functions to realize the functions of structure array data input, average score calculation, output structure array data and average score group data respectively:
void Input(struct Student s[], int n);
void Func(struct Student *p, int n, int ave[]);
void Output(STUDENT *p, int n, int ave[]);
Note that STUDENT is a data type defined with typedef
[input form] student information
[output form] student information and average score
[sample input]
2018001 zhangsan f 90 80 70 60
2018002 lisi m 88 55 69 72
2018003 wangwu f 63 89 78 85
2018004 zhaoliu m 93 69 67 68
2018005 sunqi m 85 87 68 78
[sample output]
2018001 zhangsan f 90 80 70 60 75
2018002 lisi m 88 55 69 72 71
2018003 wangwu f 63 89 78 85 79
2018004 zhaoliu m 93 69 67 68 74
2018005 sunqi m 85 87 68 78 80

code:

#include <iostream>
using namespace std;

char s[100];
char* ppp = s;

struct Student
{
    int xh;
    char name[100];
    char sex;
    int a;
    int b;
    int c;
    int d;
    double average;
}Student0[100];

int main()
{
    int n = 0;
    int pos = -1;
    while (cin >> n) 
    {
        pos ++;
        Student0[pos].xh = n;
        ppp = Student0[pos].name;
        cin >> ppp;
        cin >> Student0[pos].sex;
        cin >> Student0[pos].a;
        cin >> Student0[pos].b;
        cin >> Student0[pos].c; 
        cin >> Student0[pos].d;
        Student0[pos].average = (Student0[pos].a + Student0[pos].b 
            + Student0[pos].c + Student0[pos].d) / 4.0;
    }
    for (int i = 0; i <= pos; ++ i)
    {
        cout << Student0[i].xh << " ";
        cout << Student0[i].name << " ";
        cout << Student0[i].sex << " ";
        cout << Student0[i].a << " ";
        cout << Student0[i].b << " ";
        cout << Student0[i].c << " ";
        cout << Student0[i].d << " ";
        cout << int(Student0[i].average + 0.5) << "\n";
    }
    return 0;
}

8. Large integer addition

Title:

Please program the addition of large integers with super long digits.
[prompt]

Define a character array, receive large integers of two ultra long digits to be added, and then add single characters to characters, for example:

char x[1000],y[1000]; int sum, carry;

sum=carry+x[i]-'0'+y[i]-'0';

Where carry stands for carry.

Structures can also be used.

[example input] 1258746987452014587933321112587469874520145879333211125874698745201458793332111258746987452014587933321112587469874520145879333211

745201458793745201458793745201458793745201458793745201458793745201458793745201458793745201458793745201458793745201458793745201458793745201458793

[example output] 745201458793745201458793745201458793745214046263619721604673078412584668443946602525385335700524921891088333134779906332671333313891080792004

code:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

char x[1000], y[1000];
int str[2000];

int main()
{
    int sum, len_x, len_y;
    int carry = 0;
    gets(x);
    gets(y);
    len_x = strlen(x);
    len_y = strlen(y);
    if(len_x == len_y)
    {
        int a = -1;
        for(int i = len_x - 1; i >= 0; i --)
        {
            sum = 0;
            a ++;
            sum = carry + x[i] - '0' + y[i] - '0';
            if(sum >= 10)
            {
                carry = 1;
                str[a] = sum % 10;
            }
            if(sum < 10)
            {
                carry = 0;
                str[a] = sum;
             }
            if(i == 0 && carry == 1)
            {
                a ++;
                str[a] = 1;
            }
            for(int i = a; i >= 0; i --)
            cout << str[i] << endl;
         }
     if(len_x < len_y)
     {
         int i = len_x - 1;
         int j = len_y;
         int a = -1;
         for(;i >= 0; i --)
         {
            a ++;
            sum = 0;
            j --;
            sum = carry + x[i] - '0' + y[j] - '0';
            if(sum >= 10)
            {
                carry = 1;
                str[a] = sum % 10;
            }
            if(sum < 10)
            {
                carry = 0;
                str[a] = sum;
             }
            if(i == 0 && carry == 1)
            {
                for(j = len_y - len_x - 1; j >= 0; j --)
                {
                    sum = carry + y[j] - '0';
                    if(sum >= 10)
                    {
                    	carry = 1;
                    	str[a] = sum % 10;
                    }
                    if(sum < 10)
                    {
                    	carry = 0;
                    	str[a] = sum;
                    }
                    if(j == 0 && carry == 1)
                    {
                   		a ++;
                    	str[a] = 1;
                    }
                }
            }
         }
    }
    return 0;
}

9.playfair password

Title:

A variant encryption method of Playfair password is as follows: first select a key word (pair) (the letters are not repeated and are all lowercase letters), and then fill it into a 5X5 square together with other letters in the alphabet. The filling method is as follows:
1. First fill in the key string by line.
2. Then fill in the letters that are not in the key string in alphabetical order.
3. Because there are only 25 positions in the square, the last remaining letters do not change.
If the key is youandme, the square is as follows:

youan
dmebc
fghij
klpqr
stvwx

When encrypting a pair of letters, such as am, find a rectangle with these two letters as vertices in the square (red font):

youan
dmebc
fghij
klpqr
stvwx

The encrypted letters of this pair of letters are another pair of vertices of the rectangle, such as ob in this example.
Design a program, encrypt the input string using the above method, and output the encrypted string. In addition, there are the following provisions:
1. If there is only one letter left at the end, it will not be transformed and will be directly put into the encrypted string;
2. If two letters in a pair of letters are the same, they will not be transformed and will be directly put into the encrypted string;
3. If one of a pair of letters is not in the square, it will not be transformed and will be directly put into the encrypted string;
4. If the letter pair appears in the same row or column in the square, such as df or hi, simply swap the two letters, that is, transform them into fd or ih;
5. If a rectangle with a letter pair as the vertex can be found in the square, if the letter pair is am, in the other pair of vertex letters of the rectangle, the letter with a should be in front, and in the above example, it should be ob; Similarly, if the letter pair to be transformed is ta, the transformed letter corresponds to wo;
6. The input strings in this program are lowercase letters and do not contain other characters.

The decryption method is the same as encryption, that is, re encrypt the encrypted string to get the original string.

[input form]

Input two lines of strings from the console, the first line is the key word (length less than or equal to 25), the second line is the string to be encrypted (length less than or equal to 50), there is a carriage return line feed at the end of both lines of strings, and both lines of strings are lowercase letters without other characters.

[output form]

Output the encrypted string on standard output.

[input example]

youandme
welcometohangzhou

[output example]

vbrmmomvugnagzguu

[example description]

The key word entered is youandme, and the square formed is as shown above; The string to be encrypted is welcome Hangzhou. A rectangle with the first pair of letters we as vertices can be found in the square, and the corresponding pair of vertex letters is vb, so it is vb after encryption. Similarly, the vertex letter pairs corresponding to the letter pairs LC, et, oh and ho can be found. The letter pair om is located in the same column in the above square, so it is directly encrypted by reversing the two letters, that is, mo, and the letter pair an is the same. z in the letter pair gz is not in the above square, so it is placed in the encrypted string as it is. The last letter u is output as it is.

Algorithm tips:
1. If you use a two-dimensional array to save the characters in the square, you can first fill in the one-dimensional array with the key word and the letters not in the key word, and then put the characters in the one-dimensional array into the two-dimensional array;
2. When encrypting letter pairs, it is best to judge according to the order of the first five articles in the above provisions.

code:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

char num[25], str[5][5], s[17];
int x = -1, y = -1;

int findpos(char t)
{
    int i, j;
    for(i = 0; i < 5; i ++)
    {
        for(j = 0; j < 5; j ++)
        {
            if(str[i][j] == t)
            {
                x = i;
                y = j;
                return 1;
            }
        }
    }
    return -1;
}

int main()
{
    int len, y, i;
    char x = 'a' - 1;
    gets(num);
    len = strlen(num);
    for(int i = len; i < 25; i ++)
    {
        int j;
        x += 1;
        for(j = 0; j < len; j ++)
        {
            if(num[j] != x)
                continue;
            else
            {
                x += 1;
                j = -1;
                continue;
            }
        }
        if(j == len)
        {
            num[i] = x;
        }
    }
    for(int i = 0; i < 25; i ++)
    {
        str[i / 5][i % 5] = num[i];   //Convert one-dimensional array into two-dimensional array!! Characters can also be assigned directly!!
    }
    gets(s);
    int slen = strlen(s);
    for( i = 0; i < slen - 1; i+= 2)
    {
        int t1 = s[i];
        int t2 = s[i + 1];
        if(t1 == t2)
            cout << t1 << t2;
        int is1 = findpos(t1);
        int t1x = x;
        int t1y = y;
        int is2 = findpos(t2);
        int t2x = x;
        int t2y = y;
        if(is1 == -1 || is2 == -1)
            cout << t1 << t2;
        else if(t1x == t2x || t1y == t2y)
            cout << t2 << t1;
        else
            cout << str[t1x][t2y] << str[t2x][t1y];
    }
    if(i == slen - 1)
        cout << s[i];
    return 0;
}

Welcome to ask questions, boys and girls, come on~

Topics: C C++