Search code examples
clinked-list

Find the instance of each character in every row


We are given a 6x6 matrix of characters:

X A E I O U
U X A E I O
O U X A E I
I O U X A E
E I O U X A
X Y Z X Y X

And we are asked the find the most row where a character repeats the most

In our case is row 6 with 3 X's.

My idea considering i've done something similar in the past was to use Linked Lists

The idea basically goes like this(at least what i had in mind):

We build a structure containing the character, the number of instances and the row it belongs to.

Then we build a while loop scanning every character one by one and then checking if in this row the character is stored or not. If yes then we increment else we store it and initialize the count to 1

This is my code :

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

typedef struct Node
{
    int row;
    int count;
    char c;
    struct Node *next;
}node;

node *createNode(char *name)
{
    FILE *file;
    file= fopen(name,"r");
    if(file==NULL)
    {
        printf("Error opening file....");
        exit(1);
    }
    int n=6;
    char str[6][6];
    char c;
    node *head=NULL;
    int i=0;
    int j=0;
    while(fscanf(file,"%c ",&str[i][j])!=EOF)
    {
        int found=0;
        int r=0;
        node *p=head;
        while (p)
        {
            if(p->c==str[i][j] && p->row==i)
            {
                found=1;
                break;
            }
        }
        if(found)
        {
            p->count++;
        }
        else
        {
            node *tmp= malloc(sizeof (node));
            if(tmp==NULL)
            {
                printf("Error allocating memory!");
                exit(1);
            }
            tmp->c=str[i][j];
            tmp->row=i;
            tmp->count=1;

            tmp->next=head;
            head=tmp;
        }
        i++;
        if(i==6)
        {
            i=0;
            j++;
        }
    }
    fclose(file);
    return head;
}

void printList(node *head)
{
    node *tmp=head;
    int i=1;
    while(tmp != NULL)
    {
        printf("Node %d:\nchar->%c\nrow->%d\ncount->%d\n\n",i,tmp->c,tmp->row,tmp->count);
        i++;
        tmp=tmp->next;
    }
}

int main() {

    char name[]={"file"};
    node *head=NULL;
    head=createNode(name);
    printList(head);

    return 0;
}

It seems correct to me at least but it doesnt print anything. Im just printing for now to see if its correct, Ill add the other stuff later


Solution

  • Your program doesn't print anything because it gets stuck in an infinite loop.

    while (p)
    {
        if(p->c==str[i][j] && p->row==i)
        {
            found=1;
            break;
        }
    }
    

    You never actually make p loop through the list. You need to add p = p->next;