Question

In: Computer Science

This program will function exactly the same as Ponder 02. It prompt the user for a...

This program will function exactly the same as Ponder 02. It prompt the user for a filename. We will then read the contents of the file into a list. The program will then prompt the user for a name. Finally, we will tell the user whether the name is in the list.

Read From a File

The first part of the program will be to read the contents of a file into a list. This data will be in JSON. For example, the contents of the file languages.json might be:

{
  "array": [
      "C",
      "C#",
      "C++",
      "Java",
      "JavaScript",
      "Kotlin",
      "PHP",
      "Perl",
      "Python",
      "Swift",
      "VB"
  ]
}

Note that the contents of this file are guaranteed to be in sorted order. Of course, if the file does not exist, then a user-friendly message will be displayed to the user.

Advanced Search

Next the program will use the advanced search to determine if the name is in the list. This should behave exactly the same as it did for the linear search in Ponder 02. The only difference is that we will use a much more efficient algorithm to perform the search.

When finished, the program will display a message indicating whether the name was found.

Example

The following example is a single run-through of the program.

What is the name of the file? languages.json
What name are we looking for? C++
We found C++ in languages.json.

Solutions

Expert Solution

The algorithm for search is Binary Search. Linear Search runs in O(n) time while Binary Search runs in O(log n) time. Thus, Binary Search is much much faster than Linear Search. The only condition for binary search is that the data must be sorted. Since the values in the json file are sorted, binary search can be used.A binary search looks at the middle element of the list and compares it with the key. If key is found, then the search terminates, if the middle element is greater than key, then the key cannot lie in the upper half of the list. So the search reduces to lower half and so on.

Read the comments in the code to find how it works:

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    //Input file name from user
    string filename;
    cout << "What is the name of the file?  ";
    cin >> filename;
    
    //try to open the file
    ifstream fp;
    fp.open(filename);
    //If the file does not open
    if(!fp.is_open()) {
        cout <<"File cannot be opened as filename might be incorrect!";
        return 1;
    }
    
    //A vector of strings; An array can also be used 
    //if the maximum possible number of words is known
    std::vector<string> words;
    string word;
    int flag = 0;
    //Run the loop for each word
    while(fp >> word) {
        //List started
        if(word=="[") {
            flag = 1;
            continue;
        }
        //List ends
        if(word=="]") {
            break;
        }
        //Inside list
        if(flag) {
            //Remove the first "
            word.erase(0,1);
            //Remove the last ,
            word.erase(word.size()-1);
            //Check the last character if it is ", remove it
            if(word[word.size()-1] == '"') word.erase(word.size()-1);
            //Insert the word into the vector
            words.push_back(word);
        }
    }
    
    //Input searchKey
    string searchKey;
    cout <<"What name are we looking for? ";
    cin >> searchKey;
    
    //Implement binary search
    int i = 0, j = words.size()-1;
    int mid;
    int found = 0;
    while(i<=j) {
        mid = i+(j-i)/2;
        if(words[mid]==searchKey) {found = 1; break;}
        else if (words[mid]>searchKey) {j=mid-1;}
        else i=mid+1;
    }
    if(found) cout << "We have found " << searchKey << " in " << filename;
    else cout << searchKey << " is not in the file " << filename;
    return 0;
}

For sample run create a languages,json in the same folder as the C++ program with the followig contents:

{
  "array": [
      "C",
      "C#",
      "C++",
      "Java",
      "JavaScript",
      "Kotlin",
      "PHP",
      "Perl",
      "Python",
      "Swift",
      "VB"
  ]
}

Sample runs:

1.

What is the name of the file?  lang.j                                                                                         
File cannot be opened as filename might be incorrect!  

2.

What is the name of the file?  languages.json                                                                                 
What name are we looking for? C++                                                                                             
We have found C++ in languages.json   

3.

What is the name of the file?  languages.json                                                                                 
What name are we looking for? ABCD                                                                                            
ABCD is not in the file languages.json 

Related Solutions

Create in Java a program that will prompt the user to enter aweight for a...
Create in Java a program that will prompt the user to enter a weight for a patient in kilograms and that calculates both bolus and infusion rates based on weight of patient in an interactive GUI application, label it AMI Calculator. The patients weight will be the only entry from the user. Use 3999 as a standard for calculating BOLUS: To calculate the BOLUS you will multiply 60 times the weight of the patient for a total number. IF the...
Create in java a program that will prompt the user to enter a weight for a...
Create in java a program that will prompt the user to enter a weight for a patient in kilograms and that calculates infusion rates based on weight of patient in an interactive GUI application, label it HEPCALC. The patients’ weight will be the only entry from the user. To calculate the infusion rate you will multiply 12 times the weight divided by 50 for a total number. The end result will need to round up or down the whole number....
The program will first prompt the user for a range of numbers. Then the game will...
The program will first prompt the user for a range of numbers. Then the game will generate a random number in that range. The program will then allow the user to guess 3 times. Each time the person takes a guess, if it is not the number then the game should tell them to guess higher or lower. They only get 3 guesses. If they have not guessed the number in three tries then the game should tell them the...
IN C This assignment is to write a program that will prompt the user to enter...
IN C This assignment is to write a program that will prompt the user to enter a character, e.g., a percent sign (%), and then the number of percent signs (%) they want on a line. Your program should first read a character from the keyboard, excluding whitespaces; and then print a message indicating that the number must be in the range 1 to 79 (including both ends) if the user enters a number outside of that range. Your program...
Write a program that calculates the salary of employees. The program should prompt the user to...
Write a program that calculates the salary of employees. The program should prompt the user to enter hourly rate and number of hours of work a day. Then, the program should display the salary daily, bi-weekly (5 days a week), and monthly. Sample program: Enter your hourly rate: >>> 20 Enter how many hours you work a day: >>> 8 Your daily salary is: $160 Your bi-weekly salary is: $1600 Your monthly: $3200
Write a C program Your program will prompt the user to enter a value for the...
Write a C program Your program will prompt the user to enter a value for the amount of expenses on the credit card. Retrieve the user input using fgets()/sscanf() and save the input value in a variable. The value should be read as type double. The user may or may not enter cents as part of the input. In other words, expect the user to enter values such as 500, 500.00 and 500.10. The program will then prompt the user...
Prompt the user for their name, get and store the user input. Prompt the user for...
Prompt the user for their name, get and store the user input. Prompt the user for their age, get and store the user input. We will assume that the user will enter a positive integer and will do no error checking for valid input. Determine and store a movie ticket price based on the user's age. If their age is 12 or under, the ticket price is $5. If their age is between 13 and 64, inclusive, the ticket price...
Program Behavior Each time your program is run, it will prompt the user to enter the...
Program Behavior Each time your program is run, it will prompt the user to enter the name of an input file to analyze. It will then read and analyze the contents of the input file, then print the results. Here is a sample run of the program. User input is shown in red. Let's analyze some text! Enter file name: sample.txt Number of lines: 21 Number of words: 184 Number of long words: 49 Number of sentences: 14 Number of...
create a program that will verify a user's login credentials. The program should prompt the user...
create a program that will verify a user's login credentials. The program should prompt the user to enter his/her username and password at the keyboard. Then it should read the data from a data file named "login.txt". The file "login.txt" will contain a list of 3 valid usernames and passwords to verify the login information supplied by a user.  If the username and password entered by the user matches one of the sets read from the file, the program should print...
write a program to perform the following in C Your program should prompt the user to...
write a program to perform the following in C Your program should prompt the user to enter ten words, one at a time, which are to be stored in an array of strings. After all of the words have been entered, the list is to be reordered as necessary to place the words into alphabetical order, regardless of case. Once the list is in alphabetical order, the list should be output to the console in order. The program should execute...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT