1. Given an arbitrary ransom note, consisting of 15 - 20 words and several magaz
ID: 3735636 • Letter: 1
Question
1. Given an arbitrary ransom note, consisting of 15 - 20 words and several magazines, write a function that will return a true, if the ransom note can be constructed from the words in the magazines, otherwise it will return a false. Each word in the magazines can only be used once in your ransom note. The algorithm should work efficiently, such as, utilizing hash tables for storing and looking up strings. An example hash function maybe the sum of the ascii values of all the characters in the string, modulus an appropriate positive inte- ger. For testing the code, utilize the ransom note and the magazines provided on the Black board in files RansomNote.dat, Magazinel.dat, Magazine2.dat, Magazine3.dat, Magazine4.dat, Magazine5.datand Magazine6.dat. In this problem, you will utilize the built in string class, its constructors, some of its methods and operators. For more on the string class, please refer to Prata, Chapter 16 and the link http: //www.cplusplus.com/reference/string/string/ (6 points)Explanation / Answer
public class RansomNote1 {
public static void main(String[] args) {
if(args.length < 2) {
System.out.println(" enter ransom note1 and the " +
"content of the magazines in quotes.");
System.exit(1);
}
String note = args[0];
String mag = args[1];
System.out.println("Ransom note1: " + note);
System.out.println("Magazine content: " + mag);
System.out.println("Can construct ransom note from mag contents?");
System.out.println(ransomNote3(note, mag));
}
public static boolean ransomNote2(String note, String mag)
{
int[] count = new int[256];
for(int i = 0; i < mag.length(); i++) {
int c = mag.charAt(i);
count[c]++;
}
for(int i = 0; i < note.length(); i++) {
int c = note.charAt(i);
count[c]--;
if(count[c] < 0)
return false;
}
return true;
}
public static boolean ransomNote3(String note, String mag)
{
int[] count = new int[256];
int p = 0;
int q = 0;
while(p < note.length()) {
int nchar = note.charAt(p);
if(count[nchar] > 0)
{
count[nchar]--;
n++;
}
else {
while(q < mag.length() && mag.charAt(q) != nchar) {int mchar = mag.charAt(q);
count[mchar]++;
s
q++;
}
if(q >= mag.length())
return false;
p++;
q++;
}
}
return true;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.