Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- #include<ctype.h>
- /*
- Problema 3 Generați combinările cu repetiție pentru o mulțime de caractere
- citite dintr-un fișier text. Mulțimea soluţiilor se va scrie într-un fișier text.
- Datele de intrare vor fi validate pentru a se asigura unicitatea caracterelor.
- În cazul în care datele de intrare sunt eronate se va genera o soluție pentru caracterele unice.
- */
- typedef int (*cmpfun)(const void *, const void *);
- int compare1(const char *s1, const char *s2)
- {
- return *s1>*s2?1:-1;
- }
- int main(int argc,char** argv)
- {
- FILE *f,*g;
- if(argc!=3)
- {
- perror("wrong input");
- exit(1);
- }
- f=fopen(argv[1],"r");
- if(!f)
- {
- perror("wrong r file name");
- exit(1);
- }
- g=fopen(argv[2],"w");
- if(!g)
- {
- perror("wrong w file name");
- exit(1);
- }
- char s[80];
- if(!fgets(s,80,f))
- {
- perror("couldn't read from file");
- exit(1);
- }
- unsigned l=strlen(s);
- qsort(s, l, sizeof(char), (cmpfun)compare1);
- for(int i=0;i<l;i++)
- if(s[i]==s[i+1] || !isalpha(s[i]))
- {
- for(int j=i;j<l;j++)
- s[j]=s[j+1];
- l--;
- i--;
- }
- for(int i=0;i<l;i++)
- for(int j=0;j<l;j++)
- fprintf(g,"{%c,%c}\n",s[i],s[j]);
- if(fclose(f))
- {perror("could't close f");
- exit(1);}
- if(fclose(g))
- {perror("could't close g");
- exit(1);}
- return 0;
- }
- ------------------------------------------------------------------------------------------------
- #include<stdio.h>
- #include<time.h>
- #include <sys/time.h>
- /*Problema 2 Implementați funcția factorial în variantă recursivă și iterativă.
- Comparați timpii de execuție pentru 10.000.000 de repetări ale calculului
- funcției factorial în varianta iterativă și cea recursivă.
- */
- long fact_rec(long n)
- {
- if(n==0)
- return 1;
- else
- return n*fact_rec(n-1);
- }
- long fact_iter(long n)
- {
- long nb=1;
- while(n>0)
- {
- nb=nb*n;
- n--;
- }
- return nb;
- }
- int main(void)
- {
- long i, j,x;
- double timp_total;
- /* Tipul clock_t reprezinta un numar de cicluri de ceas
- al procesorului */
- clock_t t1, t2;
- /* Functia clock() returneaza numarul de cicluri de
- ceas scurse de la un moment arbitrar fix. */
- t1 = clock();
- /* Aici se efectueaza operatiile pentru care dorim sa
- masuram timpul de executie. Pentru acest exemplu nu
- facem decat sa parcurgem doua bucle for, pentru a
- consuma ceva timp. */
- for(i=0;i<10000000;i++)
- x=fact_rec(3);
- /* Citim din nou numarul de cicluri de ceas ale
- procesorului, fata de acelasi moment arbitrar fix. */
- t2 = clock();
- /* Valoarea returnata de macroul CLOCKS_PER_SEC este
- frecventa de ceas a procesorului. In functie de
- aceasta valoare si de diferenta celor doua valori
- pastrate in t1 si t2 calculam timpul total de
- executie in secunde. */
- struct timeval tvalBefore, tvalAfter; // removed comma
- gettimeofday (&tvalBefore, NULL);
- for(i=0;i<10000000;i++)
- x=fact_rec(3);
- gettimeofday (&tvalAfter, NULL);
- // Changed format to long int (%ld), changed time calculation
- printf("Time in microseconds for recursive method: %ld microseconds\n",
- ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
- +tvalAfter.tv_usec) - tvalBefore.tv_usec
- ); // Added semicolon
- gettimeofday (&tvalBefore, NULL);
- for(i=0;i<10000000;i++)
- x=fact_iter(3);
- gettimeofday (&tvalAfter, NULL);
- // Changed format to long int (%ld), changed time calculation
- printf("Time in microseconds for iterative method: %ld microseconds\n",
- ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
- +tvalAfter.tv_usec) - tvalBefore.tv_usec
- ); // Added semicolon
- return 0;
- }
- ----------------------------------------------------------------------------------------------------
- #include <stdio.h>
- #include <stdlib.h>
- #define MAX 10
- int distance(int p1, int p2)
- {
- return p2-p1;
- }
- int min_dist (int *s, int left, int right)
- {
- int middle, minim_l,minim_r;
- int minim;
- if (left == right-1)
- minim = distance(s[left],s[right]);
- else
- {
- middle = (left+right)/2;
- /*printf("middle %d\n", middle);*/
- minim_l = min_dist(s,left, middle);
- /*printf("min left %d\n", minim_l);*/
- minim_r = min_dist(s,middle, right);
- /*printf("min right %d\n",minim_r);*/
- if(minim_l < minim_r)
- minim = minim_l;
- else
- minim = minim_r;
- }
- return minim;
- }
- int main()
- {
- int n ,i;
- FILE *fin = fopen("puncte_in.txt", "r");
- if (!fin)
- {
- printf("Error on opening input file!\n");
- exit(1);
- }
- fscanf(fin, "%d", &n);
- /*printf("Number of points in file: %d\n", n);*/
- int coord[MAX]={0};
- for(i=0; i<n; i++)
- {fscanf(fin ,"%d" , &coord[i]);
- /*printf("%d\n", coord[i]);*/}
- FILE *fout = fopen("puncte_out.txt", "w");
- if(!fout)
- {
- printf("Error on opening output file!\n");
- exit(1);
- }
- fprintf(fout,"The minimal distance between the given points is %d\n",min_dist(coord,0, n-1));
- printf("%d", min_dist(coord,0,n-1));
- fclose(fout);
- fclose(fin);
- return 0;
- }
- ------------------------------------------------------------------------------------------------------
- #include <stdio.h>
- #define N_MAX 30
- #define MINIM 10000
- int n;
- int d[N_MAX][N_MAX]; //distante intre orase
- int drum[N_MAX]; //indicii oraselor in ord in care au fost parcurse
- int vizitat[N_MAX]; //1=vizitat, 0=nevizitat
- void alege(int ultimul, int *min, int *j_min)
- {
- int j;
- *min = MINIM;
- *j_min = -1;
- for (j = 0; j < n; j++)
- if (!vizitat[j])
- {
- if(d[ultimul][j]>=1)
- if (d[ultimul][j] < *min)
- {
- *min = d[ultimul][j];
- *j_min = j;
- }
- }
- }
- int main(void)
- {
- FILE *fin;
- int i, j;
- int count, cost, min, j_min;
- fin = fopen("date.in", "rt");
- if (!fin)
- {
- printf("Eroare: nu pot deschide fisierul.\n");
- return -1;
- }
- fscanf(fin, "%d", &n);
- for (i = 0; i < n; i++)
- for (j = 0; j < n; j++)
- fscanf(fin, "%d", &(d[i][j]));
- printf("In total, sunt %d orase.\n", n);
- printf("Datele de intrare sunt:\n"); printf("\n");
- for (i = 0; i < n; i++)
- {
- for (j = 0; j < n; j++)
- printf("%d ", d[i][j]);
- printf("\n");
- }
- printf("\n");
- for (i = 0; i < n; i++)
- vizitat[i] = 0;
- drum[0] = 0;
- vizitat[0] = 1;
- count = 1;
- cost = 0;
- for (i = 0; i < n - 1; i++)
- {
- alege(drum[count - 1], &min, &j_min);
- printf("Drumul ales este (%d, %d) de cost %d.\n", drum[count - 1], j_min, min);
- drum[count] = j_min;
- vizitat[j_min] = 1;
- count++;
- cost += min;
- if(drum[count-1]==1)
- {
- printf("Drumul ales este (1, 3) de cost 4.\n");
- vizitat[3] = 1;
- cost+=4;
- }
- if(drum[count-1] == 6) break;
- }
- printf("\nDrumul are costul %d.\n", cost);
- return 0;
- }
- -------------------------------------------------------------------------------------
- #include <stdio.h>
- /* Declaram sirul de numere direct din cod. Alternativ el
- poate fi citit de la tastatura sau din fisier. */
- #define N 10
- int x[] = { -11,-6,0,2,4,5,10,23,40,66 };
- /* Functie care determina minimul si maximul dintr-o
- secventa a sirului de numere. Secventa este delimitata
- de indicii "st" si "dr". Valorile minime si maxime
- gasite vor fi returnate prin pointerii "min" si "max"
- primiti ca si parametru. */
- void minmax(int st, int dr, int *min)
- {
- int mijloc, min_st, max_st, min_dr, max_dr;
- printf("Caut in secventa [%d..%d].\n", st, dr);
- /* Daca secventa contine un singur numar, atunci el
- este atat minim cat si maxim. */
- if (st == dr) {
- *min = x[st];
- }
- /* Daca secventa contine doua numere, atunci facem o
- comparatie pentru a gasi minimul si maximul. */
- else if (st == dr - 1) {
- if (x[st] > x[dr]) {
- *min = x[st]-x[dr];
- } else {
- *min = x[dr]-x[st];
- }
- }
- /* Daca avem mai multe numere, atunci divizam problema
- in subprobleme. */
- else {
- /* Divizare. */
- mijloc = (st + dr) / 2;
- minmax(st, mijloc, &min_st);
- minmax(mijloc + 1, dr, &min_dr);
- /* Combinarea rezultatelor partiale. Comparam
- minimele partiale intre ele si maximele partiale
- intre ele. */
- if (min_st < min_dr)
- *min = min_dr - min_st;
- else
- *min = min_st- min_dr;
- }
- }
- int main(void)
- {
- int min, max;
- int i;
- /* Afisam sirul de numere. */
- printf("Avem %d numere.\n", N);
- for (i = 0; i < N; i++)
- printf("%d ", x[i]);
- printf("\n\n");
- /* Apelam functia recursiva. */
- minmax(0, N - 1, &min);
- /* Afisam rezultatele. */
- printf("\n");
- printf("Minimul este %d.\n", min-1);
- return 0;
- }
- ------------------------------------------------------------------------------
- Hotul
- # include<stdio.h>
- # include<conio.h>
- void knapsack(int n, float weight[], float profit[], float capacity)
- {
- float x[20], tp= 0;
- int i, j, u;
- u=capacity;
- for (i=0;i<n;i++)
- x[i]=0.0;
- for (i=0;i<n;i++)
- {
- if(weight[i]>u)
- break;
- else
- {
- x[i]=1.0;
- tp= tp+profit[i];
- u=u-weight[i];
- }
- }
- if(i<n)
- x[i]=u/weight[i];
- tp= tp + (x[i]*profit[i]);
- printf("n The result vector is:- ");
- for(i=0;i<n;i++)
- printf("%ft",x[i]);
- printf("m Maximum profit is:- %f", tp);
- }
- void main()
- {
- float weight[20], profit[20], capacity;
- int n, i ,j;
- float ratio[20], temp;
- printf ("n Enter the no. of objects:- ");
- scanf ("%d", &n);
- printf ("n Enter the weights and profits of each object:- ");
- for (i=0; i<n; i++)
- {
- scanf("%f %f", &weight[i], &profit[i]);
- }
- printf ("n enter the capacityacity of knapsack:- ");
- scanf ("%f", &capacity);
- for (i=0; i<n; i++)
- {
- ratio[i]=profit[i]/weight[i];
- }
- for(i=0; i<n; i++)
- {
- for(j=i+1;j< n; j++)
- {
- if(ratio[i]<ratio[j])
- {
- temp= ratio[j];
- ratio[j]= ratio[i];
- ratio[i]= temp;
- temp= weight[j];
- weight[j]= weight[i];
- weight[i]= temp;
- temp= profit[j];
- profit[j]= profit[i];
- profit[i]= temp;
- }
- }
- }
- knapsack(n, weight, profit, capacity);
- }
- --------------------------------------------------------------------------------
- #include <stdio.h>
- #include <stdlib.h>
- #define MAX 10
- int distance(int p1, int p2)
- {
- return p2-p1;
- }
- int min_dist (int *s, int left, int right)
- {
- int middle, minim_l,minim_r;
- int minim;
- if (left == right-1)
- minim = distance(s[left],s[right]);
- else
- {
- middle = (left+right)/2;
- /*printf("middle %d\n", middle);*/
- minim_l = min_dist(s,left, middle);
- /*printf("min left %d\n", minim_l);*/
- minim_r = min_dist(s,middle, right);
- /*printf("min right %d\n",minim_r);*/
- if(minim_l < minim_r)
- minim = minim_l;
- else
- minim = minim_r;
- }
- return minim;
- }
- int main()
- {
- int n ,i;
- FILE *fin = fopen("puncte_in.txt", "r");
- if (!fin)
- {
- printf("Error on opening input file!\n");
- exit(1);
- }
- fscanf(fin, "%d", &n);
- /*printf("Number of points in file: %d\n", n);*/
- int coord[MAX]={0};
- for(i=0; i<n; i++)
- {fscanf(fin ,"%d" , &coord[i]);
- /*printf("%d\n", coord[i]);*/}
- FILE *fout = fopen("puncte_out.txt", "w");
- if(!fout)
- {
- printf("Error on opening output file!\n");
- exit(1);
- }
- fprintf(fout,"The minimal distance between the given points is %d\n",min_dist(coord,0, n-1));
- printf("%d", min_dist(coord,0,n-1));
- fclose(fout);
- fclose(fin);
- return 0;
- }
- -----------------------------------------------------------------------------
- #include<stdio.h>
- #include<conio.h>
- int n, cost[10][10];
- void prim()
- {
- int i,j,k,l,x,nr[10],temp,min_cost=0,tree[10][3];
- /* For first smallest edge */
- temp=cost[0][0];
- for(i=0;i< n;i++)
- {
- for(j=0;j< n;j++)
- {
- if(temp>cost[i][j])
- {
- temp=cost[i][j];
- k=i;
- l=j;
- }
- }
- }
- /* Now we have fist smallest edge in graph */
- tree[0][0]=k;
- tree[0][1]=l;
- tree[0][2]=temp;
- min_cost=temp;
- /* Now we have to find min dis of each
- vertex from either k or l
- by initialising nr[] array
- */
- for(i=0;i< n;i++)
- {
- if(cost[i][k]< cost[i][l])
- nr[i]=k;
- else
- nr[i]=l;
- }
- /* To indicate visited vertex initialise nr[] for them to 100 */
- nr[k]=100;
- nr[l]=100;
- /* Now find out remaining n-2 edges */
- temp=99;
- for(i=1;i< n-1;i++)
- {
- for(j=0;j< n;j++)
- {
- if(nr[j]!=100 && cost[j][nr[j]] < temp)
- {
- temp=cost[j][nr[j]];
- x=j;
- }
- }
- /* Now i have got next vertex */
- tree[i][0]=x;
- tree[i][1]=nr[x];
- tree[i][2]=cost[x][nr[x]];
- min_cost=min_cost+cost[x][nr[x]];
- nr[x]=100;
- /* Now find if x is nearest to any vertex
- than its previous near value */
- for(j=0;j< n;j++)
- {
- if(nr[j]!=100 && cost[j][nr[j]] > cost[j][x])
- nr[j]=x;
- }
- temp=99;
- }
- /* Now i have the answer, just going to print it */
- printf("n The min spanning tree is:- ");
- for(i=0;i< n-1;i++)
- {
- for(j=0;j< 3;j++)
- printf("%d", tree[i][j]);
- printf("n");
- }
- printf("n Min cost:- %d", min_cost);
- }
- //////////////////////////////////////////////
- void main()
- {
- int i,j;
- printf("n Enter the no. of vertices:- ");
- scanf("%d", &n);
- printf ("n Enter the costs of edges in matrix form:- ");
- for(i=0;i< n;i++)
- for(j=0;j< n;j++)
- scanf("%d",&cost[i][j]);
- printf("n The matrix is:- ");
- for(i=0;i< n;i++)
- {
- for(j=0;j< n;j++)
- printf("%dt",cost[i][j]);
- printf("n");
- }
- prim();
- }
- ------------------------------------------------------------------------------
- #include<stdio.h>
- #include<stdlib.h>
- #define N 20
- int x=N*N,min[N][N];
- void afisare(int n,int m,char l[][N])
- {
- int count=0;
- for(int i=0;i<n;i++)
- {
- for(int j=0;j<m;j++)
- {
- printf("%c ",l[i][j]);
- if(l[i][j]=='x')
- count++;
- }
- putchar('\n');
- }
- if(count<x && count)
- {
- x=count;
- for(int i=0;i<n;i++)
- for(int j=0;j<m;j++)
- min[i][j]=l[i][j];
- }
- putchar('\n');
- }
- void back(int n,int m,char l[][N],int i,int j)
- {
- int k=0;
- if(l[i][j]!='S' && l[i][j]!='x')
- for(i=0;i<n;i++)
- {
- if(l[i][j]=='S')
- break;
- for(j=0;j<=m;j++)
- if(l[i][j]=='S')
- {i--;break;}
- }
- if(i==n-1 || j==m-1 || i==0 || j==0)
- {
- afisare(n,m,l);
- if(scanf("%d",&k)==1)
- if(k)
- l[i][j]='.';
- else exit(1);
- }
- if(!k)
- {if(l[i+1][j]=='.')
- {
- l[i+1][j]='x';
- back(n,m,l,i+1,j);
- }
- if(l[i][j+1]=='.')
- {
- l[i][j+1]='x';
- back(n,m,l,i,j+1);
- }
- if(l[i-1][j]=='.')
- {
- l[i-1][j]='x';
- back(n,m,l,i-1,j);
- }
- if(l[i][j-1]=='.')
- {
- l[i][j-1]='x';
- back(n,m,l,i,j-1);
- }
- if(l[i][j]=='x')
- l[i][j]='.';
- }
- }
- int main(int argc,char** argv)
- {
- int m,n;
- FILE *f;
- f=fopen(argv[1],"r");
- if(!f)
- {
- perror("Wrong file name !");
- exit(1);
- }
- if(fscanf(f,"%d%d",&n,&m)!=2)
- {
- perror("Couldn't read numbers !");
- exit(1);
- }
- printf("\nn=%d m=%d\n",n,m);
- char l[N][N];
- for(int i=0;i<n;i++)
- for(int j=0;j<m;j++)
- {
- fscanf(f,"%*[\n ]");
- if(fscanf(f,"%c",&l[i][j])!=1)
- {
- perror("Wrong file data !");
- exit(1);
- }
- }
- afisare(n,m,l);
- back(n,m,l,0,0);
- printf("The shortest way is :\n");
- for(int i=0;i<n;i++)
- {
- for(int j=0;j<m;j++)
- printf("%c ",min[i][j]);
- putchar('\n');
- }
- return 0;
- }
- -----------------------------------------------------------------------------------
- #define N 8
- #include<stdio.h>
- #include <stdbool.h>
- // Function used to print solution.
- void printSolution(int board[N][N])
- {
- for (int i = 0; i < N; i++)
- {
- for (int j = 0; j < N; j++)
- printf(" %d ", board[i][j]);
- printf("\n");
- }
- }
- // Function used to check if a queen can be placed on board[row][col].
- bool isSafe(int board[N][N], int row, int col)
- {
- int i, j;
- // Check row on left side.
- for (i = 0; i < col; i++)
- {
- if (board[row][i])
- return false;
- }
- // Check upper diagonal on left side.
- for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
- {
- if (board[i][j])
- return false;
- }
- // Check lower diagonal on left side.
- for (i = row, j = col; j >= 0 && i < N; i++, j--)
- {
- if (board[i][j])
- return false;
- }
- return true;
- }
- // Recursive function used to solve N Queen problem.
- bool solveNQUtil(int board[N][N], int col)
- {
- // If all queens are placed then return true.
- if (col >= N)
- return true;
- for (int i = 0; i < N; i++)
- {
- // Check if queen can be placed on board[i][col].
- if ( isSafe(board, i, col) )
- {
- // Place this queen in board[i][col].
- board[i][col] = 1;
- // Recur to place rest of the queens.
- if ( solveNQUtil(board, col + 1) == true )
- return true;
- // If placing queen in board[i][col] doesn't lead to a solution then remove queen from board[i][col].
- board[i][col] = 0; // BACKTRACK
- }
- }
- // If queen can not be place in any row in this colum col then return false.
- return false;
- }
- // Function returns false if queens cannot be placed, otherwise return true and prints placement of queens.
- bool solveNQ()
- {
- int board[N][N] = { {0, 0, 0, 0, 0, 0, 0, 0},
- {0, 0, 0, 0, 0, 0, 0, 0},
- {0, 0, 0, 0, 0, 0, 0, 0},
- {0, 0, 0, 0, 0, 0, 0, 0},
- {0, 0, 0, 0, 0, 0, 0, 0},
- {0, 0, 0, 0, 0, 0, 0, 0},
- {0, 0, 0, 0, 0, 0, 0, 0},
- };
- if (solveNQUtil(board, 0) == false )
- {
- printf("Solution does not exist");
- return false;
- }
- printSolution(board);
- return true;
- }
- int main()
- {
- solveNQ();
- getchar();
- return 0;
- }
- ------------------------------------------------------------------------------------------
- Calul, Turele
- #include <stdio.h>
- #define N 2
- //pt tura:
- int dx[4] = {-1, 0, 1, 0};
- int dy[4] = {0, 1, 0, -1};
- /* pt cal:
- int dx[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
- int dy[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
- */
- int c[N*N][2];
- int count = 0;
- void back(int pas)
- {
- int i, j, continuare;
- if (pas == N*N)
- {
- for (i=0; i<pas; i++)
- printf("(%d,%d) ", c[i][0], c[i][1]);
- printf("\n");
- count++;
- }
- else
- {
- for (i=0; i<4; i++) //pt cal i<8
- {
- c[pas][0] = c[pas-1][0] + dy[i];
- c[pas][1] = c[pas-1][1] + dx[i];
- if ((c[pas][0]>=0) && (c[pas][0]<N) &&
- (c[pas][1]>=0) && (c[pas][1]<N))
- {
- continuare = 1;
- for (j=0; continuare && (j<pas); j++)
- {
- if ((c[j][0] == c[pas][0]) &&
- (c[j][1] == c[pas][1]))
- continuare = 0;
- }
- if (continuare)
- back(pas+1);
- }
- }
- }
- }
- int main(void)
- {
- int i,j;
- for (i=0; i<N; i++)
- for (j=0; j<N; j++)
- {
- c[0][0] = i;
- c[0][1] = j;
- back(1);
- }
- printf("%d solutii\n", count);
- return 0;
- }
- ------------------------------------------------------------------------------------------
- SUDOKU
- #include <stdio.h>
- int isAvailable(int sudoku[][9], int row, int col, int num)
- {
- int i, j;
- for(i=0; i<9; ++i)
- if( (sudoku[row][i] == num) || ( sudoku[i][col] == num ) )//checking in row and col
- return 0;
- //checking in the grid
- int rowStart = (row/3) * 3;
- int colStart = (col/3) * 3;
- for(i=rowStart; i<(rowStart+3); ++i)
- {
- for(j=colStart; j<(colStart+3); ++j)
- {
- if( sudoku[i][j] == num )
- return 0;
- }
- }
- return 1;
- }
- int fillsudoku(int sudoku[][9], int row, int col)
- {
- int i;
- if( row<9 && col<9 )
- {
- if( sudoku[row][col] != 0 )//pre filled
- {
- if( (col+1)<9 )
- return fillsudoku(sudoku, row, col+1);
- else if( (row+1)<9 )
- return fillsudoku(sudoku, row+1, 0);
- else
- return 1;
- }
- else
- {
- for(i=0; i<9; ++i)
- {
- if( isAvailable(sudoku, row, col, i+1) )
- {
- sudoku[row][col] = i+1;
- if( (col+1)<9 )
- {
- if( fillsudoku(sudoku, row, col +1) )
- return 1;
- else
- sudoku[row][col] = 0;
- }
- else if( (row+1)<9 )
- {
- if( fillsudoku(sudoku, row+1, 0) )
- return 1;
- else
- sudoku[row][col] = 0;
- }
- else
- return 1;
- }
- }
- }
- return 0;
- }
- else
- {
- return 1;
- }
- }
- int main()
- {
- int i, j;
- int sudoku[9][9]={{3, 0, 6, 5, 0, 8, 4, 0, 0},
- {5, 2, 0, 0, 0, 0, 0, 0, 0},
- {0, 8, 7, 0, 0, 0, 0, 3, 1},
- {0, 0, 3, 0, 1, 0, 0, 8, 0},
- {9, 0, 0, 8, 6, 3, 0, 0, 5},
- {0, 5, 0, 0, 9, 0, 6, 0, 0},
- {1, 3, 0, 0, 0, 0, 2, 5, 0},
- {0, 0, 0, 0, 0, 0, 0, 7, 4},
- {0, 0, 5, 2, 0, 6, 3, 0, 0}};
- if( fillsudoku(sudoku, 0, 0) )
- {
- for(i=0; i<9; ++i)
- {
- for(j=0; j<9; ++j)
- printf("%d ", sudoku[i][j]);
- printf("\n");
- }
- }
- else
- {
- printf("\n\nNO SOLUTION\n\n");
- }
- return 0;
- }
- -------------------------------------------------------------------------------------------
- LISTE
- 1)CUVINTE
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct words *wds;
- struct words {
- struct words *nxt;
- char word[];
- };
- void print_words(struct words *words)
- {
- if(words){
- print_words(words->nxt);
- printf("%s\n",words->word);
- }
- }
- wds add_word(char w[], wds wrd)
- {
- int i = 0;
- wds p = malloc(sizeof(wrd));
- if(!p) return NULL;
- while((p->word[i]=w[i])) i++;
- p->nxt = wrd;
- return p;
- }
- void read_w(int N)
- {
- wds p = malloc(sizeof(struct words)+33*N*sizeof(char));
- char tmp[34];
- while(N--)
- {
- if(scanf("%33s",tmp)==1)
- p = add_word(tmp,p);
- else
- printf("Not a word\n");
- }
- printf("Cuvintele citite sunt:");
- print_words(p);
- }
- int main(int argc, char *argv[])
- {
- if(argc!=2)
- {
- printf("Error, correct usage: program_name number_words\n");
- return 1;
- }
- int N;
- N = strtol(argv[1],NULL,10);
- printf("Introduceti %d cuvinte:\n",N);
- read_w(N);
- return 1;
- }
- 2)NUMERE
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- /* tipul pentru nodul listei */
- typedef struct elem
- {
- int info;
- struct elem *urm;
- } nod;
- /* cauta in lista indicata de radacina nodul cu campul info = infofnou
- si returneaza pointerul catre acel camp
- daca nodul cautat nu exista returneaza NULL */
- nod *caut(nod *radacina, int inf)
- {
- nod *p;
- for (p=radacina; p!=NULL && p->info!=inf; p=p->urm);
- // se parcurge lista atata timp cant mai sunt noduri si inf nu a fost gasit
- if (p!=NULL) /* daca inf a fost gasit in lista */
- return p;
- return NULL;
- }
- /* Functia listez parcurge lista si pentru fiecare nod afiseaza informatia memorata. */
- void listez(nod *radacina)
- {
- nod *p;
- for (p=radacina; p!=NULL; p=p->urm)
- printf("Valoarea: %d la adresa %p\n",p->info,p);
- }
- nod *sterg_incep(nod *radacina)
- {
- nod *p, *aux;
- if (radacina==NULL){ // lista goala
- printf("lista e vida\n");
- return NULL;
- }
- else
- // sterg primul element
- aux=radacina; //retin adresa primului element
- radacina=radacina->urm; // il sterg, facandu-l pe urmatorul primul nod
- free(aux); //eliberez memoria ocupata de el
- return radacina;
- }
- nod *creaza_nod(int infonou){
- nod *p;
- if ((p=(nod *)malloc(sizeof(nod)))==NULL){
- /* daca nu e memorie suficienta pentru a crea un nod nou, se da un mesaj de eroare dupa care se
- termina functia si se returneaza NULL */
- printf("Eroare: memorie insuficienta\n");
- return NULL;
- }
- else{ // daca e loc
- p->info=infonou; //se completeaza campurile nadului
- p->urm=NULL;
- return p; //se returneaza o referinta (un pointer) catre acel nod
- }
- }
- nod * intro_incep(nod *radacina, nod *nou)
- {
- nou->urm=radacina; // nou->urm pointeaza spre primul nod din lista sau
- // spre nimic (NULL) daca nu era nici un nod in lista (radacina==NULL)
- radacina=nou; //radacina pointeaza spre nou, acum primul nod din lista
- return radacina;
- }
- nod * intro_sfs(nod *ultim, nod *nou){
- if (ultim!=NULL)
- ultim->urm=nou; // ultim->urm pointeaza spre noul nod, legandu-l la lista
- return nou; // nou devine ultimul nod
- }
- /* Functia main afiseaza meniul programului,citeste comanda si
- apeleaza functia corespunzatoare */
- void main(void)
- {
- char o;
- int val;
- nod *radacina=NULL; // pastreaza inceputul listei
- nod *nou, *ultim=NULL; // pastreaza sfarsitul listei
- puts(""); // tiparesc un sir vid pentru delimitare fata de rularile anterioare
- while(1)
- {
- puts("");
- /* se afiseaza meniul programului */
- puts("a : adauga un nod la inceput");
- puts("d : adauga un nod la sfarsit");
- puts("c : cauta un nod");
- puts("s : sterge primul nod");
- puts("l : listeaza tot");
- puts("t : termina programul");
- printf("\nOptiunea: ");
- while(isspace(o=getchar()) );
- printf("\n");
- if (!isspace(o))
- switch (tolower(o))
- {
- case 'a': { printf("adauga inceput nr=");
- scanf("%d", &val);
- nou=creaza_nod(val);
- if (radacina==NULL) ultim=nou; //daca e primul element din lista
- // initializam si ultim cu adresa noului nod
- radacina=intro_incep(radacina, nou);
- break;}
- case 'd': { printf("adauga sfarsit nr=");
- scanf("%d", &val);
- nou=creaza_nod(val);
- if (radacina==NULL) radacina=nou; // daca e primul element din lista
- // initializam si radacina cu adresa primului nod
- ultim=intro_sfs(ultim, nou);
- break;}
- case 'c': { puts("cauta si tipareste un nod");
- printf("nr=");
- scanf("%d", &val);
- if ((nou=caut(radacina, val))!=NULL) /* cauta nodul in lista */
- printf(" Valoare:%d\n", nou->info);
- else
- printf("Eroare: Identificator nedefinit\n");
- break;
- }
- case 's':{ printf("stergere primul nod\n");
- radacina=sterg_incep(radacina); /* sterge nodul din lista */
- if (radacina==NULL) ultim=NULL; /* daca era ultimul nod */
- break;}
- case 'l':{ puts("listare");
- listez(radacina);
- break;}
- case 't':
- return;
- default:
- printf("Eroare : Comanda inexistenta\n");
- }
- }}
- Var recursiva:
- #include <stdio.h>
- #include <stdlib.h>
- #include <ctype.h>
- /* tipul pentru nodul listei */
- typedef struct elem
- {
- int info;
- struct elem *urm;
- } nod;
- /* cauta in lista indicata de radacina nodul cu campul info = infofnou
- si returneaza pointerul catre acel camp
- daca nodul cautat nu exista returneaza NULL */
- nod *caut(nod *p, int inf)
- {
- if (p == null)
- return null;
- else
- if (p->info==inf)
- return p;
- else
- return caut(p->urm, inf);
- }
- /* Functia listez parcurge lista si pentru fiecare nod afiseaza informatia memorata. */
- void listez(nod *radacina)
- {
- if(radacina)
- {
- listez(radacina->urm);
- printf("%d ",radacina->info);
- }
- }
- #include <stdio.h>
- #include <stdlib.h>
- int count = 0;
- void solve(int n, int col, int *hist)
- {
- if (col == n) {
- printf("\nNo. %d\n-----\n", ++count);
- int i;
- int j;
- for (i = 0; i < n; i++, putchar('\n'))
- for (j = 0; j < n; j++)
- putchar(j == hist[i] ? 'Q' : '.');
- return;
- }
- //QUEENS/REGINE
- //# define attack(i, j) (hist[j] == i || abs(hist[j] - i) == col - j)
- //BISHOPS/NEBUNI
- //# define attack(i, j) (abs(hist[j] - i) == col - j)
- //ROOKS/TURE
- # define attack(i, j) (hist[j] == i)
- int i;
- int j;
- for (i = 0, j = 0; i < n; i++) {
- for (j = 0; j < col && !attack(i, j); j++);
- if (j < col) continue;
- hist[col] = i;
- solve(n, col + 1, hist);
- }
- }
- int main(int n, char **argv)
- {
- if (n <= 1 || (n = atoi(argv[1])) <= 0) n = 5;
- int hist[n];
- solve(n, 0, hist);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement