From 5947dff0d98c31a6ce2c980e5f02bd560183de14 Mon Sep 17 00:00:00 2001 From: juan Date: Fri, 3 Dec 2021 00:07:02 +0800 Subject: [PATCH] Am i the first one to finish these psets? IDK. --- pset11/2-6-SneakyMatrix.c | 76 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 pset11/2-6-SneakyMatrix.c diff --git a/pset11/2-6-SneakyMatrix.c b/pset11/2-6-SneakyMatrix.c new file mode 100644 index 0000000..5f850c6 --- /dev/null +++ b/pset11/2-6-SneakyMatrix.c @@ -0,0 +1,76 @@ +// More of a math problem +#include +#define MAX 100 + +// *** THERE IS AN SIMPLER SOLUTION, THIS ONE IS BLOATED AND BAD *** +// +// There are two main movements: +// 1: diagonal move, which includes two ways: i++&&j-- and i--&&j++ +// ^way = 0 ^way = 1 +// and for the diagonal move, the are six scenarios where the next step hits the +// boundary. +// a: nexti < n, nextj < 0 where i is valid. Results in i++ +// b: nexti < 0, nextj < n where j is valid. Results in j++ +// c: nexti >=n, nextj < 0 where none is valid. Results in j++ +// d: nexti <0, nextj >= n where none is valid. Results in i++ +// e: nexti >=n, nextj >=0 where j is valid. Results in j++ +// f: nexti >=0, nextj >=n where i is valid. Results in i++ +// +// 2: horizontal and vertical move, which includes two ways as well: i++ and j++ +// The movement stops when i == j and j == n +void fill(int matrix[][MAX], int n); + +int main(void) { + int n; + scanf("%d", &n); + + int matrix[n][MAX]; + fill(matrix, n); + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n - 1; j++) { + printf("%d ", matrix[i][j]); + } + printf("%d\n", matrix[i][n - 1]); + } + return 0; +} + +void fill(int matrix[][MAX], int n) { + int i = 0, j = 0; + int nexti, nextj; + int way = 1; + int count = 1; + while (count <= n * n) { + matrix[i][j] = count++; + if (way == 1) { + nexti = i + 1; + nextj = j - 1; + } else { + nexti = i - 1; + nextj = j + 1; + } + // Validate if the next step is in the matrix. + // First: the next step is within matrix. + if (nexti >= 0 && nexti < n && nextj >= 0 && nextj < n) { + i = nexti; + j = nextj; + } else { + // Second: the next step is out of boundary. + if (nextj < 0 && nexti < n) { + i++; + } else if (nexti < 0 && nextj < n) { + j++; + } else if (nexti >= n && nextj < 0) { + j++; + } else if (nexti < 0 && nextj >= n) { + i++; + } else if (nexti >= n && nextj >= 0) { + j++; + } else if (nexti >= 0 && nextj >= n) { + i++; + } + way *= -1; + } + } +}