16*16 Sudoku solver using backtracking in c - c

I have coded a 16*16 sudoku solver using the backtracking algorithm in c. The program takes input from the user using a text file. The unfilled positions in the matrix are filled with a 0. Works perfectly fine.
I want to further optimize the code for time and space complexity. Please suggest some methods or ways to optimize the code.
#include <stdio.h>
#include<time.h>
#define N 16
int isAvailable(int sudoku[16][16], int row, int col, int num)
{
int i, j;
for(i=0; i<16; i++){
if( (sudoku[row][i] == num) || ( sudoku[i][col] == num ) )
return 0;
}
int rowStart = (row/4) * 4;
int colStart = (col/4) * 4;
for(i=rowStart; i<(rowStart+4); ++i)
{
for(j=colStart; j<(colStart+4); ++j)
{
if( sudoku[i][j] == num )
return 0;
}
}
return 1;
}
int fillsudoku(int sudoku[16][16], int row, int col)
{
int i;
if( row<16 && col<16 )
{
if( sudoku[row][col] != 0 )
{
if( (col+1)<16 )
return fillsudoku(sudoku, row, col+1);
else if( (row+1)<16 )
return fillsudoku(sudoku, row+1, 0);
else
return 1;
}
else
{
for(i=0; i<16; ++i)
{
if( isAvailable(sudoku, row, col, i+1) )
{
sudoku[row][col] = i+1;
if( (col+1)<16 )
{
if( fillsudoku(sudoku, row, col+1) )
return 1;
else
sudoku[row][col] = 0;
}
else if( (row+1)<16 )
{
if( fillsudoku(sudoku, row+1, 0) )
return 1;
else
sudoku[row][col] = 0;
}
else
return 1;
}
}
}
return 0;
}
else
{
return 1;
}
}
int main()
{
clock_t tic=clock();
int a,i,j;
int sudoku[N][N];
FILE *f;
f=fopen("s16.txt","r");
for(i=0;i<N;i++){
for(j=0;j<N;j++)
{
fscanf(f,"%d",&sudoku[i][j]);
}
}
if( fillsudoku(sudoku, 0, 0) )
{
for(i=0; i<16; ++i)
{
for(j=0; j<16; ++j){
printf("%d ", sudoku[i][j]);
if(sudoku[i][j]<10){
printf(" ");
}
if(j%4==3){
printf("|");
}
}
printf("\n");
if(i%4==3){
printf("----------------------------------------------------");
}
printf("\n");
}
}
else
{
printf("\n\nNO SOLUTION\n\n");
}
clock_t toc=clock();
printf("\nTotal time elasped is %f", (double)(toc - tic) / CLOCKS_PER_SEC);
return 0;
fclose(f);
}

Related

Havel-Hakimi Algorithm in C

