Question

In: Computer Science

Question: Properly convert the solution to this problem from Java to C++ Problem Statement If you...

Question: Properly convert the solution to this problem from Java to C++

Problem Statement

If you want to write a message anonymously, one way to do it is to cut out letters from headlines in a newspaper and paste them onto a blank piece of paper to form the message you want to write. Given several headlines that you have cut out, determine how many messages from a list you can write using the letters from the headlines. You should only consider each message by itself and not in conjunction with the others, see example 2.

Write the function how_many which takes as parameters a vector<string> headlines containing the headlines which you have cut out as well as a vector<string> messages with the messages you may want to write, and returns an int which is the total number of messages you can write.

Constraints

  • All letters that you cut out can be used both as upper or lower case in a message.
  • Spaces should be ignored in elements in both headlines and messages.
  • headlines will contain between 1 and 50 elements, inclusive.
  • messages will contain between 1 and 50 elements, inclusive.
  • The length of each element in headlines will be between 1 and 50 characters, inclusive.
  • The length of each element in messages will be between 1 and 50 characters, inclusive.
  • Each element in headlines will only contain the letters 'A'-'Z', 'a'-'z' and space.
  • Each element in messages will only contain the letters 'A'-'Z', 'a'-'z' and space.

Examples

  1. headlines =
    
    {"Earthquake in San Francisco",
     "Burglary at musuem in Sweden",
     "Poverty"}
    
    messages =
    
    {"Give me my money back",
     "I am the best coder",
     "TOPCODER"}
    
    Returns: 2
    

    In the first message we have three 'm's, but there are only two 'm's among the headlines (both in the word "museum"), so this message can't be written.

    The second message can be written. Note that the first letter, 'I', only appears as lower case in the headlines, but that's allowed. The last message can also be written, so the method should return 2.

  2. headlines = 
    
            {"Programming is fun"}
    
    messages = 
    
            {"program","programmer","gaming","sing","NO FUN"}
    
    Returns: 4
    

    The messages "program", "gaming", "sing" and "NO FUN" can all be written but not "programmer" (no 'e's exist). The method should return 4.

  3. headlines = 
    
       {"abcdef","abcdef"}
    
    messages = 
    
       {"AaBbCc","aabbbcc","   ","FADE"}
    
    Returns: 3
    

    All messages except the second one can be written, because it contains three 'b's but there are only two 'b's available. Also note the message only containing spaces - such a message can of course always be written.

Given Function

#include <vector>
#include <string>

int how_many(vector<string> headlines, vector<string> messages) {
// fill in code here
}

Solution (Convert the Java code below to C++).

import java.util.*;

public class Anonymous {
      public int howMany(String[] headlines, String[] messages) {
          
    
          HashMap<Character, Integer> lettersAvailable = countLetters(headlines);

          int wordsWeCanMake = 0; 
          for(String message : messages){
                  String[] oneMessage = {message}; 
                  HashMap<Character, Integer> lettersNeeded = countLetters(oneMessage);
                  boolean canMakeMessage = true;
                  Iterator it = lettersNeeded.entrySet().iterator(); 
                  while (it.hasNext()){
                          Map.Entry pairs = (Map.Entry)it.next();
                          char key = (Character) pairs.getKey(); 
                          if(!(key==' ')){
                                  int numNeeded = (Integer) pairs.getValue();
                                  if(lettersAvailable.containsKey(key)){
                                          int numAvailable = lettersAvailable.get(key); 
                                          canMakeMessage = (numNeeded <= numAvailable) && canMakeMessage;
                                  }
                                  else{
                                          canMakeMessage = false ; 
                                          break;
                                  }
                          }
                          
                      it.remove();
                  }
                  if(canMakeMessage){
                          wordsWeCanMake += 1; 
                  }
          }
          return wordsWeCanMake; 
      }
      
      public HashMap<Character, Integer> countLetters(String[] words){
          HashMap<Character, Integer> counts = new HashMap<Character, Integer>();
          int currentCountOfLetter = 0;
          
          for(String word : words){  
                  for(int i=0; i<word.length(); i++){
                          char letter = Character.toLowerCase(word.charAt(i));
                          if (counts.containsKey(letter)){
                                  currentCountOfLetter = counts.get(letter);
                                  currentCountOfLetter +=1; 
                          }
                          else {
                                  currentCountOfLetter = 1;
                          }
                          counts.put(letter, currentCountOfLetter); 
                  }
          }
          
          return counts; 
      }
      }
}

Solutions

Expert Solution

Name of Proram file Anonymous.cpp

#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
void countLetters(vector<string> words, map<char,int> &counts) // I have taken the map as input parameter by references just for the optimization purpose
{
map<char,int>:: iterator mit;
// int currentCountOfLetter = 0; no need of this variable in our program
string s;
for(int i=0;i<words.size();i++)
{
s=words[i]; // For each string in the words vector
transform(s.begin(),s.end(),s.begin(),::tolower); // I am using transform method decalred in algorithm header file to conver the whole string in lower case before hand
string::iterator it;
for(it=s.begin();it!=s.end();it++) //I am iterating over strings as it is optimized implementation and it saves time to iterate over indexing
{
char c=*it;
mit=counts.find(c);
if(mit!=counts.end())
{
mit->second++; // increment the count of character already present in the map by one
}
else
{
counts.insert(pair<char,int>(c,1)); // It not prersent in the map then insert in the map with its count 1
}
}
}
}

int howMany(vector<string> headlines, vector<string> messages)
{
char c;
vector<string> v;
int wordsWeCanMake = 0;
bool canMakeMessage;
map<char,int> lettersAvailable;
map<char,int> lettersNeeded;
string m;
map<char,int>::iterator ait;
map<char,int>::iterator nit;
countLetters(headlines,lettersAvailable);
for(int i=0;i<messages.size();i++)
{
canMakeMessage=true;
m=messages[i];
v.push_back(m);
countLetters(v,lettersNeeded);
for(nit=lettersNeeded.begin();nit!=lettersNeeded.end();nit++)
{
c = nit->first;
if(c!=' ')
{
ait = lettersAvailable.find(c);
if(ait!=lettersAvailable.end())
{
if(!(nit->second <= ait->second))
{
canMakeMessage = false;
break;
}
}
else
{
canMakeMessage = false;
break;
}
}
}
v.clear();
lettersNeeded.clear();
if(canMakeMessage)
{
wordsWeCanMake++;
}
}
return wordsWeCanMake;
}


int main() // cross verified different examples by commenting the lines of code and it is working properly, if you want give it a try
{
vector<string> headlines;
headlines.push_back("Earthquake in San Francisco");
headlines.push_back("Burglary at musuem in Sweden");
headlines.push_back("Poverty");
headlines.push_back("Programming is fun");
headlines.push_back("abcdef");
headlines.push_back("abcdef");
vector<string> messages;
messages.push_back("Give me my money back");
messages.push_back("I am the best coder");
messages.push_back("TOPCODER");
messages.push_back("program");
messages.push_back("programmer");
messages.push_back("gaming");
messages.push_back("sing");
messages.push_back("NO FUN");
messages.push_back("AaBbCc");
messages.push_back("aabbbcc");
messages.push_back("FADE");
cout<<howMany(headlines,messages);
return 0;
}

// Hope you are satisfied with the answer, and if you are then please rate this solution, it will be a great help.

// I have kept the variables names sames as in java code to understand it better
// Thanks I enjoyed solving your Problem.
// If you have any confusion then please let me know in the comment section. I will be gratefull to solve any further queries of yours.


Related Solutions

Provide an example of a properly constructed problem statement or a poorly constructed problem statement. Explain...
Provide an example of a properly constructed problem statement or a poorly constructed problem statement. Explain why the statement you provided is either properly written or poorly written.
Convert the attached C++ code to working Java code. Be judicious in the change that you...
Convert the attached C++ code to working Java code. Be judicious in the change that you make. This assignment is not about re-writing or improving this code, but rather about recognizing the differences between C++ and Java, and making the necessary coding changes to accommodate how Java does things. PLEASE DO NOT use a built-in Java QUEUE (or any other) container. Additional resources for assignment: #include <iostream> #include <string> using namespace std; class pizza { public: string ingrediants, address; pizza...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution {...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); HashMap labs = new HashMap(); while (true) { System.out.println("Choose operation : "); System.out.println("1. Create a Lab"); System.out.println("2. Modify a Lab"); System.out.println("3. Delete a Lab"); System.out.println("4. Assign a pc to a Lab"); System.out.println("5. Remove a pc from a Lab"); System.out.println("6. Quit"); int choice = sc.nextInt(); String name=sc.nextLine(); switch (choice) { case 1:...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use the file in.txt as sample input for your program. v import java.io.*; import java.util.*; public class Pretty { public static final int LINE_SIZE = 50; public static void main(String[] parms) { String inputLine; int position = 1; Scanner fileIn = new Scanner(System.in); while (fileIn.hasNextLine()) { inputLine = fileIn.nextLine(); if (inputLine.equals("")) { if (position > 1) { System.out.println(); } System.out.println(); position = 1; } else...
CONVERT CODE FROM JAVA TO C# PLEASE AND SHOW OUTPUT import java.util.*; public class TestPaperFolds {...
CONVERT CODE FROM JAVA TO C# PLEASE AND SHOW OUTPUT import java.util.*; public class TestPaperFolds {    public static void main(String[] args)    {        for(int i = 1; i <= 4; i++)               //loop for i = 1 to 4 folds        {            String fold_string = paperFold(i);   //call paperFold to get the String for i folds            System.out.println("For " + i + " folds we get: " + fold_string);        }    }    public static String paperFold(int numOfFolds)  ...
Please Provide the solution in java, already have a question which is answer in C++. Language:...
Please Provide the solution in java, already have a question which is answer in C++. Language: java. Please don't provide your email for private answer. Q1. Implement a program which allows the user to find the shortest path between two nodes in a graph possibly passing through a third node. I.e. the user should be able to ask questions like: Which is the shortest path from A to B passing through C? The program should output an ordered list of...
Any java solution for this question ? A state is divided into R*C cities.The government has...
Any java solution for this question ? A state is divided into R*C cities.The government has launched an initiative to find the cities which are dominated by coders. Each city may or may not have coders residing in it. If the city is dominated by coders, it is marked with 1 else it is marked with 0. Two cities are termed as connected cities if they both are dominated by coders and can be reached by moving vertically, horizontally, or...
Convert this C++ code to Java code this code is to encrypt and decrypt strings of...
Convert this C++ code to Java code this code is to encrypt and decrypt strings of characters using Caesar cipher please attach samples run of the code #include <iostream> #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string> #define MAX_SIZE 200 void encrypt_str(char xyz[], int key); // Function prototype for the function to encrypt the input string. void decrypt_str(char xyz[], int key); // Function prototype for the function to decrypt the encrypted string. using namespace std; int main() { char input_str[MAX_SIZE];...
I need convert this java code to C language. There is no string can be used...
I need convert this java code to C language. There is no string can be used in C. Thank you! import java.util.Scanner; public class Nthword { public static void main( String args[] ) { String line; int word; Scanner stdin = new Scanner(System.in); while ( stdin.hasNextLine() ) { line = stdin.nextLine(); word = stdin.nextInt(); stdin.nextLine(); // get rid of the newline after the int System.out.println( "Read line: \"" + line + "\", extracting word [" + word + "]" );...
Java Programming Question The problem is to count all the possible paths from top left to...
Java Programming Question The problem is to count all the possible paths from top left to bottom right of a MxN matrix with the constraints that from each cell you can either move to right or down.Input: The first line of input contains an integer T, denoting the number of test cases. The first line of each test case is M and N, M is number of rows and N is number of columns.Output: For each test case, print the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT