简体   繁体   中英

How to compare and register array values which are replicated

I am having trouble interpreting the logic of this exercise...

The exercise asks me to register 5 "brands" in a structure and the output must show how many times each brand repeated, if it has been registered more than once of course.

#include <stdio.h>
#include <stdlib.h>

#define C 5

typedef struct      
{
    int id;
    char brands[30];
} Something;


Something a[C];
int main() 
{
    int i=0, j=0;

    //input
    for(i=0;i<C;i++)
    {
        a[i].id = i;

        printf("BRAND: ");
        fflush(stdin);
        gets(a[i].brands);
    }

    for(i=0;i<C;i++)
    {
        for(j=0;j<C;j++)
        {
            if (strcmp(a[i].brands, a[j].brands)==0)
                // 
        }
    }
    return 0;
}

The brand inputs values are not constant, it could be anything.

So I was thinking to look through a search, comparing whether there is equal brand and incrementing a counter for each. (This counter is where I stuck, since I dont know how many different brands will be in the registry)...

Eg 1
Inputs

Ford
Ferrari
Ford
Nissan
Nissan

Output should be like this:

Ford 2x
Ferrari 1x
Nissan 2x


Eg 2
Inputs

Ford
Ford
Ford
Ford
Nissan

Output:

Ford 4x
Nissan 1x

There are many ways to achieve what you want. Below are some pointers that will hopefully help you reach a solution.

The first step would be to include a counter in your structure.

typedef struct      
{
    int id;
    char brands[30];
    unsigned int count;
} Something;

Initialise all the count fields to 0. The brands field only contains a valid string if the count is greater than 0. Since a is a global variable, all the fields are automatically initialised to 0 so there is no extra code needed.

Then each time you read an input the code would search through a from the beginning. The search logic would be

for each 'a' entry
    if (count field > 0)
        if (brand field is same as input)
            // Found a match
            increment count field
            break out of loop
        // else will check next entry by continuing the loop
    else
        // Reached end of valid entries. Hence no match.
        Create a new entry. Copy input into the brand field. 
        Set count field to 1.
        break out of loop

I have deliberately shown pseudo code to leave the C code as an exercise for you. But basically the idea is (as stated in my earlier comment) to search the existing valid entries after reading each input (you don't need two seperate arrays).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM