Jump to content
Incepat0r

Generare matrice in C

Recommended Posts

Posted

Salut!

Am de generat o matrice de forma:

n..........................z

z n.......................y

y z n....................x

x y z n.................w

...

o......................z n

si pe moment nu am nici o idee despre cum arata algoritmul care permite o astel de generare.

Posted (edited)


#include <string.h>
#include <stdio.h>
#include <stdlib.h>

char *shift(char *line, size_t n) {
char *shifted = (char *) malloc(n * sizeof(char));
int i;

shifted[0] = line[n - 1];
for (i = 0; i < n - 1; i++)
shifted[i + 1] = line[i];

return shifted;
}

char **gen_matrice(char *seed, size_t n) {
char **matrix = (char **) malloc(n * sizeof(char));
int i, j;
for (i = 0; i < n; i++)
matrix[i] = (char *) malloc(n * sizeof(char));

for (i = 0; i < n; i++)
matrix[i] = seed;

for (i = 0; i < n; i++)
for (j = 0; j < i; j++)
matrix[i] = shift(matrix[i], n);

return matrix;
}

int main() {
char line[] = "nopqrstuvwxyz";
int n = strlen(line);
char **matrice = gen_matrice(line, n);
int i, j;

for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
putchar(matrice[i][j]);
putchar('\n');
}

getchar();
return 0;
}

Nu e cea mai buna implementare. Nu mut valorile din tablou in alt tablou, ci doar mut pointerul pe o alta adresa. Memoria se elibereaza la `char line[]`, care e referentiat la prima linie a matricii, iar fiind alocat static, se va elibera zona de memoria la sfarsitul blocului (in cazul de sus e vorba de main(), deci e irelevant).

Edited by totti93

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...