Question

Assignment #1: Sorting with Binary Search Tree Through this programming assignment, the students will learn to do the followicases. All strings will be no more than 100 characters long. In addition to parsing and processing the command line argumentsinput for an input file. If the line is not an empty line and the line is already in the tree, increase the count for that noHeres an example: bash$ cat myfile bob is working. david is a new hire. Bob is working. alice is bobs boss. charles doesntclean target for cleaning up the directory (removing all temporary files and object files). Make sure you dont include intI need help with this code, I'm stuck on it, please remember step 4, I'm very much stuck on that part. It says something about putting how many times it appears

Assignment #1: Sorting with Binary Search Tree Through this programming assignment, the students will learn to do the following: Know how to process command line arguments. 1 Perform basic file I/O. 2. Use structs, pointers, and strings. Use dynamic memory. 3. 4. This assignment asks you to sort the lines of an input file (or from standard input) and print the sorted lines to an output file (or standard output). Your program, called bstsort (binary search tree sort), will take the following command line arguments: % bstsort [-c] [-o output_file_name] [input_file_name] If -c is present, the program needs to compare the strings case sensitive; otherwise, it's case insensitive. If the output_file_name is given with the -o option, the program will output the sorted lines to the given output file; otherwise, the output shall be the standard output. Similarly, if the input_file_name is given, the program will read from the input file; otherwise, the input will be from the standard input. You must use getopt() to parse the command line arguments to determine the cases. All strings will be no more than 100 characters long. In addition to parsing and processing the command line arguments, your program needs to do the following:
cases. All strings will be no more than 100 characters long. In addition to parsing and processing the command line arguments, your program needs to do the following: You need to construct a binary search tree as you read from input. A binary search tree is a binary tree. Each node can have at most two child nodes (one on the left and one on the right), both or either one can be empty. If a child node exists, it's the root of a binary search tree (we call subtree). Each node contains a key (in our case, it's a string) and a count of how many of that string were included. If he left subtree of a node exists, it contains only nodes with keys less than the node's key. If the right subtree of a node exists, it contains only nodes with keys greater than the node's key. You can look up binary search tree on the web or in your Data Structure textbook. Note that you do not need to balance the binary search tree (that is, you can ignore all 1. those rotation operations) in this assignment. 2. Initially the tree is empty (that is, the root is null). The program reads from the input file (or stdin) one line at a time; If the line is not an empty line and the line is not already in the tree, it should create a tree node that stores a pointer to the string and a count of 1 indicating this is the first occurrence of that string, and then insert the tree node to the binary search tree. An empty line would indicate the end of input for stdin, an empty line or end of file would indicate the end of
input for an input file. If the line is not an empty line and the line is already in the tree, increase the count for that node indicating that there are multiple instances of that line. You must develop two string comparison functions, one for case sensitive and the other for case 3. insensitive. You must not use the strcmp) and strcasecmp() functions provided by the C library. You must implement your own version. You will be comparing the ASCII values. Note that using ASCII, all capital letters come before all lower case letters Once the program has read all the input (when EOF is returned or a blank line encountered), the 4. program then performs an in-order traversal of the binary search tree to print out all the strings one line at a time to the output file or stdout. Next to the line include a count of how many times that line appeared. If the selection was for case insensitive then you should include either the first choice encountered, the last choice encountered or all capital letters. Before the program ends, it must reclaim the tree! You can do this by performing a post-order 5. traversal, i.e., reclaiming the children nodes before reclaiming the node itself. Make sure you also reclaim the memory occupied by the string as well. 6. It is required that you use getopt for processing the command line and use malloc or calloc and free functions for dynamically allocating and deallocating nodes and the buffers for the strings. It is required that you implement your own string comparison functions instead of using the corresponding libc functions.
Here's an example: bash$ cat myfile bob is working. david is a new hire. Bob is working. alice is bob's boss. charles doesn't like bob. bash$ ./bstsort myfile 1 alice is bob's boss. 2 bob is working 1 charles doesn't like bob. 1 david is a new hire. Please submit your work through the inbox as one zip file. Follow the instructions below carefully (to avoid unnecessary loss of grade): You should submit the source code and the Makefile in the zip file called FirstnameLastnameA1 One should be able to create the executable by simply 'make'. The Makefile should also contain a
'clean' target for cleaning up the directory (removing all temporary files and object files). Make sure you don't include intermediate files: *.o, executables, *~, etc., in your submission. (There'll be a penalty for including unnecessary intermediate files). Only two files should be included unless permission is given for more, those would be bstsort.c, and Makefile. If you feel a need to include a bstsort.h file, please send me a note asking for permission.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

SOLUTION :-

