Make a small game by yourself (2 ).
The random display matrix has been completed, and the next step is how to move numbers according to the input
1. first, an issort function is required to determine whether the sorting is complete. If not, printf enters the number to be moved, and then finds the number to be moved based on the input to locate the underline position, determine whether the location can be moved. If yes, swap. You can move the data to the left, right, and center of the matrix. Therefore, the isleft function and isright function are required to determine whether this is the case.
While (! Issort (square, f * f) {printf ("Enter the number to move:"); int m; scanf ("% d", & m ); // enter the number int t = findnum (m, square, f) to be moved; // locate the position int max = findmax (square, f) of the number to be moved ); // locate the underline position if ((! Isleft (max, f ))&&(! Isright (max, f) & (t = max + 1 | t = max-1 | t = max + f | t = max-f )) swap (& square [max], & square [t]); else if (isleft (max, f) & (t = max + 1 | t = max + f | t = max-f) swap (& square [max], & square [t]); // else if (isright (max, f) on the left) & (t = max-1 | t = max + f | t = max-f) swap (& square [max], & square [t]); // else printf ("cannot be moved! \ N "); for (I = 0, k = 0; I <f * f; I + = f) // print the output in the matrix format {for (j = 0; j <f; j ++) {if (ismax (& square [0], f * f, k) printf ("% 2c ",'_'); else printf ("% 2d", square [k]); k ++;} printf ("\ n ");}}
Issort function findmax function findnum function isleft function isright Function
Intissort (int a [], int c) // judge whether the matrix is sorted {for (int B = 0; B <C-1; B ++) {if (a [B]> = a [B + 1]) return 0;} return 1 ;}
Intfindnum (int a, int B [], int c) // locate the input number position {for (int k = 0; k <c * c; k ++) {if (B [k] = a) return k;} return printf ("No such number! \ N ");}
Intfindmax (int a [], int B) // locate the underline position {int max = 0; for (int I = 1; I <B * B; I ++) {if (a [max] <a [I]) max = I;} return max ;}
Intisleft (int max, int f) // judge whether the underline is on the left {for (int I = 0; I <F-1; I ++) {if (max = (I + 1) * f) return 1;} return 0;} intisright (int max, int f) // determine whether the underline is on the right {for (int I = 0; I <F-1; I ++) {if (max = (I + 1) * F-1) return 1;} return 0 ;}
The final code is complete, but each input will output a new matrix. Remember that fflush was mentioned in cs50 of the Netease Open Class, but the Matrix cannot be displayed when used.
How can I achieve dynamic update of the matrix every time I input a number?