Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _GNU_SOURCE
- #include <sys/types.h>
- #include <sys/mman.h>
- #include <unistd.h>
- #include <string.h>
- #include <stdio.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <stdint.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <stdlib.h>
- int main(int argc, char *argv[]) {
- char *file_name = argv[1];
- int32_t N = strtol(argv[2], NULL, 10);
- int32_t W = strtol(argv[3], NULL, 10);
- size_t length = N * N * W + N;
- int fd = open(file_name, O_RDWR | O_CREAT, 0777);
- ftruncate(fd, length);
- struct stat st;
- fstat(fd, &st);
- char *contents = mmap(NULL,
- st.st_size,
- PROT_READ | PROT_WRITE,
- MAP_SHARED,
- fd,
- 0);
- memset(contents, ' ', st.st_size);
- int *arr;
- arr = (int*)malloc(N * N * sizeof(int));
- for (int i = 0; i < N; i++) {
- for (int j = 0; j < N; j++) {
- arr[i * N + j] = 0;
- }
- }
- int count = 1;
- int i = 0;
- int j = 0;
- int d = 3;
- while(count != N * N + 1) {
- if (i != N && i != -1 && j != N && j != -1 && arr[i * N + j] == 0) {
- char *cur = contents + i * N * W + j * W + i;
- arr[i * N + j] = 1;
- char *strs = malloc(100 * sizeof(char));
- snprintf(strs, W + 1, "%d", count);
- stpncpy(cur + W - strlen(strs), strs, strlen(strs));
- free(strs);
- count++;
- if (d == 0) {
- if (i + 1 == N || arr[(i + 1) * N + j] == 1) {
- d = 1;
- j--;
- } else {
- i++;
- }
- } else if (d == 1) {
- if (j - 1 == -1 || arr[i * N + j - 1] == 1) {
- d = 2;
- i--;
- } else {
- j--;
- }
- } else if (d == 2) {
- if (i - 1 == -1 || arr[(i - 1) * N + j] == 1) {
- d = 3;
- j++;
- } else {
- i--;
- }
- } else if (d == 3) {
- if (j + 1 == N || arr[i * N + j + 1] == 1) {
- d = 0;
- i++;
- } else {
- j++;
- };
- }
- }
- }
- for (int i = 0; i < N; ++i) {
- *(contents + N * W + i * N * W + i) = '\n';
- }
- free(arr);
- finally:
- munmap(contents, st.st_size);
- close(fd);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement