Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ctype.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define HISTOGRAM_LENGTH 26
- /** Reads a sentence from STDIN and returns its histogram. */
- int* readSentence() {
- int* histogram = calloc(HISTOGRAM_LENGTH, sizeof(int));
- // Read characters until a period and update the histogram with them.
- for (char c = getchar(); c != '.'; c = getchar()) {
- // Skip any nonalpha characters.
- if (!isalpha(c)) {
- continue;
- }
- int index = tolower(c) - 'a';
- histogram[index]++;
- }
- // Get rid of the newline at the end of the sentence.
- getchar();
- return histogram;
- }
- typedef struct Table {
- int** histograms;
- int length;
- } Table;
- /** Reads a table of sentences from STDIN and computes their histograms. */
- Table readTable() {
- Table table;
- scanf("%d", &table.length);
- table.histograms = calloc(table.length, sizeof(int*));
- for (int i = 0; i < table.length; i++) {
- table.histograms[i] = readSentence();
- }
- return table;
- }
- /** Frees the table and its histograms from memory. */
- void freeTable(Table table) {
- for (int i = 0; i < table.length; i++) {
- free(table.histograms[i]);
- }
- free(table.histograms);
- }
- int main(int argc, char** argv) {
- Table table = readTable();
- Table tests = readTable();
- for (int i = 0; i < tests.length; i++) {
- for (int j = 0; j < table.length; j++) {
- // If the histograms are equal, the sentences are anagrams.
- if (!memcmp(tests.histograms[i], table.histograms[j], HISTOGRAM_LENGTH * sizeof(int))) {
- printf("%d ", j + 1);
- }
- }
- putchar('\n');
- }
- freeTable(table);
- freeTable(tests);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement