0

This is the origional question:

Write a function repeating_group(char* arr[], int n);

where,

  • arr[]: predefined array of string to operate on
  • n: size of the arr[]

and returns char* res[] with repeating strings grouped together.

Example:

input:

char* arr[] = {"tut", "slf", "tut", "lzyy", "slf", "tut"};

output:

char* res[] = {"tut", "tut", "tut", "slf", "slf", "lzyy"}

This is my code:

#include<stdio.h>
char repeating_group(char*arr[],int n)
{
    int i,j;
    printf("char*res[]= {");
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {

            if(arr[i]==arr[j])
            {
                printf("\"%s\",\"%s\",",arr[i],arr[j]);
            }
        }
    }
    printf("}");
}

int main()
{
    char*arr[]={"Carrot","Tomato","Mustard","Carrot","Mustard","Tomato","Potato","Brinjal"};
    int n=sizeof(arr)/sizeof(arr[0]);
    repeating_group(arr,n);
    getchar();
    return 0;
}

The problem here is that it only prints the stuff that is needed but do not return an array in which the elements should be stored.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

0

As i am new to C too, i edited your code and it worked but as i don't know shorting and other method i did it by my way there will be many other and easy way to do it rather then mine. some element which are not the same where getting left and not been stored so to solve that is have to create new array there are two new array arr1 and arr2 in the program

#include<stdio.h>
char repeating_group(char*arr[],int n)
{
    int i,j,k=0;
    char *arr1[n];
    char *arr2[n];
   
    for(i=0;i<n;i++)
        arr2[i]=arr[i];
    
    for(i=0;i<n;i++)
    { 
        for(j=i+1;j<n;j++)
        {
            if(arr2[j]==0)
                continue;
            if(arr[i]==arr[j])
            {
                arr1[k++]=arr2[i];
                arr1[k++]=arr2[j];  
                arr2[i]=0;
                arr2[j]=0;
            }
        }   
    }
    for(i=0;i<n;i++)
        if(arr2[i]!=0)
            arr1[k++]=arr2[i];
    
    printf("char* arr[]= {");
    for(i=0;i<n;i++)
        printf("\"%s\",",arr[i]);
    printf("}");
    
    printf("\n\n");
    
    printf("char* res[]= {");
    for(i=0;i<n;i++)
        printf("\"%s\",",arr1[i]);
    printf("}");
    return 0;
}
int main(void)
{
    char *arr[]={"Carrot","Tomato","Mustard","Carrot","Mustard","Tomato","Potato","Brinjal"};
    int n=sizeof(arr)/sizeof(arr[0]);
    repeating_group(arr,n);
    //getchar();
}

it works!!

MONUDDIN TAMBOLI
  • 152
  • 1
  • 11