Advertisement
alexarcan

descoslaimprim

Jun 19th, 2014
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 29.62 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4. #include<ctype.h>
  5. /*
  6. Problema 3 Generați combinările cu repetiție pentru o mulțime de caractere
  7. citite dintr-un fișier text. Mulțimea soluţiilor se va scrie într-un fișier text.
  8. Datele de intrare vor fi validate pentru a se asigura unicitatea caracterelor.
  9. În cazul în care datele de intrare sunt eronate se va genera o soluție pentru caracterele unice.
  10. */
  11. typedef int (*cmpfun)(const void *, const void *);
  12. int compare1(const char *s1, const char *s2)
  13. {
  14. return *s1>*s2?1:-1;
  15. }
  16.  
  17.  
  18. int main(int argc,char** argv)
  19. {
  20. FILE *f,*g;
  21. if(argc!=3)
  22. {
  23. perror("wrong input");
  24. exit(1);
  25. }
  26. f=fopen(argv[1],"r");
  27. if(!f)
  28. {
  29. perror("wrong r file name");
  30. exit(1);
  31. }
  32. g=fopen(argv[2],"w");
  33. if(!g)
  34. {
  35. perror("wrong w file name");
  36. exit(1);
  37. }
  38. char s[80];
  39. if(!fgets(s,80,f))
  40. {
  41. perror("couldn't read from file");
  42. exit(1);
  43. }
  44. unsigned l=strlen(s);
  45. qsort(s, l, sizeof(char), (cmpfun)compare1);
  46. for(int i=0;i<l;i++)
  47. if(s[i]==s[i+1] || !isalpha(s[i]))
  48. {
  49. for(int j=i;j<l;j++)
  50. s[j]=s[j+1];
  51. l--;
  52. i--;
  53. }
  54. for(int i=0;i<l;i++)
  55. for(int j=0;j<l;j++)
  56. fprintf(g,"{%c,%c}\n",s[i],s[j]);
  57. if(fclose(f))
  58. {perror("could't close f");
  59. exit(1);}
  60.  
  61. if(fclose(g))
  62. {perror("could't close g");
  63. exit(1);}
  64.  
  65. return 0;
  66. }
  67. ------------------------------------------------------------------------------------------------
  68. #include<stdio.h>
  69. #include<time.h>
  70. #include <sys/time.h>
  71. /*Problema 2 Implementați funcția factorial în variantă recursivă și iterativă.
  72. Comparați timpii de execuție pentru 10.000.000 de repetări ale calculului
  73. funcției factorial în varianta iterativă și cea recursivă.
  74. */
  75.  
  76. long fact_rec(long n)
  77. {
  78.  
  79. if(n==0)
  80. return 1;
  81.  
  82.  
  83. else
  84. return n*fact_rec(n-1);
  85.  
  86.  
  87. }
  88.  
  89. long fact_iter(long n)
  90. {
  91. long nb=1;
  92. while(n>0)
  93. {
  94. nb=nb*n;
  95. n--;
  96. }
  97. return nb;
  98. }
  99.  
  100. int main(void)
  101. {
  102.  
  103.  
  104. long i, j,x;
  105. double timp_total;
  106.  
  107. /* Tipul clock_t reprezinta un numar de cicluri de ceas
  108. al procesorului */
  109. clock_t t1, t2;
  110.  
  111. /* Functia clock() returneaza numarul de cicluri de
  112. ceas scurse de la un moment arbitrar fix. */
  113. t1 = clock();
  114.  
  115. /* Aici se efectueaza operatiile pentru care dorim sa
  116. masuram timpul de executie. Pentru acest exemplu nu
  117. facem decat sa parcurgem doua bucle for, pentru a
  118. consuma ceva timp. */
  119. for(i=0;i<10000000;i++)
  120. x=fact_rec(3);
  121.  
  122.  
  123. /* Citim din nou numarul de cicluri de ceas ale
  124. procesorului, fata de acelasi moment arbitrar fix. */
  125. t2 = clock();
  126.  
  127. /* Valoarea returnata de macroul CLOCKS_PER_SEC este
  128. frecventa de ceas a procesorului. In functie de
  129. aceasta valoare si de diferenta celor doua valori
  130. pastrate in t1 si t2 calculam timpul total de
  131. executie in secunde. */
  132.  
  133.  
  134. struct timeval tvalBefore, tvalAfter; // removed comma
  135.  
  136. gettimeofday (&tvalBefore, NULL);
  137. for(i=0;i<10000000;i++)
  138. x=fact_rec(3);
  139.  
  140. gettimeofday (&tvalAfter, NULL);
  141.  
  142. // Changed format to long int (%ld), changed time calculation
  143.  
  144. printf("Time in microseconds for recursive method: %ld microseconds\n",
  145. ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
  146. +tvalAfter.tv_usec) - tvalBefore.tv_usec
  147. ); // Added semicolon
  148.  
  149.  
  150. gettimeofday (&tvalBefore, NULL);
  151. for(i=0;i<10000000;i++)
  152. x=fact_iter(3);
  153.  
  154. gettimeofday (&tvalAfter, NULL);
  155.  
  156. // Changed format to long int (%ld), changed time calculation
  157.  
  158. printf("Time in microseconds for iterative method: %ld microseconds\n",
  159. ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
  160. +tvalAfter.tv_usec) - tvalBefore.tv_usec
  161. ); // Added semicolon
  162.  
  163. return 0;
  164. }
  165. ----------------------------------------------------------------------------------------------------
  166. #include <stdio.h>
  167. #include <stdlib.h>
  168.  
  169. #define MAX 10
  170.  
  171. int distance(int p1, int p2)
  172. {
  173. return p2-p1;
  174. }
  175.  
  176. int min_dist (int *s, int left, int right)
  177. {
  178. int middle, minim_l,minim_r;
  179. int minim;
  180.  
  181. if (left == right-1)
  182. minim = distance(s[left],s[right]);
  183. else
  184. {
  185. middle = (left+right)/2;
  186. /*printf("middle %d\n", middle);*/
  187.  
  188. minim_l = min_dist(s,left, middle);
  189. /*printf("min left %d\n", minim_l);*/
  190.  
  191. minim_r = min_dist(s,middle, right);
  192. /*printf("min right %d\n",minim_r);*/
  193.  
  194. if(minim_l < minim_r)
  195. minim = minim_l;
  196. else
  197. minim = minim_r;
  198. }
  199.  
  200. return minim;
  201. }
  202.  
  203.  
  204. int main()
  205. {
  206. int n ,i;
  207.  
  208. FILE *fin = fopen("puncte_in.txt", "r");
  209.  
  210. if (!fin)
  211. {
  212. printf("Error on opening input file!\n");
  213. exit(1);
  214. }
  215.  
  216. fscanf(fin, "%d", &n);
  217. /*printf("Number of points in file: %d\n", n);*/
  218.  
  219. int coord[MAX]={0};
  220.  
  221. for(i=0; i<n; i++)
  222. {fscanf(fin ,"%d" , &coord[i]);
  223. /*printf("%d\n", coord[i]);*/}
  224.  
  225. FILE *fout = fopen("puncte_out.txt", "w");
  226.  
  227. if(!fout)
  228. {
  229. printf("Error on opening output file!\n");
  230. exit(1);
  231. }
  232.  
  233. fprintf(fout,"The minimal distance between the given points is %d\n",min_dist(coord,0, n-1));
  234. printf("%d", min_dist(coord,0,n-1));
  235.  
  236. fclose(fout);
  237. fclose(fin);
  238. return 0;
  239. }
  240.  
  241. ------------------------------------------------------------------------------------------------------
  242. #include <stdio.h>
  243. #define N_MAX 30
  244. #define MINIM 10000
  245. int n;
  246. int d[N_MAX][N_MAX]; //distante intre orase
  247. int drum[N_MAX]; //indicii oraselor in ord in care au fost parcurse
  248. int vizitat[N_MAX]; //1=vizitat, 0=nevizitat
  249. void alege(int ultimul, int *min, int *j_min)
  250. {
  251. int j;
  252. *min = MINIM;
  253. *j_min = -1;
  254. for (j = 0; j < n; j++)
  255. if (!vizitat[j])
  256. {
  257. if(d[ultimul][j]>=1)
  258. if (d[ultimul][j] < *min)
  259. {
  260. *min = d[ultimul][j];
  261. *j_min = j;
  262. }
  263. }
  264. }
  265.  
  266. int main(void)
  267. {
  268. FILE *fin;
  269. int i, j;
  270. int count, cost, min, j_min;
  271. fin = fopen("date.in", "rt");
  272. if (!fin)
  273. {
  274. printf("Eroare: nu pot deschide fisierul.\n");
  275. return -1;
  276. }
  277. fscanf(fin, "%d", &n);
  278. for (i = 0; i < n; i++)
  279. for (j = 0; j < n; j++)
  280. fscanf(fin, "%d", &(d[i][j]));
  281. printf("In total, sunt %d orase.\n", n);
  282. printf("Datele de intrare sunt:\n"); printf("\n");
  283. for (i = 0; i < n; i++)
  284. {
  285. for (j = 0; j < n; j++)
  286. printf("%d ", d[i][j]);
  287. printf("\n");
  288. }
  289. printf("\n");
  290. for (i = 0; i < n; i++)
  291. vizitat[i] = 0;
  292. drum[0] = 0;
  293. vizitat[0] = 1;
  294. count = 1;
  295. cost = 0;
  296. for (i = 0; i < n - 1; i++)
  297. {
  298.  
  299. alege(drum[count - 1], &min, &j_min);
  300. printf("Drumul ales este (%d, %d) de cost %d.\n", drum[count - 1], j_min, min);
  301. drum[count] = j_min;
  302. vizitat[j_min] = 1;
  303. count++;
  304. cost += min;
  305. if(drum[count-1]==1)
  306. {
  307. printf("Drumul ales este (1, 3) de cost 4.\n");
  308. vizitat[3] = 1;
  309. cost+=4;
  310. }
  311. if(drum[count-1] == 6) break;
  312. }
  313. printf("\nDrumul are costul %d.\n", cost);
  314. return 0;
  315. }
  316. -------------------------------------------------------------------------------------
  317.  
  318. #include <stdio.h>
  319.  
  320. /* Declaram sirul de numere direct din cod. Alternativ el
  321. poate fi citit de la tastatura sau din fisier. */
  322. #define N 10
  323. int x[] = { -11,-6,0,2,4,5,10,23,40,66 };
  324.  
  325.  
  326. /* Functie care determina minimul si maximul dintr-o
  327. secventa a sirului de numere. Secventa este delimitata
  328. de indicii "st" si "dr". Valorile minime si maxime
  329. gasite vor fi returnate prin pointerii "min" si "max"
  330. primiti ca si parametru. */
  331. void minmax(int st, int dr, int *min)
  332. {
  333. int mijloc, min_st, max_st, min_dr, max_dr;
  334.  
  335. printf("Caut in secventa [%d..%d].\n", st, dr);
  336.  
  337. /* Daca secventa contine un singur numar, atunci el
  338. este atat minim cat si maxim. */
  339. if (st == dr) {
  340. *min = x[st];
  341.  
  342. }
  343.  
  344. /* Daca secventa contine doua numere, atunci facem o
  345. comparatie pentru a gasi minimul si maximul. */
  346. else if (st == dr - 1) {
  347.  
  348. if (x[st] > x[dr]) {
  349. *min = x[st]-x[dr];
  350.  
  351. } else {
  352. *min = x[dr]-x[st];
  353.  
  354. }
  355. }
  356. /* Daca avem mai multe numere, atunci divizam problema
  357. in subprobleme. */
  358. else {
  359. /* Divizare. */
  360. mijloc = (st + dr) / 2;
  361. minmax(st, mijloc, &min_st);
  362. minmax(mijloc + 1, dr, &min_dr);
  363.  
  364. /* Combinarea rezultatelor partiale. Comparam
  365. minimele partiale intre ele si maximele partiale
  366. intre ele. */
  367.  
  368. if (min_st < min_dr)
  369. *min = min_dr - min_st;
  370. else
  371. *min = min_st- min_dr;
  372.  
  373.  
  374. }
  375. }
  376.  
  377. int main(void)
  378. {
  379. int min, max;
  380. int i;
  381.  
  382. /* Afisam sirul de numere. */
  383. printf("Avem %d numere.\n", N);
  384. for (i = 0; i < N; i++)
  385. printf("%d ", x[i]);
  386. printf("\n\n");
  387.  
  388. /* Apelam functia recursiva. */
  389. minmax(0, N - 1, &min);
  390.  
  391. /* Afisam rezultatele. */
  392. printf("\n");
  393. printf("Minimul este %d.\n", min-1);
  394.  
  395.  
  396.  
  397. return 0;
  398. }
  399. ------------------------------------------------------------------------------
  400.  
  401. Hotul
  402. # include<stdio.h>
  403. # include<conio.h>
  404.  
  405. void knapsack(int n, float weight[], float profit[], float capacity)
  406. {
  407. float x[20], tp= 0;
  408. int i, j, u;
  409. u=capacity;
  410.  
  411. for (i=0;i<n;i++)
  412. x[i]=0.0;
  413.  
  414. for (i=0;i<n;i++)
  415. {
  416. if(weight[i]>u)
  417. break;
  418. else
  419. {
  420. x[i]=1.0;
  421. tp= tp+profit[i];
  422. u=u-weight[i];
  423. }
  424. }
  425.  
  426. if(i<n)
  427. x[i]=u/weight[i];
  428.  
  429. tp= tp + (x[i]*profit[i]);
  430.  
  431. printf("n The result vector is:- ");
  432. for(i=0;i<n;i++)
  433. printf("%ft",x[i]);
  434.  
  435. printf("m Maximum profit is:- %f", tp);
  436.  
  437. }
  438.  
  439. void main()
  440. {
  441. float weight[20], profit[20], capacity;
  442. int n, i ,j;
  443. float ratio[20], temp;
  444.  
  445.  
  446. printf ("n Enter the no. of objects:- ");
  447. scanf ("%d", &n);
  448.  
  449. printf ("n Enter the weights and profits of each object:- ");
  450. for (i=0; i<n; i++)
  451. {
  452. scanf("%f %f", &weight[i], &profit[i]);
  453. }
  454.  
  455. printf ("n enter the capacityacity of knapsack:- ");
  456. scanf ("%f", &capacity);
  457.  
  458. for (i=0; i<n; i++)
  459. {
  460. ratio[i]=profit[i]/weight[i];
  461. }
  462.  
  463. for(i=0; i<n; i++)
  464. {
  465. for(j=i+1;j< n; j++)
  466. {
  467. if(ratio[i]<ratio[j])
  468. {
  469. temp= ratio[j];
  470. ratio[j]= ratio[i];
  471. ratio[i]= temp;
  472.  
  473. temp= weight[j];
  474. weight[j]= weight[i];
  475. weight[i]= temp;
  476.  
  477. temp= profit[j];
  478. profit[j]= profit[i];
  479. profit[i]= temp;
  480. }
  481. }
  482. }
  483.  
  484. knapsack(n, weight, profit, capacity);
  485.  
  486. }
  487. --------------------------------------------------------------------------------
  488. #include <stdio.h>
  489. #include <stdlib.h>
  490.  
  491. #define MAX 10
  492.  
  493. int distance(int p1, int p2)
  494. {
  495. return p2-p1;
  496. }
  497.  
  498. int min_dist (int *s, int left, int right)
  499. {
  500. int middle, minim_l,minim_r;
  501. int minim;
  502.  
  503. if (left == right-1)
  504. minim = distance(s[left],s[right]);
  505. else
  506. {
  507. middle = (left+right)/2;
  508. /*printf("middle %d\n", middle);*/
  509.  
  510. minim_l = min_dist(s,left, middle);
  511. /*printf("min left %d\n", minim_l);*/
  512.  
  513. minim_r = min_dist(s,middle, right);
  514. /*printf("min right %d\n",minim_r);*/
  515.  
  516. if(minim_l < minim_r)
  517. minim = minim_l;
  518. else
  519. minim = minim_r;
  520. }
  521.  
  522. return minim;
  523. }
  524.  
  525.  
  526. int main()
  527. {
  528. int n ,i;
  529.  
  530. FILE *fin = fopen("puncte_in.txt", "r");
  531.  
  532. if (!fin)
  533. {
  534. printf("Error on opening input file!\n");
  535. exit(1);
  536. }
  537.  
  538. fscanf(fin, "%d", &n);
  539. /*printf("Number of points in file: %d\n", n);*/
  540.  
  541. int coord[MAX]={0};
  542.  
  543. for(i=0; i<n; i++)
  544. {fscanf(fin ,"%d" , &coord[i]);
  545. /*printf("%d\n", coord[i]);*/}
  546.  
  547. FILE *fout = fopen("puncte_out.txt", "w");
  548.  
  549. if(!fout)
  550. {
  551. printf("Error on opening output file!\n");
  552. exit(1);
  553. }
  554.  
  555. fprintf(fout,"The minimal distance between the given points is %d\n",min_dist(coord,0, n-1));
  556. printf("%d", min_dist(coord,0,n-1));
  557.  
  558. fclose(fout);
  559. fclose(fin);
  560. return 0;
  561. }
  562.  
  563. -----------------------------------------------------------------------------
  564. #include<stdio.h>
  565. #include<conio.h>
  566.  
  567. int n, cost[10][10];
  568.  
  569. void prim()
  570. {
  571. int i,j,k,l,x,nr[10],temp,min_cost=0,tree[10][3];
  572. /* For first smallest edge */
  573. temp=cost[0][0];
  574. for(i=0;i< n;i++)
  575. {
  576. for(j=0;j< n;j++)
  577. {
  578. if(temp>cost[i][j])
  579. {
  580. temp=cost[i][j];
  581. k=i;
  582. l=j;
  583. }
  584. }
  585. }
  586. /* Now we have fist smallest edge in graph */
  587. tree[0][0]=k;
  588. tree[0][1]=l;
  589. tree[0][2]=temp;
  590. min_cost=temp;
  591.  
  592. /* Now we have to find min dis of each
  593. vertex from either k or l
  594. by initialising nr[] array
  595. */
  596.  
  597. for(i=0;i< n;i++)
  598. {
  599. if(cost[i][k]< cost[i][l])
  600. nr[i]=k;
  601. else
  602. nr[i]=l;
  603. }
  604. /* To indicate visited vertex initialise nr[] for them to 100 */
  605. nr[k]=100;
  606. nr[l]=100;
  607. /* Now find out remaining n-2 edges */
  608. temp=99;
  609. for(i=1;i< n-1;i++)
  610. {
  611. for(j=0;j< n;j++)
  612. {
  613. if(nr[j]!=100 && cost[j][nr[j]] < temp)
  614. {
  615. temp=cost[j][nr[j]];
  616. x=j;
  617. }
  618. }
  619. /* Now i have got next vertex */
  620. tree[i][0]=x;
  621. tree[i][1]=nr[x];
  622. tree[i][2]=cost[x][nr[x]];
  623. min_cost=min_cost+cost[x][nr[x]];
  624. nr[x]=100;
  625.  
  626. /* Now find if x is nearest to any vertex
  627. than its previous near value */
  628.  
  629. for(j=0;j< n;j++)
  630. {
  631. if(nr[j]!=100 && cost[j][nr[j]] > cost[j][x])
  632. nr[j]=x;
  633. }
  634. temp=99;
  635. }
  636. /* Now i have the answer, just going to print it */
  637. printf("n The min spanning tree is:- ");
  638. for(i=0;i< n-1;i++)
  639. {
  640. for(j=0;j< 3;j++)
  641. printf("%d", tree[i][j]);
  642. printf("n");
  643. }
  644.  
  645. printf("n Min cost:- %d", min_cost);
  646. }
  647.  
  648. //////////////////////////////////////////////
  649. void main()
  650. {
  651. int i,j;
  652.  
  653.  
  654. printf("n Enter the no. of vertices:- ");
  655. scanf("%d", &n);
  656.  
  657. printf ("n Enter the costs of edges in matrix form:- ");
  658. for(i=0;i< n;i++)
  659. for(j=0;j< n;j++)
  660. scanf("%d",&cost[i][j]);
  661.  
  662. printf("n The matrix is:- ");
  663. for(i=0;i< n;i++)
  664. {
  665. for(j=0;j< n;j++)
  666. printf("%dt",cost[i][j]);
  667. printf("n");
  668. }
  669. prim();
  670.  
  671. }
  672. ------------------------------------------------------------------------------
  673.  
  674. #include<stdio.h>
  675. #include<stdlib.h>
  676.  
  677. #define N 20
  678.  
  679. int x=N*N,min[N][N];
  680.  
  681. void afisare(int n,int m,char l[][N])
  682. {
  683. int count=0;
  684. for(int i=0;i<n;i++)
  685. {
  686. for(int j=0;j<m;j++)
  687. {
  688. printf("%c ",l[i][j]);
  689. if(l[i][j]=='x')
  690. count++;
  691. }
  692. putchar('\n');
  693. }
  694. if(count<x && count)
  695. {
  696. x=count;
  697. for(int i=0;i<n;i++)
  698. for(int j=0;j<m;j++)
  699. min[i][j]=l[i][j];
  700. }
  701. putchar('\n');
  702. }
  703.  
  704. void back(int n,int m,char l[][N],int i,int j)
  705. {
  706. int k=0;
  707. if(l[i][j]!='S' && l[i][j]!='x')
  708. for(i=0;i<n;i++)
  709. {
  710. if(l[i][j]=='S')
  711. break;
  712. for(j=0;j<=m;j++)
  713. if(l[i][j]=='S')
  714. {i--;break;}
  715. }
  716. if(i==n-1 || j==m-1 || i==0 || j==0)
  717. {
  718. afisare(n,m,l);
  719. if(scanf("%d",&k)==1)
  720. if(k)
  721. l[i][j]='.';
  722. else exit(1);
  723. }
  724. if(!k)
  725. {if(l[i+1][j]=='.')
  726. {
  727. l[i+1][j]='x';
  728. back(n,m,l,i+1,j);
  729. }
  730. if(l[i][j+1]=='.')
  731. {
  732. l[i][j+1]='x';
  733. back(n,m,l,i,j+1);
  734. }
  735. if(l[i-1][j]=='.')
  736. {
  737. l[i-1][j]='x';
  738. back(n,m,l,i-1,j);
  739. }
  740. if(l[i][j-1]=='.')
  741. {
  742. l[i][j-1]='x';
  743. back(n,m,l,i,j-1);
  744. }
  745. if(l[i][j]=='x')
  746. l[i][j]='.';
  747. }
  748. }
  749. int main(int argc,char** argv)
  750. {
  751. int m,n;
  752. FILE *f;
  753. f=fopen(argv[1],"r");
  754. if(!f)
  755. {
  756. perror("Wrong file name !");
  757. exit(1);
  758. }
  759. if(fscanf(f,"%d%d",&n,&m)!=2)
  760. {
  761. perror("Couldn't read numbers !");
  762. exit(1);
  763. }
  764. printf("\nn=%d m=%d\n",n,m);
  765. char l[N][N];
  766. for(int i=0;i<n;i++)
  767. for(int j=0;j<m;j++)
  768. {
  769. fscanf(f,"%*[\n ]");
  770. if(fscanf(f,"%c",&l[i][j])!=1)
  771. {
  772. perror("Wrong file data !");
  773. exit(1);
  774. }
  775. }
  776. afisare(n,m,l);
  777. back(n,m,l,0,0);
  778. printf("The shortest way is :\n");
  779. for(int i=0;i<n;i++)
  780. {
  781. for(int j=0;j<m;j++)
  782. printf("%c ",min[i][j]);
  783. putchar('\n');
  784. }
  785. return 0;
  786. }
  787. -----------------------------------------------------------------------------------
  788. #define N 8
  789. #include<stdio.h>
  790. #include <stdbool.h>
  791.  
  792. // Function used to print solution.
  793. void printSolution(int board[N][N])
  794. {
  795. for (int i = 0; i < N; i++)
  796. {
  797. for (int j = 0; j < N; j++)
  798. printf(" %d ", board[i][j]);
  799. printf("\n");
  800. }
  801. }
  802.  
  803. // Function used to check if a queen can be placed on board[row][col].
  804. bool isSafe(int board[N][N], int row, int col)
  805. {
  806. int i, j;
  807.  
  808. // Check row on left side.
  809. for (i = 0; i < col; i++)
  810. {
  811. if (board[row][i])
  812. return false;
  813. }
  814.  
  815. // Check upper diagonal on left side.
  816. for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
  817. {
  818. if (board[i][j])
  819. return false;
  820. }
  821.  
  822. // Check lower diagonal on left side.
  823. for (i = row, j = col; j >= 0 && i < N; i++, j--)
  824. {
  825. if (board[i][j])
  826. return false;
  827. }
  828.  
  829. return true;
  830. }
  831.  
  832. // Recursive function used to solve N Queen problem.
  833. bool solveNQUtil(int board[N][N], int col)
  834. {
  835. // If all queens are placed then return true.
  836. if (col >= N)
  837. return true;
  838.  
  839. for (int i = 0; i < N; i++)
  840. {
  841. // Check if queen can be placed on board[i][col].
  842. if ( isSafe(board, i, col) )
  843. {
  844. // Place this queen in board[i][col].
  845. board[i][col] = 1;
  846.  
  847. // Recur to place rest of the queens.
  848. if ( solveNQUtil(board, col + 1) == true )
  849. return true;
  850.  
  851. // If placing queen in board[i][col] doesn't lead to a solution then remove queen from board[i][col].
  852. board[i][col] = 0; // BACKTRACK
  853. }
  854. }
  855.  
  856. // If queen can not be place in any row in this colum col then return false.
  857. return false;
  858. }
  859.  
  860. // Function returns false if queens cannot be placed, otherwise return true and prints placement of queens.
  861. bool solveNQ()
  862. {
  863. int board[N][N] = { {0, 0, 0, 0, 0, 0, 0, 0},
  864. {0, 0, 0, 0, 0, 0, 0, 0},
  865. {0, 0, 0, 0, 0, 0, 0, 0},
  866. {0, 0, 0, 0, 0, 0, 0, 0},
  867. {0, 0, 0, 0, 0, 0, 0, 0},
  868. {0, 0, 0, 0, 0, 0, 0, 0},
  869. {0, 0, 0, 0, 0, 0, 0, 0},
  870. };
  871.  
  872. if (solveNQUtil(board, 0) == false )
  873. {
  874. printf("Solution does not exist");
  875. return false;
  876. }
  877.  
  878. printSolution(board);
  879. return true;
  880. }
  881.  
  882. int main()
  883. {
  884. solveNQ();
  885.  
  886. getchar();
  887. return 0;
  888. }
  889. ------------------------------------------------------------------------------------------
  890. Calul, Turele
  891. #include <stdio.h>
  892. #define N 2
  893.  
  894. //pt tura:
  895. int dx[4] = {-1, 0, 1, 0};
  896. int dy[4] = {0, 1, 0, -1};
  897.  
  898.  
  899. /* pt cal:
  900. int dx[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
  901. int dy[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
  902. */
  903. int c[N*N][2];
  904. int count = 0;
  905. void back(int pas)
  906. {
  907. int i, j, continuare;
  908. if (pas == N*N)
  909. {
  910. for (i=0; i<pas; i++)
  911. printf("(%d,%d) ", c[i][0], c[i][1]);
  912. printf("\n");
  913. count++;
  914. }
  915. else
  916. {
  917. for (i=0; i<4; i++) //pt cal i<8
  918. {
  919. c[pas][0] = c[pas-1][0] + dy[i];
  920. c[pas][1] = c[pas-1][1] + dx[i];
  921.  
  922. if ((c[pas][0]>=0) && (c[pas][0]<N) &&
  923. (c[pas][1]>=0) && (c[pas][1]<N))
  924. {
  925. continuare = 1;
  926. for (j=0; continuare && (j<pas); j++)
  927. {
  928. if ((c[j][0] == c[pas][0]) &&
  929. (c[j][1] == c[pas][1]))
  930. continuare = 0;
  931. }
  932.  
  933. if (continuare)
  934. back(pas+1);
  935. }
  936. }
  937. }
  938. }
  939. int main(void)
  940. {
  941. int i,j;
  942. for (i=0; i<N; i++)
  943. for (j=0; j<N; j++)
  944. {
  945. c[0][0] = i;
  946. c[0][1] = j;
  947. back(1);
  948. }
  949. printf("%d solutii\n", count);
  950. return 0;
  951. }
  952. ------------------------------------------------------------------------------------------
  953. SUDOKU
  954. #include <stdio.h>
  955.  
  956. int isAvailable(int sudoku[][9], int row, int col, int num)
  957. {
  958. int i, j;
  959. for(i=0; i<9; ++i)
  960. if( (sudoku[row][i] == num) || ( sudoku[i][col] == num ) )//checking in row and col
  961. return 0;
  962.  
  963. //checking in the grid
  964. int rowStart = (row/3) * 3;
  965. int colStart = (col/3) * 3;
  966.  
  967. for(i=rowStart; i<(rowStart+3); ++i)
  968. {
  969. for(j=colStart; j<(colStart+3); ++j)
  970. {
  971. if( sudoku[i][j] == num )
  972. return 0;
  973. }
  974. }
  975.  
  976. return 1;
  977. }
  978.  
  979. int fillsudoku(int sudoku[][9], int row, int col)
  980. {
  981. int i;
  982. if( row<9 && col<9 )
  983. {
  984. if( sudoku[row][col] != 0 )//pre filled
  985. {
  986. if( (col+1)<9 )
  987. return fillsudoku(sudoku, row, col+1);
  988. else if( (row+1)<9 )
  989. return fillsudoku(sudoku, row+1, 0);
  990. else
  991. return 1;
  992. }
  993. else
  994. {
  995. for(i=0; i<9; ++i)
  996. {
  997. if( isAvailable(sudoku, row, col, i+1) )
  998. {
  999. sudoku[row][col] = i+1;
  1000.  
  1001. if( (col+1)<9 )
  1002. {
  1003. if( fillsudoku(sudoku, row, col +1) )
  1004. return 1;
  1005. else
  1006. sudoku[row][col] = 0;
  1007. }
  1008. else if( (row+1)<9 )
  1009. {
  1010. if( fillsudoku(sudoku, row+1, 0) )
  1011. return 1;
  1012. else
  1013. sudoku[row][col] = 0;
  1014. }
  1015. else
  1016. return 1;
  1017. }
  1018. }
  1019. }
  1020. return 0;
  1021. }
  1022. else
  1023. {
  1024. return 1;
  1025. }
  1026. }
  1027.  
  1028. int main()
  1029. {
  1030. int i, j;
  1031. int sudoku[9][9]={{3, 0, 6, 5, 0, 8, 4, 0, 0},
  1032. {5, 2, 0, 0, 0, 0, 0, 0, 0},
  1033. {0, 8, 7, 0, 0, 0, 0, 3, 1},
  1034. {0, 0, 3, 0, 1, 0, 0, 8, 0},
  1035. {9, 0, 0, 8, 6, 3, 0, 0, 5},
  1036. {0, 5, 0, 0, 9, 0, 6, 0, 0},
  1037. {1, 3, 0, 0, 0, 0, 2, 5, 0},
  1038. {0, 0, 0, 0, 0, 0, 0, 7, 4},
  1039. {0, 0, 5, 2, 0, 6, 3, 0, 0}};
  1040.  
  1041. if( fillsudoku(sudoku, 0, 0) )
  1042. {
  1043.  
  1044. for(i=0; i<9; ++i)
  1045. {
  1046. for(j=0; j<9; ++j)
  1047. printf("%d ", sudoku[i][j]);
  1048. printf("\n");
  1049. }
  1050. }
  1051. else
  1052. {
  1053. printf("\n\nNO SOLUTION\n\n");
  1054. }
  1055.  
  1056. return 0;
  1057. }
  1058. -------------------------------------------------------------------------------------------
  1059. LISTE
  1060. 1)CUVINTE
  1061. #include <stdio.h>
  1062. #include <stdlib.h>
  1063.  
  1064. typedef struct words *wds;
  1065.  
  1066. struct words {
  1067. struct words *nxt;
  1068. char word[];
  1069. };
  1070.  
  1071. void print_words(struct words *words)
  1072. {
  1073. if(words){
  1074. print_words(words->nxt);
  1075. printf("%s\n",words->word);
  1076. }
  1077. }
  1078.  
  1079. wds add_word(char w[], wds wrd)
  1080. {
  1081. int i = 0;
  1082. wds p = malloc(sizeof(wrd));
  1083. if(!p) return NULL;
  1084. while((p->word[i]=w[i])) i++;
  1085. p->nxt = wrd;
  1086. return p;
  1087. }
  1088.  
  1089. void read_w(int N)
  1090. {
  1091. wds p = malloc(sizeof(struct words)+33*N*sizeof(char));
  1092. char tmp[34];
  1093. while(N--)
  1094. {
  1095. if(scanf("%33s",tmp)==1)
  1096. p = add_word(tmp,p);
  1097. else
  1098. printf("Not a word\n");
  1099. }
  1100. printf("Cuvintele citite sunt:");
  1101. print_words(p);
  1102. }
  1103.  
  1104. int main(int argc, char *argv[])
  1105. {
  1106. if(argc!=2)
  1107. {
  1108. printf("Error, correct usage: program_name number_words\n");
  1109. return 1;
  1110. }
  1111. int N;
  1112. N = strtol(argv[1],NULL,10);
  1113. printf("Introduceti %d cuvinte:\n",N);
  1114. read_w(N);
  1115. return 1;
  1116. }
  1117.  
  1118. 2)NUMERE
  1119. #include <stdio.h>
  1120. #include <stdlib.h>
  1121. #include <ctype.h>
  1122.  
  1123. /* tipul pentru nodul listei */
  1124. typedef struct elem
  1125. {
  1126. int info;
  1127. struct elem *urm;
  1128. } nod;
  1129.  
  1130. /* cauta in lista indicata de radacina nodul cu campul info = infofnou
  1131. si returneaza pointerul catre acel camp
  1132. daca nodul cautat nu exista returneaza NULL */
  1133.  
  1134. nod *caut(nod *radacina, int inf)
  1135. {
  1136. nod *p;
  1137. for (p=radacina; p!=NULL && p->info!=inf; p=p->urm);
  1138. // se parcurge lista atata timp cant mai sunt noduri si inf nu a fost gasit
  1139. if (p!=NULL) /* daca inf a fost gasit in lista */
  1140. return p;
  1141. return NULL;
  1142. }
  1143.  
  1144. /* Functia listez parcurge lista si pentru fiecare nod afiseaza informatia memorata. */
  1145. void listez(nod *radacina)
  1146. {
  1147. nod *p;
  1148. for (p=radacina; p!=NULL; p=p->urm)
  1149. printf("Valoarea: %d la adresa %p\n",p->info,p);
  1150. }
  1151.  
  1152. nod *sterg_incep(nod *radacina)
  1153. {
  1154. nod *p, *aux;
  1155. if (radacina==NULL){ // lista goala
  1156. printf("lista e vida\n");
  1157. return NULL;
  1158. }
  1159. else
  1160. // sterg primul element
  1161. aux=radacina; //retin adresa primului element
  1162. radacina=radacina->urm; // il sterg, facandu-l pe urmatorul primul nod
  1163. free(aux); //eliberez memoria ocupata de el
  1164. return radacina;
  1165. }
  1166.  
  1167. nod *creaza_nod(int infonou){
  1168. nod *p;
  1169. if ((p=(nod *)malloc(sizeof(nod)))==NULL){
  1170. /* daca nu e memorie suficienta pentru a crea un nod nou, se da un mesaj de eroare dupa care se
  1171. termina functia si se returneaza NULL */
  1172. printf("Eroare: memorie insuficienta\n");
  1173. return NULL;
  1174. }
  1175. else{ // daca e loc
  1176. p->info=infonou; //se completeaza campurile nadului
  1177. p->urm=NULL;
  1178. return p; //se returneaza o referinta (un pointer) catre acel nod
  1179. }
  1180. }
  1181.  
  1182. nod * intro_incep(nod *radacina, nod *nou)
  1183. {
  1184. nou->urm=radacina; // nou->urm pointeaza spre primul nod din lista sau
  1185. // spre nimic (NULL) daca nu era nici un nod in lista (radacina==NULL)
  1186. radacina=nou; //radacina pointeaza spre nou, acum primul nod din lista
  1187. return radacina;
  1188.  
  1189. }
  1190.  
  1191. nod * intro_sfs(nod *ultim, nod *nou){
  1192. if (ultim!=NULL)
  1193. ultim->urm=nou; // ultim->urm pointeaza spre noul nod, legandu-l la lista
  1194. return nou; // nou devine ultimul nod
  1195. }
  1196.  
  1197. /* Functia main afiseaza meniul programului,citeste comanda si
  1198. apeleaza functia corespunzatoare */
  1199. void main(void)
  1200. {
  1201. char o;
  1202. int val;
  1203. nod *radacina=NULL; // pastreaza inceputul listei
  1204. nod *nou, *ultim=NULL; // pastreaza sfarsitul listei
  1205. puts(""); // tiparesc un sir vid pentru delimitare fata de rularile anterioare
  1206. while(1)
  1207. {
  1208. puts("");
  1209. /* se afiseaza meniul programului */
  1210. puts("a : adauga un nod la inceput");
  1211. puts("d : adauga un nod la sfarsit");
  1212. puts("c : cauta un nod");
  1213. puts("s : sterge primul nod");
  1214. puts("l : listeaza tot");
  1215. puts("t : termina programul");
  1216. printf("\nOptiunea: ");
  1217. while(isspace(o=getchar()) );
  1218. printf("\n");
  1219. if (!isspace(o))
  1220. switch (tolower(o))
  1221. {
  1222. case 'a': { printf("adauga inceput nr=");
  1223. scanf("%d", &val);
  1224. nou=creaza_nod(val);
  1225. if (radacina==NULL) ultim=nou; //daca e primul element din lista
  1226. // initializam si ultim cu adresa noului nod
  1227. radacina=intro_incep(radacina, nou);
  1228. break;}
  1229. case 'd': { printf("adauga sfarsit nr=");
  1230. scanf("%d", &val);
  1231. nou=creaza_nod(val);
  1232. if (radacina==NULL) radacina=nou; // daca e primul element din lista
  1233. // initializam si radacina cu adresa primului nod
  1234. ultim=intro_sfs(ultim, nou);
  1235. break;}
  1236. case 'c': { puts("cauta si tipareste un nod");
  1237. printf("nr=");
  1238. scanf("%d", &val);
  1239. if ((nou=caut(radacina, val))!=NULL) /* cauta nodul in lista */
  1240. printf(" Valoare:%d\n", nou->info);
  1241. else
  1242. printf("Eroare: Identificator nedefinit\n");
  1243. break;
  1244. }
  1245. case 's':{ printf("stergere primul nod\n");
  1246. radacina=sterg_incep(radacina); /* sterge nodul din lista */
  1247. if (radacina==NULL) ultim=NULL; /* daca era ultimul nod */
  1248. break;}
  1249. case 'l':{ puts("listare");
  1250. listez(radacina);
  1251. break;}
  1252. case 't':
  1253. return;
  1254. default:
  1255. printf("Eroare : Comanda inexistenta\n");
  1256. }
  1257. }}
  1258.  
  1259. Var recursiva:
  1260. #include <stdio.h>
  1261. #include <stdlib.h>
  1262. #include <ctype.h>
  1263.  
  1264. /* tipul pentru nodul listei */
  1265. typedef struct elem
  1266. {
  1267. int info;
  1268. struct elem *urm;
  1269. } nod;
  1270.  
  1271. /* cauta in lista indicata de radacina nodul cu campul info = infofnou
  1272. si returneaza pointerul catre acel camp
  1273. daca nodul cautat nu exista returneaza NULL */
  1274.  
  1275.  
  1276. nod *caut(nod *p, int inf)
  1277. {
  1278. if (p == null)
  1279. return null;
  1280. else
  1281. if (p->info==inf)
  1282. return p;
  1283. else
  1284. return caut(p->urm, inf);
  1285. }
  1286. /* Functia listez parcurge lista si pentru fiecare nod afiseaza informatia memorata. */
  1287. void listez(nod *radacina)
  1288. {
  1289. if(radacina)
  1290. {
  1291. listez(radacina->urm);
  1292. printf("%d ",radacina->info);
  1293. }
  1294. }
  1295.  
  1296.  
  1297. #include <stdio.h>
  1298. #include <stdlib.h>
  1299.  
  1300. int count = 0;
  1301. void solve(int n, int col, int *hist)
  1302. {
  1303. if (col == n) {
  1304. printf("\nNo. %d\n-----\n", ++count);
  1305. int i;
  1306. int j;
  1307. for (i = 0; i < n; i++, putchar('\n'))
  1308. for (j = 0; j < n; j++)
  1309. putchar(j == hist[i] ? 'Q' : '.');
  1310.  
  1311. return;
  1312. }
  1313.  
  1314. //QUEENS/REGINE
  1315. //# define attack(i, j) (hist[j] == i || abs(hist[j] - i) == col - j)
  1316.  
  1317. //BISHOPS/NEBUNI
  1318. //# define attack(i, j) (abs(hist[j] - i) == col - j)
  1319.  
  1320. //ROOKS/TURE
  1321. # define attack(i, j) (hist[j] == i)
  1322. int i;
  1323. int j;
  1324. for (i = 0, j = 0; i < n; i++) {
  1325. for (j = 0; j < col && !attack(i, j); j++);
  1326. if (j < col) continue;
  1327.  
  1328. hist[col] = i;
  1329. solve(n, col + 1, hist);
  1330. }
  1331. }
  1332.  
  1333. int main(int n, char **argv)
  1334. {
  1335. if (n <= 1 || (n = atoi(argv[1])) <= 0) n = 5;
  1336. int hist[n];
  1337. solve(n, 0, hist);
  1338. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement