The stupidest way to solve a simple problem

Title: input a 5x5 matrix, move the largest element to the center, and place the four smallest elements in four corners (from left to right, from top to bottom, from small to large)

Idea: the maximum value is the best to find. Loop through it once to find the maximum value and its address. Then I will find the smallest four numbers. My idea is to first store the first row of the two-dimensional array with an array, then start to traverse from the second row, start to compare from the largest element in the array b, first replace which one is smaller than, and finally replace the smallest five numbers in the two-dimensional array in the array b. Then I find the address of these four numbers. At the beginning, I didn't add the flag flag, so once there are two identical numbers in the two-dimensional array, the program will crash. After realizing this, I set a corresponding flag1,flag2, etc. for each number. Once one is found, take the address, and set the flag to 1 at the same time, indicating that the number has taken the address. Finally, just output.

 1 #include<stdio.h>
 2 int main(){
 3     void sort(int q[]);
 4     int a[5][5];
 5     int b[5];
 6     int max=0,temp;
 7     int flag1=0,flag2=0,flag3=0,flag4=0;
 8     int *p;
 9     int *p1,*p2,*p3,*p4;
10     for(int i=0;i<5;i++)
11       for(int j=0;j<5;j++)
12         scanf("%d",&a[i][j]);
13     for(int i=0;i<5;i++)
14       b[i]=a[0][i];
15     
16     for(int i=0;i<5;i++){
17       for(int j=0;j<5;j++){
18         if(a[i][j]>max) {max=a[i][j]; p=&a[i][j];}  
19 }
20 }
21     for(int i=1;i<5;i++){
22         for(int j=0;j<5;j++){
23                 for(int k=4;k>=0;k--){
24                   if(a[i][j]<b[k]) {
25                   b[k]=a[i][j];
26                   sort(b);break;
27          }
28     }
29         }
30     }
31     for(int i=0;i<5;i++){
32       for(int j=0;j<5;j++){
33         if(a[i][j]==b[0]&&flag1==0) {p1=&a[i][j];flag1=1;}
34         else if(a[i][j]==b[1]&&flag2==0) {p2=&a[i][j];flag2=1;}
35         else if(a[i][j]==b[2]&&flag3==0){p3=&a[i][j];flag3=1;}
36         else if(a[i][j]==b[3]&&flag4==0) {p4=&a[i][j];flag4=1;} 
37 }
38 }
39 *p=a[2][2];a[2][2]=max;
40 *p1=a[0][0];a[0][0]=b[0];
41 *p2=a[0][4];a[0][4]=b[1];
42 *p3=a[4][0];a[4][0]=b[2];
43 *p4=a[4][4];a[4][4]=b[3];
44      printf("\n \n");
45     for(int i=0;i<5;i++){
46       for(int j=0;j<5;j++){
47         printf("%d ",a[i][j]);
48 }
49         printf("\n");
50 }
51 }
52 //sort 
53 void sort(int q[]){
54     int temp1;
55     for(int i=0;i<5;i++){
56         for(int j=i+1;j<5;j++){
57             if(q[i]>q[j]){
58                 temp1=q[i];q[i]=q[j];q[j]=temp1;
59             }
60         }
61     }
62 }

Operation result:

Tags: C P4

Posted on Mon, 04 May 2020 04:09:15 -0400 by irbrian