Advertisement
Guest User

C trial n error

a guest
Nov 23rd, 2020
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1.  
  2. #include <stdio.h>
  3. #define NO_OF_CHARS 256
  4. #define N 100
  5.  
  6. // C function to find the second most frequent character
  7. // in a given string 'str'
  8. char getSecondMostFreq(char *str)
  9. {
  10. // count number of occurrences of every character.
  11. int count[NO_OF_CHARS] = {0}, i;
  12. for (i=0; str[i]; i++)
  13. (count[str[i]])++;
  14.  
  15. // Traverse through the count[] and find second highest element.
  16. int first = 0, second = 0, third = 0;
  17. for (i = 0; i < NO_OF_CHARS; i++)
  18. {
  19. /* If current element is smaller than first then update both
  20. first and second */
  21. if (count[i] > count[first])
  22. {
  23. third = second;
  24. second = first;
  25. first = i;
  26. }
  27.  
  28. /* If count[i] is in between first and second then update second */
  29. else if (count[i] > count[second] &&
  30. count[i] != count[first] &&
  31. count[i] != count[third])
  32. second = i;
  33. }
  34.  
  35. return second;
  36. }
  37.  
  38. char getThirdMostFreq(char *str)
  39. {
  40. // count number of occurrences of every character.
  41. int count[NO_OF_CHARS] = {0}, i;
  42. for (i=0; str[i]; i++)
  43. (count[str[i]])++;
  44.  
  45. // Traverse through the count[] and find second highest element.
  46. int first = 0, second = 0, third = 0;
  47. for (i = 0; i < NO_OF_CHARS; i++)
  48. {
  49. /* If current element is smaller than first then update both
  50. first and second */
  51. if (count[i] > count[first])
  52. {
  53. third = second;
  54. second = first;
  55. first = i;
  56. }
  57.  
  58. /* If count[i] is in between first and second then update second */
  59. else if (count[i] != count[second] &&
  60. count[i] != count[first] &&
  61. count[i] > count[third])
  62. third = i;
  63. }
  64.  
  65. return third;
  66. }
  67.  
  68. // Driver program to test above function
  69. int main()
  70. {
  71. char str[N];
  72. scanf("%s", &str);
  73. char res = getSecondMostFreq(str);
  74. if (res != '\0')
  75. printf("Second most frequent char is %c", res);
  76. else
  77. printf("No second most frequent character");
  78. char str[] = *str
  79. char res = getThirdMostFreq(str);
  80. if (res != '\0')
  81. printf("Third most frequent char is %c", res);
  82. else
  83. printf("No third most frequent character");
  84. return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement