Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- magic_square_multiplication_v1.c
- Product of the 3 numbers in each row and column.
- All numbers are different, from range 1 to 9.
- x5 = 5 .
- indexes of array:
- x1 x x2 x x3 = 54 0 1 2
- x x x
- x4 x x5 x x6 = 120 3 4 5
- x x x
- x7 x x8 x x9 = 56 6 7 8
- " " "
- 96 180 21
- https://web.facebook.com/photo.php?fbid=545662472810656&set=a.102725373771037&type=3&theater
- Algorithm with permutations.
- https://www.codesdope.com/blog/article/generating-permutations-of-all-elements-of-an-arra/
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- int number_of_solutions=0;
- unsigned number_of_attempts=0;
- //function to print the array of n integers
- void print_array(int arr[], int n)
- {
- number_of_attempts++;
- if( arr[0] * arr[1] * arr[2] == 54 &&
- arr[3] * arr[4] * arr[5] == 120 &&
- arr[6] * arr[7] * arr[8] == 56 &&
- arr[0] * arr[3] * arr[6] == 96 &&
- arr[1] * arr[4] * arr[7] == 180 &&
- arr[2] * arr[5] * arr[8] == 21 )
- {
- number_of_solutions++; // number_of_solutions and display them
- printf("\n---%3d. solution: --------\n\n", number_of_solutions);
- printf(" %3d %3d %3d \n", arr[0], arr[1], arr[2] );
- printf(" %3d %3d %3d \n", arr[3], arr[4], arr[5] );
- printf(" %3d %3d %3d \n", arr[6], arr[7], arr[8] );
- }
- } // print_array()
- // function to swap the variables a and b
- void swap(int *a, int *b)
- {
- int temp;
- temp = *a;
- *a = *b;
- *b = temp;
- }
- // recursive function to generate permutation
- void permutation(int *arr, int start, int end)
- {
- int i;
- if(start==end)
- {
- print_array(arr, end+1); // this is one permutation
- return;
- }
- for( i=start; i<=end; i++ ) // fixing one first digit,
- {
- swap((arr+i), (arr+start)); // swapping numbers
- permutation(arr, start+1, end); // and calling permutation on the rest of the digits
- swap((arr+i), (arr+start)); // swapping numbers
- }
- } // permutation()
- int main(void)
- {
- int i;
- int arr[9]; // array of 9 permutation elements
- for (i = 0; i < 9; i++) // fill in the array with integers from 1 to 9
- arr[i] = i + 1;
- permutation(arr, 0, 8); //calling recursive function to generate permutations
- printf("\n Number of attempts is 9! = %ld \n", number_of_attempts);
- printf("\n There are %d solutions. \n", number_of_solutions);
- return 0;
- } // main()
- /*
- --- 1. solution: --------
- 6 9 1
- 8 5 3
- 2 4 7
- Number of attempts is 9! = 362880
- There are 1 solutions.
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement