I do understand I have mistakes in this code
#include <stdio.h> #include <stdlib.h> #include <string.h> int diziyi_yazdır(int dizi[], int dizi_uzunluğu) { for (int i = 0; i < dizi_uzunluğu; i++) { printf("%d", dizi[i]); } printf("\n"); } int kombnsyon_yazdır(int dizi[], int dizi_uzunluğu, int index) { if (index == 4) { return 0; } for (int i = 0; i < dizi_uzunluğu; i++) { int geçici = dizi[index]; dizi[index] = dizi[i]; dizi[i] = geçici; diziyi_yazdır(dizi, dizi_uzunluğu); kombnsyon_yazdır(dizi, dizi_uzunluğu, index + 1); dizi[i] = dizi[index]; dizi[i] = geçici; } } int main() { int dizi[4] = { 1, 2, 3, 4 }; kombnsyon_yazdır(dizi, 4, 0); } I was just expecting same sequences more than one and thats it but instead I got this output how? You can see there are duplicates in the program's output (only partly shown):
1234 2134 3124 4123 4321 4312 4312 3132 2133 2331 2313 2313 ... 1111 1111 1111 1111 1111 For English readers, here is a translation:
#include <stdio.h> #include <stdlib.h> #include <string.h> int print_array(int arr[], int arr_length) { for (int i = 0; i < arr_length; i++) { printf("%d", arr[i]); } printf("\n"); } int print_combinations(int arr[], int arr_length, int index) { if (index == 4) { return 0; } for (int i = 0; i < arr_length; i++) { int temp = arr[index]; arr[index] = arr[i]; arr[i] = temp; print_array(arr, arr_length); print_combinations(arr, arr_length, index + 1); arr[i] = arr[index]; arr[i] = temp; } } int main() { int arr[4] = { 1, 2, 3, 4 }; print_combinations(arr, 4, 0); }
dizi[i]a different value, makes the first assignment useless. Also, if you swap two elements, be aware that if you visit the other element later, your code is making the same swap again.