I'm still a student in C. I need to do a practical task for this semester but I can't. I've tried everything, but it doesn't seems to work. What I need to do is to create a fractal which is a figure just like this one:
.
Fractals are never-ending patterns. I need to create one by using certain commands, like F
, -
and +
. F
means forward, -
means to turn left and +
to turn right, or vice versa. First the program reads the base pattern, which is F
. Then it needs to replace it by another constant pattern: 'F-F+F+FF-F-F+F'
. After that, other figure is created, because the commands were replaced. So, iit functions like this: every time it finds a 'F', this 'F' is replaced by 'F-F+F+FF-F-F+F'. The - and + are kept in the same spot.
I need to do this in C language (can't be in c++). I created this function using arrays and pointers. Char v[]
is the array received to be replaced; int n
is its size; char regra[]
is the constant pattern 'F-F+F+FF-F-F+F'; 'int n_regra' is the size of this pattern. The qnt_v
is other function to count the f's, and the qnt_sinais
is to count the + and -. These two are for defining the size of the array to be generated in the function. Hope I made myself clear.
I tried using this function only for the first basic pattern 'F'. The function should return F-F+F+FF-F-F+F, but it didn't return anything.
#include <stdio.h>
#include <string.h>
int qnt_f(char* v, int n){
int f = 0;
for(int i=0;i<n;i++){
if(v[i]=='F'){
f++;
}
}
return f;
}
int qnt_sinais(char* v, int n){
int s = 0;
for(int i=0;i<n;i++){
if(v[i]=='+' || v[i]=='-'){
s++;
}
}
return s;
}
char *fractal(char v[], int n, char regra[], int n_regra){
int t = ((qnt_f(v, n))*n_regra)+(qnt_sinais(v, n)*2)+1;
char fractal[t];
for(int i=1;i<n;i++){
if(v[i]=='F'){
strcat(fractal, regra);
}
else if(v[i]=='+'){
char sinal_mais[2] = "+";
strcat(fractal, sinal_mais);
}
else{
char sinal_menos[2] = "-";
strcat(fractal, sinal_menos);
}
}
char *f_ptr = fractal;
return f_ptr;
}
int main(){
char axioma[2] = "F";
char regra[15] = "F-F+F+FF-F-F+F";
printf("%s\n", fractal(axioma, sizeof(axioma), regra, sizeof(regra)));
return 0;
}