C :: Aufgabe #131
1 Lösung
Erzeugen einer Text-Spirale
Anfänger - C
von hak
- 08.10.2016 um 20:06 Uhr
Schreibe ein Programm das einen beliebigen Text in Spiralform ausgibt!
Für den Input "123456789" sollte das Programm ausgeben:
543
612
789
Beispiel im Anhang: das Alphabet in Spiralform (Python)
Für den Input "123456789" sollte das Programm ausgeben:
543
612
789
Beispiel im Anhang: das Alphabet in Spiralform (Python)
Lösungen:
Die Ausgabe enthält noch Debugzeilen, welche die Moves des Spiral-Algorithmus anzeigen.
Konsolenausgabe:
$ ./spirale 1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ
...
try regular move to ( -1 , -3)
not vacant, move to ( -3 , -5)
try regular move to ( -3 , -3)
not vacant, move to ( -5 , -5)
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . Z Y X W V U . . .
. . . G F E D C T . . .
. . . H 5 4 3 B S . . .
. . . I 6 1 2 A R . . .
. . . J 7 8 9 0 Q . . .
. . . K L M N O P . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
C-Code
/******************************************** * spirale.c Textspirale ********************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #define SIZE 12 char grid[SIZE][SIZE]; /* auxiliary functions */ int p2i(int x) { /* convert position to index */ return (x>>1) + SIZE/2; } int vacant(int x, int y) { /* return true if grid position is vacant */ return (grid[p2i(x)][p2i(y)]) ? 0 : 1; } void fill(int x, int y, char c) { /* set character on grid position */ grid[p2i(x)][p2i(y)] = c; } void pr(int x, int y) { /* debug */ printf("try regular move to (%3d ,%3d)\n", x, y); } void pc(int x, int y) { /* debug */ printf("not vacant, move to (%3d ,%3d)\n", x, y); } void show_grid(void) { int x, y; for (y=0; y<SIZE; y++) { for (x=0; x<SIZE; x++) printf(" %c", (grid[x][y]) ? grid[x][y]:'.'); printf("\n"); } } /*** main ***/ int main(int argc, char **argv) { int x1, x2, y1, y2; int i, len=0; if (argc < 2) return 0; len = strlen(argv[1]); if (len == 0) return 0; /* Init */ memset(grid, 0, sizeof(grid)); x1 = -1; y1 = 1; fill(x1, y1, argv[1][0]); /* loop through string */ for (i=1; i<len; i++) { if (x1 > 0 && y1 < 0) { /* Quadrant I */ x2 = x1 - 2; y2 = y1; pr(x2, y2); if (!vacant(x2,y2)) { x2 = x1; y2 = y1 - 2; pc(x2, y2); } } else if (x1 < 0 && y1 < 0) { /* Quadrant II */ x2 = x1; y2 = y1 + 2; pr(x2, y2); if (!vacant(x2,y2)) { x2 = x1 - 2; y2 = y1; pc(x2, y2); } } else if (x1 < 0 && y1 > 0) { /* Quadrant III */ x2 = x1 + 2; y2 = y1; pr(x2, y2); if (!vacant(x2,y2)) { x2 = x1; y2 = y1 + 2; pc(x2, y2); } } else { /* Quadrant IV */ x2 = x1; y2 = y1 - 2; pr(x2, y2); if (!vacant(x2,y2)) { x2 = x1 + 2; y2 = y1; pc(x2, y2); } } x1 = x2; y1 = y2; fill(x1, y1, argv[1][i]); } show_grid(); return 0; }