#include <string.h>
#include <stdbool.h>
#include <getopt.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct Node{
   char* key;
   int value;
   struct Node* left;
   struct Node* right;
}Node;

void removeEnterLine(char* line){
   char* ptr=&(line[0]);
   while(ptr!=NULL){
       if((*ptr)=='\n'){

           *ptr='\0';
           break;
       }
       ptr++;
   }
}

int strcmpCaseSensitive(char* str1,char* str2){
   char* ptr1=str1;
   char* ptr2=str2;
   while(ptr1!='\0' && ptr2!='\0'){
       if((*ptr1)>(*ptr2))
           return 1;
       else if((*ptr1)<(*ptr2))
           return -1;

       ptr1++;
       ptr2++;
   }

   if(ptr1=='\0' && ptr2=='\0')
       return 0;
   else if(ptr1=='\0')
       return -1;
   else
       return 1;
}

int strcmpCaseInsensitive(char* str1,char* str2){

  

   char* ptr1=str1;
   char* ptr2=str2;
   while(ptr1!='\0' && ptr2!='\0'){
       char ch1=*ptr1;
       char ch2=*ptr2;
       ch1=tolower(ch1);
       ch2=tolower(ch2);

       if(ch1>ch2)
           return 1;
       else if(ch1<ch2)
           return -1;

       ptr1++;
       ptr2++;
   }

   if(ptr1=='\0' && ptr2=='\0'){
       return 0;
   }
   else if(ptr1=='\0')
       return -1;
   else
       return 1;
}

int compareStrings(char* str1,char* str2,bool caseSensitive){

   if(caseSensitive==true){
       return strcmpCaseSensitive(str1,str2);
   }else{
       return strcmpCaseInsensitive(str1,str2);
   }
  
}

void insert(char* tmp,Node* root,bool caseSensitive){
   Node* temp=root;
   Node* parent=NULL;
   while(temp!=NULL){
       if(compareStrings(temp->key,tmp,caseSensitive)==0){
           temp->value=temp->value+1;
           return;
       }else if(compareStrings(temp->key,tmp,caseSensitive)>0){
           parent=temp;
           temp=temp->left;
       }else{
           parent=temp;
           temp=temp->right;
       }
   }


      
   Node* newest=(Node*)malloc(sizeof(Node)*1);
   newest->left=NULL;
   newest->right=NULL;
   newest->key=tmp;
   newest->value=1;

   if(compareStrings(parent->key,tmp,caseSensitive)>0){
       //printf("left\n");
       parent->left=newest;
   }else{
       //printf("right\n");
       parent->right=newest;
   }

}


void inorder(Node* root){
   if(root==NULL)
       return;
   inorder(root->left);
   int i;
   for(i=1;i<=root->value;i++)
       printf("%s\n", root->key);
   inorder(root->right);
}

int main(int argc,char** argv){

   bool caseSensitive=false;
   char* output="";
   char* input="";
   int c;
   while((c=getopt(argc,argv,"co:"))!=-1){
       switch(c){
           case 'c':
               caseSensitive=true;
               break;

           case 'o':
               output=optarg;
               break;
       }
   }

   int size=100000;
   char** arr=(char**)(malloc(sizeof(char*)*size));

   int index;  
   for (index = optind; index < argc; index++){
      input=argv[index];
   }

   int ind=0;
   if(strcmp(input,"")==0){ //std input
      size_t line_size;
      printf("Enter strings line by line\n");
      char* line=(char*)malloc(sizeof(char)*100);
      while(getline(&line,&line_size,stdin)!=-1){
          if(strcmp(line,"\n")==0)
              break;
          removeEnterLine(line);
          arr[ind++]=line;
          line=(char*)malloc(sizeof(char)*100);
     
      }

   }else{
      FILE *file = fopen(input, "r");
      char* line=(char*)malloc(sizeof(char)*100);
      size_t line_size;
     
      while(getline(&line,&line_size,file)!=-1){
          removeEnterLine(line);
          arr[ind++]=line;
          line=(char*)malloc(sizeof(char)*100);
     
      }

   }

   int j;
   // for(j=0;j<ind;j++)
   //   printf("%s\n", arr[j]);

   int sizeTree=0;
   Node* root;

   for(j=0;j<ind;j++){
      char* tmp=arr[j];
      if(sizeTree==0){
          Node* newest=(Node*)malloc(sizeof(Node)*1);
          newest->key=tmp;
          newest->value=1;
          newest->left=NULL;
          newest->right=NULL;
          root=newest;
      }else{
          insert(tmp,root,caseSensitive);
         
      }

       sizeTree++;     

   }

   inorder(root);


   return 0;
}

sample input:

hello
good
boy
dude
dude

//make sure there is \n line after last word in input file

Add a comment
Know the answer?
Add Answer to:
I need help with this code, I'm stuck on it, please remember step 4, I'm very...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • //I NEED THE PROGRAM IN C LANGUAGE!// QUESTION: I need you to write a program which...

    //I NEED THE PROGRAM IN C LANGUAGE!// QUESTION: I need you to write a program which manipulates text from an input file using the string library. Your program will accept command line arguments for the input and output file names as well as a list of blacklisted words. There are two major features in this programming: 1. Given an input file with text and a list of words, find and replace every use of these blacklisted words with the string...

  • Would appreciate the answer in the Java coding language please and thank you! 10d 10h left...

    Would appreciate the answer in the Java coding language please and thank you! 10d 10h left Java 7 1. Check the Structure Autocomplete Ready 1 > import java.io.*;... 10 ALL A binary tree uses a multi-node data structure where each node may have 0 to 2 child nodes, and has one stored value, its node number in this case. A tree may either be: 11 class Result { * Complete the 'isValid' function below. • An empty tree, the root...

  • Objective: Use input/output files, strings, and command line arguments. Write a program that processes a text...

    Objective: Use input/output files, strings, and command line arguments. Write a program that processes a text file by removing all blank lines (including lines that only contain white spaces), all spaces/tabs before the beginning of the line, and all spaces/tabs at the end of the line. The file must be saved under a different name with all the lines numbered and a single blank line added at the end of the file. For example, if the input file is given...

  • I need help in C++ implementing binary search tree. I have the .h file for the...

    I need help in C++ implementing binary search tree. I have the .h file for the binary search tree class. I have 4 classic texts, and 2 different dictionaries. Classic Texts: Alice In Wonderland.txt A Tale of Two Cities.txt Pride And Prejudice.txt War and Peace.txt 2 different dictionaries: Dictionary.txt Dictionary-brit.txt The data structures from the standard template library can not be used.The main program should open the text file, read in the words, remove the punctuation and change all the...

  • C language huffman This exercise will familiarize you with linked lists, which you will need for...

    C language huffman This exercise will familiarize you with linked lists, which you will need for a subsequent programming Getting Started assignment Overview Requirements Getting Started Submit Start by getting the files. Type 264get hw13 and then cd hw13 from bash. Pre-tester You will get the following files: Q&A Updates 1. huffman.h: An empty header file, you have to define your own functions in this homework. 2. huffman.c: An empty c file, you have to define your own functions in...

  • Please submit only Python source code. 1. Arithmetic trees 50 marks You are given an input file with multiple pairs of...

    Please submit only Python source code. 1. Arithmetic trees 50 marks You are given an input file with multiple pairs of input lines. The first line of each pair is a tree given as a predecessor array. The second line is the value at the corresponding node. Values at leaf nodes (nodes with no children) are integers. At non-leaf nodes, the two possible values are + or *. The tree represents an arithmetic expression where the value at a non-leaf...

  • Homework description::::: Write JAVA program with following description. Sample output with code will be helful... A...

    Homework description::::: Write JAVA program with following description. Sample output with code will be helful... A compiler must examine tokens in a program and decide whether they are reserved words in the Java language, or identifiers defined by the user. Design a program that reads a Java program and makes a list of all the identifiers along with the number of occurrences of each identifier in the source code. To do this, you should make use of a dictionary. The...

  • Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate ins...

    Binary Search Tree Part A: The code attached in this document is a sample code to demonstrate insert operation in binary search tree. Please fill in the missing part for the insert method to make the program work. The expected output should be as follows. 20 30 40 50 60 70 80 Part B: Find Lowest Common Ancestor (LCA) of a Binary Search Tree. According to WikiPedia definition , The lowest common ancestor is defined between two nodes v and...

  • (4) Based on Problem P13.10 e Submit the solution as hmw-6-4.cpp. . Write a program that...

    (4) Based on Problem P13.10 e Submit the solution as hmw-6-4.cpp. . Write a program that reads a list of strings (a string per line) from the file data4.txt and inserts them into a binary search tree. You can use the implementation of the class BinarySearchTree introduced in the textbook or rhe one posted on CCLE Implement a traversal function void inorder (Action & a) for inorder traversal of a binary search tree that carries out an action other than...

  • Overview: file you have to complete is WordTree.h, WordTree.cpp, main.cpp Write a program in C++ that...

    Overview: file you have to complete is WordTree.h, WordTree.cpp, main.cpp Write a program in C++ that reads an input text file and counts the occurrence of individual words in the file. You will see a binary tree to keep track of words and their counts. Project description: The program should open and read an input file (named input.txt) in turn, and build a binary search tree of the words and their counts. The words will be stored in alphabetical order...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT