fork download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <pthread.h>
  6.  
  7. char alphabet[26] = "abcdefghijklmnopqrstuvwxyz";
  8. int count[26];
  9. pthread_mutex_t mutex;
  10.  
  11. char* sentence(char * s){
  12. char* p;
  13. char* q;
  14. char* arr;
  15. int i;
  16. p = s;
  17. q = malloc(100);
  18. arr = q;
  19. for (i=0; *p != '.'; i++){
  20. *q = *p;
  21. q++;
  22. p++;
  23. }
  24. *q = '\0';
  25. return arr;
  26. }
  27.  
  28. char** load_sentence(char* p, char** q, int i){
  29. q[i] = malloc(strlen(p)+1);
  30. strcpy(q[i], p);
  31. return q;
  32. }
  33.  
  34. void* count_letter(void * s){
  35. pthread_mutex_lock(&mutex);
  36. char* p = (char*) s;
  37. int i;
  38. for (i=0; i<26; i++){
  39. if (*p == alphabet[i]){
  40. count[i]++;
  41. }
  42. }
  43. pthread_mutex_unlock(&mutex);
  44. return NULL;
  45. }
  46.  
  47. void frequency(char* str){
  48. char* s = str;
  49. int i, j, l;
  50. l = strlen(str);
  51. pthread_t tid[l];
  52. if (pthread_mutex_init(&mutex, NULL) != 0){
  53. printf("Mutex init failed\n");
  54. exit(1);
  55. }
  56. for (i=0; i<l; i++){
  57. pthread_create(&tid[i], NULL, count_letter, (void*) s);
  58. s++;
  59. }
  60. for (j=0; j<l; j++){
  61. pthread_join(tid[j], NULL);
  62. }
  63. }
  64.  
  65.  
  66. int main(int argc, char* argv[]){
  67.  
  68.  
  69. int fd;
  70. char buff[100];
  71. char ** text = malloc(10*sizeof(char*));
  72. scanf("%s ", buff);
  73. printf("%s\n", buff);
  74. char* start = buff;
  75. int i = 0; //number of phrases!
  76. char* p = NULL;
  77.  
  78. while (*(p = sentence(start)) != '\0'){
  79. text = load_sentence(p, text, i);
  80. start += strlen(p)+1;
  81. i++;
  82. }
  83.  
  84. int j, k;
  85.  
  86. for (k=0; k<i; k++){
  87. frequency(text[k]);
  88. }
  89.  
  90. for (j=0; j<26; j++){
  91. printf("%c : %d times\n", alphabet[j], count[j]);
  92. }
  93. }
Success #stdin #stdout 0s 42256KB
stdin
aaaaaaaaa.aaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaa.
stdout
aaaaaaaaa.aaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaa.
a : 37 times
b : 0 times
c : 0 times
d : 0 times
e : 0 times
f : 0 times
g : 0 times
h : 0 times
i : 0 times
j : 0 times
k : 0 times
l : 0 times
m : 0 times
n : 0 times
o : 0 times
p : 0 times
q : 0 times
r : 0 times
s : 0 times
t : 0 times
u : 0 times
v : 0 times
w : 0 times
x : 0 times
y : 0 times
z : 0 times