I'm trying to write havel-hakimi theorem in C. But I have a problem with the while loop. The program doesn't sort array again in the while loop and that's why output prints the wrong answer. Could show me what's my fault please?
# include <stdio.h>
int main(){
int j,i,vertex_number,temp1,temp2,a=0,b=0;
printf("Vertex Number:");
scanf("%d",&vertex_number);
int graph[vertex_number];
for(i=0;i<vertex_number;i++){
scanf("%d",&graph[i]);
}
while(1){
//SORTING ARRAY
for(i=0;i<vertex_number;i++){
for(j=i+1;j<vertex_number;j++){
if(graph[i]<graph[j]){
temp1=graph[i];
graph[i]=graph[j];
graph[j]=temp1;
}
}
}
//IF ALL VERTEX DEGREES EQUAL 0 GRAPH EXIST
for(i=0;i<vertex_number;i++){
if(graph[i]==0){
a++;
}
}
if(a==vertex_number){
printf(" graph exist.");
return 0;
}
//NEGATIVE VERTEX DEGREE NOT EXIST
for(i=0;i<vertex_number;i++){
if(graph[i]<0){
b++;
}
}
if(b>0){
printf("graph not exist.");
return 0;
}
temp2=graph[0];
for(i=0;i<temp2;i++){
graph[i]=graph[i+1];
}
vertex_number--;
for(i=0;i<temp2;i++){
graph[i]-=1;
}
printf("-------------\n");
for(i=0;i<vertex_number;i++){
printf("%d\n",graph[i]);
}
}
}
Your have 2 issues, the exist if graph[i]-=1; is negative and the removing loop doing should be done for vertex_number and not temp2
# include <stdio.h>
int main(void) {
int i, j, vertex_number, temp1, temp2;
printf("Vertex Number:");
scanf("%d", &vertex_number);
int graph[vertex_number];
for (i = 0; i < vertex_number; i++){
scanf("%d", &graph[i]);
}
while (1) {
//SORTING ARRAY
for (i = 0; i < vertex_number; i++) {
for (j = i+1; j < vertex_number; j++) {
if (graph[i] < graph[j]) {
temp1 = graph[i];
graph[i] = graph[j];
graph[j] = temp1;
}
}
}
//IF ALL VERTEX DEGREES EQUAL 0 GRAPH EXIST
if (graph[0] == 0) {
printf(" graph exist.");
return 0;
}
//NEGATIVE VERTEX DEGREE NOT EXIST
for (i = 0; i < vertex_number; i++) {
if (graph[i] < 0){
printf("graph not exist.");
return 0;
}
}
temp2 = graph[0];
vertex_number--;
for (i = 0; i < vertex_number; i++) { // HERE was your issue
graph[i] = graph[i + 1];
}
for (i = 0; i < temp2; i++) {
graph[i]-=1;
if (graph[i] < 0) {
printf("graph not exist.");
return 0;
}
}
printf("-------------\n");
for (i = 0; i < vertex_number; i++) {
printf("%d\n",graph[i]);
}
}
}
You don't need a, if the first is null all the other are null or negative
You don't need b neither just stop on first occurence
Not an answer, but a cleaned-up version that works follows.
The key is that it literally removes the first element from the array by advancing the pointer and reducing the size of the array. That way, we're always working with elements 0..s-1 or 0..n-1.
// Destroys the contents of the provided array.
int havel_hakimi(unsigned *degrees, size_t n) {
while (1) {
// Yuck
for (size_t i=0; i<n; ++i) {
for (size_t j=i+1; j<n; ++j) {
if (degrees[i] < degrees[j]) {
int temp = degrees[i];
degrees[i] = degrees[j];
degrees[j] = temp;
}
}
}
if (degrees[0] == 0)
return 1; // Has a simple graph.
// Remove first element.
unsigned s = degrees[0];
++degrees;
--n;
if (s > n)
return 0; // Invalid input!
if (degrees[s-1] == 0)
return 0; // Doesn't have a simple graph.
for (size_t i=s; i--; )
--degrees[i];
}
}
Tested using the following:
#include <stdio.h>
int main(void) {
{
unsigned degrees[] = { 6, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1 };
printf("%d\n", havel_hakimi(degrees, sizeof(degrees)/sizeof(degrees[0]))); // 1
}
{
unsigned degrees[] = { 6, 5, 5, 4, 3, 2, 1 };
printf("%d\n", havel_hakimi(degrees, sizeof(degrees)/sizeof(degrees[0]))); // 0
}
return 0;
}

Maze by recursive division not working - C

I'm having some trouble with my recursive division generated maze. I know there's something wrong about the recursion, but I just can't find a way to solve it.
I also know the code is really big and not optimized at all, but I'm working better on this issue later.
The red maze is what I'm generating and the purple one is what I'm trying to do:
What should I be doing to correct that?
Tnks.
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#define MAX 41
#define FUNDO 0
#define PAREDE 1
#define SAIDA 2
#define SOLUCAO 3
int num_aleat(int min, int max)
{
return rand()%(max-min+1)+min;
}
void paredes(int m[][MAX], int FINAL_i, int FINAL_j, int INICIO_i, int INICIO_j)
{
int i=0, j=0;
for(i=0; i<MAX; i++)
{
if (i!=FINAL_i && i!=INICIO_i)
m[i][j]=PAREDE;
}
i=0;
for(j=0; j<MAX; j++)
{
if (j!=INICIO_j)
m[i][j]=PAREDE;
else
m[i][j]=SAIDA;
}
j=0;
for(i=0; i<MAX; i++)
{
if (j!=FINAL_j && j!=INICIO_j)
m[i][j+MAX-1]=PAREDE;
}
i=0;
for(j=0; j<MAX; j++)
{
if (j!=FINAL_j)
m[i+MAX-1][j]=PAREDE;
else
m[i+MAX-1][j]=SAIDA;
}
j=0;
}
void pardede_gener(int m[][MAX], int min, int max, int x, int dir)
{
int i=0, passagem=0;
switch (dir)
{
case 1:
passagem=num_aleat(min, max);
printf("\nc\n");
for(i=min; i<=max; i++)
{
if(i!=passagem)
m[i][x]=PAREDE;
printf("\nd_%i_%i\n", i, x);
}
return;
break;
case 2:
passagem=num_aleat(min, max);
for(i=min; i<=max; i++)
{
if(i!=passagem)
m[x][i]=PAREDE;
}
return;
break;
}
return;
}
void div(int m[][MAX], int i, int j, int max_i, int max_j, int dir)
{
int parede_i=MAX, parede_j=MAX, flag=0;
if(dir==1)
{
while(1)
{
parede_j=num_aleat(j, max_j);
if (parede_j%2==0 && m[i+1][parede_j]==FUNDO && m[i+1][parede_j-1]!=PAREDE && m[i+1][parede_j+1]!=PAREDE || m[i+2][parede_j]!=PAREDE)
break;
else
break;
}
if(m[i+1][parede_j]!=PAREDE && m[i+1][parede_j-1]!=PAREDE && m[i+1][parede_j+1]!=PAREDE)
{
pardede_gener(m, i+1, max_i-1, parede_j, dir);
dir=2;
div(m, i, j, max_i, parede_j, dir);
div(m, i, parede_j, max_i, max_j, dir);
}
else
return;
}
else if(dir==2)
{
while(1)
{
parede_i=num_aleat(j, max_j);
if (parede_i%2==0 && m[parede_i][j+1]==FUNDO && m[parede_i-1][j+1]!=PAREDE && m[parede_i+1][j+1]!=PAREDE || m[parede_i][j+2]==PAREDE)
break;
else
break;
}
if(m[parede_i][j+1]!=PAREDE && m[parede_i-1][j+1]!=PAREDE && m[parede_i+1][j+1]!=PAREDE)
{
pardede_gener(m, j, max_j-1, parede_i-1, dir);
dir=1;
div(m, i, j, parede_i, max_j, dir);
div(m, parede_i, j, max_i, max_j, dir);
}
else
return;
}
}
bool resolve(int *m, int i, int j, int fi, int fj)
{
*(m + i*MAX + j)=SOLUCAO;
if(i==fi-1 && j==fj)
return true;
if (i+1<MAX && *(m + (i+1)*MAX + j)==FUNDO)
{
if(resolve(m, i+1, j, fi, fj))
return true;
}
if (i-1>=0 && *(m + (i-1)*MAX + j)==FUNDO)
{
if(resolve(m, i-1, j, fi, fj))
return true;
}
if (j+1<MAX && *(m + i*MAX + (j+1))==FUNDO)
{
if(resolve(m, i, j+1, fi, fj))
return true;
}
if (j-1>=0 && *(m + i*MAX + (j-1))==FUNDO)
{
if(resolve(m, i, j-1, fi, fj))
return true;
}
*(m + i*MAX + j)=FUNDO;
return false;
}
int main()
{
int lab[MAX][MAX];
int FINAL_i=0, FINAL_j=0, INICIO_i=0, INICIO_j=0, i=0, j=0;
srand(time(NULL));
FINAL_i=MAX-1;
while (INICIO_j%2==0 || FINAL_j%2==0)
{
INICIO_j=rand()%(MAX-2)+1;
FINAL_j=rand()%(MAX-2)+1;
}
zero(lab);
paredes(lab, FINAL_i, FINAL_j, INICIO_i, INICIO_j);
div(lab, 0, 0, MAX-1, MAX-1, 1);
// resolve(*lab, 1, INICIO_j, FINAL_i, FINAL_j);
return 0;
}

Possible mode error

I've made this program that computes the mean, the median and the mode from an array. Although I've tested with some examples, I found out there might be a case that I have forgotten as for many of the inputs I've tested it works but the testing program that my teacher is using gave me an error for a certain test, but I was not presented with its input. Maybe someone can have a look and see if I am making a mistake at the mode point of the code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void *safeMalloc(int n) {
void *p = malloc(n);
if (p == NULL) {
printf("Error: malloc(%d) failed. Out of memory?\n", n);
exit(EXIT_FAILURE);
}
return p;
}
int main(int argc, char *argv[]) {
int n, i;
scanf("%d", &n);
int *array = safeMalloc(n * sizeof(int));
for (i = 0; i < n; i++) {
int value;
scanf("%d", &value);
array[i] = value;
}
//mean
double mean;
double sum = 0;
for (i = 0; i < n; i++) {
sum = sum + (double)array[i];
}
mean = sum / n;
printf("mean: %.2f\n", mean);
//median
float temp;
int j;
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++) {
if (array[i] > array[j]) {
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
printf("median: %d\n", array[n / 2]);
//mode
int val = array[0], noOfRepetitions = 1, valMax = array[0], maxRepetitions = 1, possibleMax = 1;
for (i = 1; i < n; i++) {
if (array[i] == val) {
noOfRepetitions++;
}
if (array[i] != val) {
val = array[i];
noOfRepetitions = 1;
}
if (noOfRepetitions == possibleMax) {
maxRepetitions = 1;
continue;
}
if (noOfRepetitions > maxRepetitions) {
valMax = val;
maxRepetitions = noOfRepetitions;
possibleMax = maxRepetitions;
}
}
if (maxRepetitions > 1) {
printf("mode: %d\n", valMax);
} else {
printf("mode: NONE\n");
}
return 0;
}
My idea for mode was because the numbers are sorted when just transverse it. If the next element is the same as the previous one, increase the noOfRepetitions. If the noOfRepetition is bigger than the maxRepetitions until now, replace with that. Also store the last maximum val needed if we have for example more than 2 numbers with the same number of repetitions.
EDIT: The mode of an array should return the number with the maximum number of occurrences in the array.If we have 2 or more number with the same number of maximum occurrences , there isn't a mode on that array.
I've discovered my mistake. I didn't think of the case when I have numbers with same maximum frequency and after that came one with lower frequency but still bigger than others. For example : 1 1 1 2 2 2 3 3 4 5 6.With my code , the result would have been 3 . I just needed to change the comparison of noOfRepetitions with oldMaxRepetition.
There seems to be no purpose for the variable possibleMax. You should just remove these lines:
if(noOfRepetitions==possibleMax){
maxRepetitions=1;
continue;
}
They cause maxRepetitions to be reset erroneously.
You could detect if the distribution is multimodal and print all mode values:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void *safeMalloc(int n) {
void *p = malloc(n);
if (p == NULL) {
printf("Error: malloc(%d) failed. Out of memory?\n", n);
exit(EXIT_FAILURE);
}
return p;
}
int main(int argc, char *argv[]) {
int n, i;
if (scanf("%d", &n) != 1 || n <= 0)
return 1;
int *array = safeMalloc(n * sizeof(int));
for (i = 0; i < n; i++) {
if (scanf("%d", &array[i]) != 1)
return 1;
}
//mean
double sum = 0;
for (i = 0; i < n; i++) {
sum = sum + (double)array[i];
}
printf("mean: %.2f\n", sum / n);
//median
int j;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (array[i] > array[j]) {
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
printf("median: %d\n", array[n / 2]);
//mode
int val = array[0], noOfRepetitions = 1, valMax = array[0], maxRepetitions = 1;
for (i = 1; i < n; i++) {
if (array[i] == val) {
noOfRepetitions++;
if (noOfRepetitions > maxRepetitions) {
valMax = val;
maxRepetitions = noOfRepetitions;
}
} else {
val = array[i];
noOfRepetitions = 1;
}
}
if (maxRepetitions == 1) {
printf("mode: NONE\n");
} else {
printf("mode: %d", valMax);
val = array[0];
noOfRepetitions = 1;
for (i = 1; i < n; i++) {
if (array[i] == val) {
noOfRepetitions++;
} else {
if (noOfRepetition == maxRepetitions && val != valMax) {
printf(", %d", val);
}
val = array[i];
noOfRepetitions = 1;
}
}
if (noOfRepetition == maxRepetitions && val != valMax) {
printf(", %d", val);
}
printf("\n");
}
return 0;
}
Your code to search a mode seems too complicated. Compare this:
//mode
int val = array[0], noOfRepetitions = 1,
valMax = array[0], maxRepetitions = 1;
for (i = 1; i < n; i++) {
if (array[i] == val) {
if (++noOfRepetitions > maxRepetitions) {
valMax = val;
maxRepetitions = noOfRepetitions;
}
}
else
{
val = array[i];
noOfRepetitions = 1;
}
}
It's probably the simplest code to do what you need, but it overwrites maxVal and maxRepetitions much too often.
The following version overwrites the two 'max' variables only once per each new maximum found – at the cost of duplicating some part of code:
//mode
int val = array[0], noOfRepetitions = 1,
valMax = array[0], maxRepetitions = 1;
for (i = 1; i < n; i++) {
if (array[i] == val) {
++noOfRepetitions;
}
else
{
if (noOfRepetitions > maxRepetitions) {
valMax = val;
maxRepetitions = noOfRepetitions;
}
val = array[i];
noOfRepetitions = 1;
}
}
if (noOfRepetitions > maxRepetitions) {
valMax = val;
maxRepetitions = noOfRepetitions;
}

C sudoku backtracking solver precheck function

This is my first post on StackOverflow, so I apologize if I'm doing something wrong. I'm relatively new to C, so I'm sure my code is fairly ugly and hacky in places, however the majority of the code does what I expect it to. I'm having trouble with a precheck method that I'm using to check a sudoku board before I begin feeding it through my solver-logic. I'm redirecting input from a text file with strings that look like
4.....8.5.34.........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......
4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.5......
4.....8.5.3..........7......2.....6.....8.4......1...x...6.3.7.5..2.....1.4......
417369825632158947958724316825437169791586432346912758289643571573291684164875293
417369825632158947958724316825437169791586432346912758289643.71573291684164875293
Each string is (ideally) 81 characters with just digits 1-9 and '.'s. I parse a string into a temp char array, and then use the method fillBoard to transfer the chars in the temp array into a 2d int array. Once this is complete, I call my precheck method. If the filled board doesn't pass the row, column, and box checks, the precheck method returns a one, indicating that the puzzle is not solvable (meaning an error message should be printed and that the program should move on to the next string). For some reason, my precheck method is returning one even for strings that should be solvable. I'm not sure why this is. Any help would be appreciated. Thanks.
#include <stdio.h>
#include <string.h>
int alphaError = 0;
struct Point findEmpty(int board[9][9]);
int usedInBox(int board[9][9], int boxStartRow, int boxStartCol, int num);
int positionSafe(int board[9][9], int row, int col, int num);
int usedInCol(int board[9][9], int col, int num);
int usedInRow(int board[9][9], int row, int num);
int solvePuzzle(int board[9][9]);
int precheck(int board[9][9]);
int main()
{
char c;
int charCount = 0;
int i = 0;
char tempStr[100000];
int board[9][9];
while((fscanf(stdin, "%c", &c)) != EOF)
{
printf("%c", c);
if(c != '\n')
{
if(isalpha(c))
{
alphaError = 1;
}
tempStr[i] = c;
i++;
charCount++;
}
else
{
if(charCount != 81 || alphaError == 1)
{
printf("Error\n\n");
i = 0;
charCount = 0;
alphaError = 0;
}
else
{
fillBoard(board, tempStr);
printBoard(board);
if(precheck(board) == 1)
{
printf("Error\n\n");
}
else
{
if(solvePuzzle(board) == 1)
{
printBoard(board);
}
else
{
printf("No solution\n\n");
}
}
i = 0;
charCount = 0;
}
}
}
return 0;
}
struct Point
{
int x;
int y;
} point;
struct Point findEmpty(int board[9][9])
{
struct Point point1;
point1.x = -1;
point1.y = -1;
int row, col;
for(row = 0; row < 9; row++)
{
for(col = 0; col < 9; col++)
{
if(board[row][col] == 0)
{
point1.x = col;
point1.y = row;
}
}
}
return point1;
}
int usedInBox(int board[9][9], int boxStartRow, int boxStartCol, int num)
{
int row, col;
for(row = 0; row < 3; row++)
{
for(col = 0; col < 3; col++)
{
if(board[row + boxStartRow][col + boxStartCol] == num)
{
return 1;
}
}
}
return 0;
}
int positionSafe(int board[9][9], int row, int col, int num)
{
if((usedInRow(board, row, num)) == 0 && (usedInCol(board, col, num)) == 0 && (usedInBox(board, (row-row%3), (col-col%3), num)) == 0)
{
return 1;
}
else
{
return 0;
}
}
int usedInCol(int board[9][9], int col, int num)
{
int row;
for(row = 0; row < 9; row++)
{
if(board[row][col] == num)
{
return 1;
}
}
return 0;
}
int usedInRow(int board[9][9], int row, int num)
{
int col;
for(col = 0; col < 9; col++)
{
if(board[row][col] == num)
{
return 1;
}
}
return 0;
}
int solvePuzzle(int board[9][9])
{
int num;
struct Point point2;
point2 = findEmpty(board);
if(point2.x == -1)
{
return 1;
}
for(num = 1; num <= 9; num++)
{
if(positionSafe(board, point2.y, point2.x, num) == 1)
{
board[point2.y][point2.x] = num;
if(solvePuzzle(board) == 1)
{
return 1;
}
board[point2.y][point2.x] = 0;
}
}
return 0;
}
void printBoard(int board[9][9])
{
int i, j;
for (i = 0; i < 9; i++)
{
for (j = 0; j < 9; j++)
{
printf("%d", board[i][j]);
}
}
printf("\n\n");
}
void fillBoard(int board[9][9], char tempStr[100000])
{
int i, j;
int k = 0;
for(i = 0; i < 9; i++)
{
for(j = 0; j < 9; j++)
{
if(tempStr[k] == '.')
{
board[i][j] = 0;
}
else
{
board[i][j] = (tempStr[k] - '0');
}
k++;
}
}
}
int precheck(int board[9][9])
{
int i, j, num;
for(i = 0; i < 9; i++)
{
for(j = 0; j < 9; j++)
{
if(board[i][j] != 0)
{
num = board[i][j];
if(positionSafe(board, i, j, num) == 0)
{
return 1;
}
}
}
}
return 0;
}
So you are using precheck on an already filled board? That might be the problem because usedInCol, usedInRow and usedInBlock will return 1 if the value is already present. So precheck should be used only while filling the board, not after. It will always return 1 if you check values you take from the already filled board.

How to blur a .pgm file?

I've written this code, which is supposed to blur a .pgm file. Works perfectly on Linux, but it gives a wrong result on Windows. The program should be run like this: "filter.exe enb.pgm enb_filtered.pgm qs 3", where the 4th argument can be qs/cnt/ins, depending on what sorting algorithm wants the user to use, while the 5th one it's an odd number and gives the width of the blurring window (it should go at least until 21). 1st argument is our .exe, the 2nd one is the initial image, while the 3rd one is the final image. On Linux, the result is the expected one, while on Windows the enb.filtered.pgm file is all black and it has wrong dimensions. Can you, guys, help me?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#define HI(num) (((num) & 0x0000FF00) >> 8)
#define LO(num) ((num) & 0x000000FF)
typedef struct _PGMData {
int row;
int col;
int max_gray;
int **matrix;
} PGMData;
void quick_sort (int *a, int n) {
int i, j, p, t;
if (n < 2)
return;
p = a[n / 2];
for (i = 0, j = n - 1;; i++, j--) {
while (a[i] < p)
i++;
while (p < a[j])
j--;
if (i >= j)
break;
t = a[i];
a[i] = a[j];
a[j] = t;
}
quick_sort(a, i);
quick_sort(a + i, n - i);
}
void insertion_sort (int *a, int n) {
int i, j, t;
for (i = 1; i < n; i++) {
t = a[i];
for (j = i; j > 0 && t < a[j - 1]; j--) {
a[j] = a[j - 1];
}
a[j] = t;
}
}
void counting_sort(int *array, int n)
{
int i, j, k, min, max, *count;
min = max = array[0];
for(i=1; i < n; i++) {
if ( array[i] < min ) {
min = array[i];
}
else if ( array[i] > max ) {
max = array[i];
}
}
count = (int *)calloc(max - min + 1, sizeof(int));
for(i = 0, k = 0; i < n; i++) {
count[array[i] - min]++;
}
for(i = min; i <= max; i++) {
for(j = 0; j < count[i - min]; j++) {
array[k++] = i;
}
}
free(count);
}
int **allocate_dynamic_matrix(int row, int col)
{
int **ret_val;
int i;
ret_val = (int **)malloc(sizeof(int *) * row);
if (ret_val == NULL) {
perror("memory allocation failure");
exit(EXIT_FAILURE);
}
for (i = 0; i < row; ++i) {
ret_val[i] = (int *)malloc(sizeof(int) * col);
if (ret_val[i] == NULL) {
perror("memory allocation failure");
exit(EXIT_FAILURE);
}
}
return ret_val;
}
void deallocate_dynamic_matrix(int **matrix, int row)
{
int i;
for (i = 0; i < row; ++i)
free(matrix[i]);
free(matrix);
}
void SkipComments(FILE *fp)
{
int ch;
char line[100];
while ((ch = fgetc(fp)) != EOF && isspace(ch))
;
if (ch == '#') {
fgets(line, sizeof(line), fp);
SkipComments(fp);
} else
fseek(fp, -1, SEEK_CUR);
}
PGMData* readPGM(FILE *pgmFile, PGMData *data)
{
char version[3];
int i, j;
int lo, hi;
fgets(version, sizeof(version), pgmFile);
if (strcmp(version, "P5")) {
fprintf(stderr, "Wrong file type!\n");
exit(EXIT_FAILURE);
}
SkipComments(pgmFile);
fscanf(pgmFile, "%d", &(data->col));
SkipComments(pgmFile);
fscanf(pgmFile, "%d", &(data->row));
SkipComments(pgmFile);
fscanf(pgmFile, "%d", &(data->max_gray));
fgetc(pgmFile);
data->matrix = allocate_dynamic_matrix(data->row, data->col);
if (data->max_gray > 255)
for (i = 0; i < data->row; ++i)
for (j = 0; j < data->col; ++j) {
hi = fgetc(pgmFile);
lo = fgetc(pgmFile);
data->matrix[i][j] = (hi << 8) + lo;
}
else
for (i = 0; i < data->row; ++i)
for (j = 0; j < data->col; ++j) {
lo = fgetc(pgmFile);
data->matrix[i][j] = lo;
}
fclose(pgmFile);
return data;
}
/*and for writing*/
void writePGM(const char *filename, const PGMData *data)
{
FILE *pgmFile;
int i, j;
int hi, lo;
pgmFile = fopen(filename, "wb");
if (pgmFile == NULL) {
perror("cannot open file to write");
exit(EXIT_FAILURE);
}
fprintf(pgmFile, "P5 ");
fprintf(pgmFile, "%d %d ", data->col, data->row);
fprintf(pgmFile, "%d ", data->max_gray);
if (data->max_gray > 255) {
for (i = 0; i < data->row; ++i) {
for (j = 0; j < data->col; ++j) {
hi = HI(data->matrix[i][j]);
lo = LO(data->matrix[i][j]);
fputc(hi, pgmFile);
fputc(lo, pgmFile);
}
}
} else {
for (i = 0; i < data->row; ++i)
for (j = 0; j < data->col; ++j) {
lo = LO(data->matrix[i][j]);
fputc(lo, pgmFile);
}
}
fclose(pgmFile);
deallocate_dynamic_matrix(data->matrix, data->row);
}
int main ( int argc, char *argv[] )
{
PGMData *initialImage, *finalImage;
int **initialMatrix=NULL, **finalMatrix=NULL;
int n=atoi(argv[4]);
int i, j, k, l, counter;
int *buffer=NULL;
//Time count
clock_t start, end;
double cpu_time_used;
start = clock();
if ( argc != 5 ) /* argc should be 5 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen( argv[1], "r" );
/* fopen returns 0, the NULL pointer, on failure */
if ( !file )
{
printf( "Could not open file\n" );
}
else
{ initialImage = (PGMData *)malloc(1 * sizeof(PGMData));
initialImage = readPGM (file, initialImage);
initialMatrix = (int **)malloc(initialImage->row * sizeof(int*));
for(i = 0; i < initialImage->row; i++) {
initialMatrix[i] = (int *)malloc(initialImage->col * sizeof(int));
}
finalMatrix = (int **)malloc(initialImage->row * sizeof(int*));
for(i = 0; i < initialImage->row; i++) {
finalMatrix[i] = (int *)malloc(initialImage->col * sizeof(int));
}
if (initialMatrix == NULL || finalMatrix == NULL) {
puts ("Unable to allocate memory for matrix");
}
for (i = 0; i < initialImage->row; i++){
for (j = 0; j < initialImage->col; j++){
initialMatrix[i][j] = initialImage->matrix[i][j];
}
}
buffer = (int *) malloc(n * n * sizeof (int));
if (buffer == NULL) {
puts ("Unable to allocate memory for buffer");
}
for (i = 0; i < initialImage->row; i++){
for (j = 0; j < initialImage->col; j++){
counter = 0;
for (k = -(n/2); k <= n/2; k++){
for (l = -(n/2); l <= n/2; l++){
/*top left corner*/ if (i-k <= 0 && j-l <= 0) {
buffer[counter]=initialMatrix[0][0];
}
/*left side*/ else if (i-k <= 0 && j-l >= 0 && j-l <= initialImage->col-1) {
buffer[counter]=initialMatrix[0][j-l];
}
/*top side*/ else if (j-l <= 0 && i-k >= 0 && i-k <= initialImage->row-1) {
buffer[counter]=initialMatrix[i-k][0];
}
/*bottom left corner*/ else if (j-l <= 0 && i-k >= initialImage->row-1) {
buffer[counter]=initialMatrix[initialImage->row-1][0];
}
/*top right corner*/ else if (i-k <= 0 && j-l >= initialImage->col-1) {
buffer[counter]=initialMatrix[0][initialImage->col-1];
}
/*bottom side*/ else if (i-k >= initialImage->row-1 && j-l >= 0 && j-l <=initialImage->col-1) {
buffer[counter]=initialMatrix[initialImage->row-1][j-l];
}
/*right side*/ else if (j-l >= initialImage->col-1 && i-k >= 0 && i-k <=initialImage->row-1) {
buffer[counter]=initialMatrix[i-k][initialImage->col-1];
}
/*bottom right corner*/ else if (j-l >= initialImage->col-1 && i-k >= initialImage->row-1) {
buffer[counter]=initialMatrix[initialImage->row-1][initialImage->col-1];
}
/*rest*/ else {
buffer[counter]=initialMatrix[i-k][j-l];
}
counter++;
}
}
if(!strcmp(argv[3], "ins")) {
insertion_sort (buffer, n*n);
}
else if(!strcmp(argv[3], "qs")) {
quick_sort (buffer, n*n);
}
else if(!strcmp(argv[3], "cnt")) {
counting_sort (buffer, n*n);
}
else {
puts ("Unknown sorting algorithm");
}
finalMatrix[i][j] = buffer [n * n/2];
}
}
finalImage = (PGMData *)malloc(1 * sizeof(PGMData));
finalImage->col=initialImage->col;
finalImage->row=initialImage->row;
finalImage->max_gray = initialImage->max_gray;
finalImage->matrix = finalMatrix;
writePGM (argv[2], finalImage);
deallocate_dynamic_matrix(initialMatrix, initialImage->row);
deallocate_dynamic_matrix(initialImage->matrix, initialImage->row);
free(buffer);
free(initialImage);
free(finalImage);
}
}
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf ("Execution time: %f seconds\n", cpu_time_used);
}

Resources