Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.5 kB
2
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct{
    char word1[51],word2[51];
    double grade;
}cuvinte; // am facut un struct ca sa tinem fiecare pereche alaturi de gradul ei

void swap1(cuvinte *x, cuvinte *y) //schimbam 2 cuvinte intre ele cu grad cu tot
{
    cuvinte tmp;
    tmp=*x;
    *x = *y;
    *y = tmp;
}

void sort(cuvinte *word, int n)
{
    for(int i = 0; i< n-1; i++)
    {
        for(int j = 0; j< n-i-1; j++)
        {
            if(word[j].grade < word[j+1].grade)
            {
                swap1(word[j],word[j+1]);
            }
            else if(word[j].grade == word[j+1].grade && strcmp(word[j].word1,word[j+1].word1) < 0)
            {
                swap1(word+j,word+j+1);
            }
        }
    }
}




int is_anagram(char *s1, char *s2)
{
    int length1 = strlen(s1);
    int length2 = strlen(s2);

    if(length1 != length2)
        return 0;

    int count1[256];
    int count2[256]; // creeam doi vectori de aparitie a literelor si ii initializam cu 0

    for(int i = 0; i < 256; i++)
    {
        count1[i] = 0;
        count2[i] = 0;
    }

    for(int i = 0; i < length1; i++) // pentru fiecare litera crestem valoare vectorului de aparitie
    {
        count1[s1[i]]++;
        count2[s2[i]]++;
    }

    for(int i = 0; i < length1; i++)
    {
        if(count1[i] != count2[i]) // daca aparitia unei litere nu este prezenta in ambele cuvinte returnam -1
            return 0;
    }

    return 1; // la final daca a trecut toate testele returnam 1
}

double compute_grade(char *s1, char *s2)
{
    double diff_letters = 0;
    int length = strlen(s1);
    for(int i = 0; i < length; i++)
    {
        if(s1[i] != s2[i])
            diff_letters++;
    }

    double result = diff_letters/length;

    return result;

}



int main()
{
    int lines;
    cuvinte pairs[1001];
    scanf("%d", &lines);
    for(int i = 0; i < lines; i++)
    {
        scanf("%s", (pairs+i)->word1);
        scanf("%s", (pairs+i)->word2);
        if(is_anagram(pairs[i].word1,pairs[i].word2) == 1)
        {
            pairs[i].grade = compute_grade(pairs[i].word1,pairs[i].word2);
        }
        else pairs[i].grade = -1;

    }
    sort(pairs,lines);
    printf("\n");
    for(int i = 0; i < lines; i++)
    {
        printf("%s %s\n",pairs[i].word1,pairs[i].word2);
    }

    return 0;
}