Advertisement
Guest User

Untitled

a guest
Feb 9th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. #include <ctype.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #define HISTOGRAM_LENGTH 26
  7.  
  8. /** Reads a sentence from STDIN and returns its histogram. */
  9. int* readSentence() {
  10. int* histogram = calloc(HISTOGRAM_LENGTH, sizeof(int));
  11.  
  12. // Read characters until a period and update the histogram with them.
  13. for (char c = getchar(); c != '.'; c = getchar()) {
  14. // Skip any nonalpha characters.
  15. if (!isalpha(c)) {
  16. continue;
  17. }
  18.  
  19. int index = tolower(c) - 'a';
  20. histogram[index]++;
  21. }
  22.  
  23. // Get rid of the newline at the end of the sentence.
  24. getchar();
  25.  
  26. return histogram;
  27. }
  28.  
  29. typedef struct Table {
  30. int** histograms;
  31. int length;
  32. } Table;
  33.  
  34. /** Reads a table of sentences from STDIN and computes their histograms. */
  35. Table readTable() {
  36. Table table;
  37. scanf("%d", &table.length);
  38.  
  39. table.histograms = calloc(table.length, sizeof(int*));
  40. for (int i = 0; i < table.length; i++) {
  41. table.histograms[i] = readSentence();
  42. }
  43.  
  44. return table;
  45. }
  46.  
  47. /** Frees the table and its histograms from memory. */
  48. void freeTable(Table table) {
  49. for (int i = 0; i < table.length; i++) {
  50. free(table.histograms[i]);
  51. }
  52.  
  53. free(table.histograms);
  54. }
  55.  
  56. int main(int argc, char** argv) {
  57. Table table = readTable();
  58. Table tests = readTable();
  59.  
  60. for (int i = 0; i < tests.length; i++) {
  61. for (int j = 0; j < table.length; j++) {
  62. // If the histograms are equal, the sentences are anagrams.
  63. if (!memcmp(tests.histograms[i], table.histograms[j], HISTOGRAM_LENGTH * sizeof(int))) {
  64. printf("%d ", j + 1);
  65. }
  66. }
  67. putchar('\n');
  68. }
  69.  
  70. freeTable(table);
  71. freeTable(tests);
  72.  
  73. return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement