I am pretty new to competitive programming. It took me almost 3 hours to make this, initially I started with 4 for loops and then to make it scalable for sizes bigger than 4, I decided to turn this into a recursion which is when it took most of my time, even though I am proud of it, I am still worried that it took me an hour to actually come up with the solution and I have a feeling that it is neither efficient nor good, (you could say I am basically doing combination rather than permutation), I would like a code review please and how would you make this more efficient?
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int counter = 0;
int factorial(int n){
if(n==1) return 1;
else return n*factorial(n-1);
}
int index_present_check(int* n_arr, int n, int depth){
for(int i = 0 ; i < depth ; i++) if(n_arr[i]==n) return 1;
return 0;
}
int present_in_array_check(char** store_arr,char* arr_to_print,int counter){
for(int i = 0; i < counter; i++) if(strcmp(store_arr[i],arr_to_print)==0) return 1;
return 0;
}
void permutation(int depth,int length,char* src_arr, char* arr_to_print,int* n_arr,char** store_arr){
for(int i = 0 ; i < length ; i ++){
if(depth ==1){
arr_to_print[0] = src_arr[i];
n_arr[0] = i;
permutation(depth+1,length,src_arr,arr_to_print,n_arr,store_arr);
}
else{
if(!index_present_check(n_arr,i,depth)){
arr_to_print[depth-1] = src_arr[i];
n_arr[depth-1] = i;
permutation(depth+1,length,src_arr,arr_to_print,n_arr,store_arr);
n_arr[depth-1] = -1;
}
}
}
if(depth==length){
if(!present_in_array_check(store_arr,arr_to_print,counter)){
printf("%s ",arr_to_print);
strcpy(store_arr[counter],arr_to_print);
counter++;
if(counter%factorial(length-1)==0){
printf("\n");
}
}
}
}
int main()
{
char* src_arr = "ABCDE";
int length = 4;
int depth = 1;
int iteration_length = factorial(length);
char* arr_to_print = malloc(length*sizeof(char));
int* n_arr = malloc(length*sizeof(int));
char** store_arr = (char**)malloc(sizeof(char*)*iteration_length);
for(int i = 0 ; i<iteration_length;i++) store_arr[i] = malloc(sizeof(char)*length);
permutation(depth,length,src_arr,arr_to_print,n_arr,store_arr);
return 0;
}
I posted this in reddit too, but it was a bit off timing and didn't get much code review, however it was helpful nonetheless.