Skip to content

Commit 54d63a1

Browse files
Added ransom solution
1 parent a492af3 commit 54d63a1

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

ransom/Ransom.java

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
public class Ransom {
5+
public static boolean canRansom(String magazine, String ransom) {
6+
if (magazine.length() < ransom.length()) {
7+
return false;
8+
}
9+
Map<String, Integer> magMap = new HashMap<>();
10+
for (String word : magazine.split(" ")) {
11+
if (magMap.containsKey(word)) {
12+
magMap.put(word, magMap.get(word) + 1);
13+
} else {
14+
magMap.put(word, 1);
15+
}
16+
}
17+
18+
for (String word : ransom.split(" ")) {
19+
if (!magMap.containsKey(word)) {
20+
return false;
21+
}
22+
if (magMap.get(word) == 1) {
23+
magMap.remove(word);
24+
} else {
25+
magMap.put(word, magMap.get(word) - 1);
26+
}
27+
}
28+
return true;
29+
}
30+
}

ransom/RansomTest.java

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import org.testng.Assert;
2+
import org.testng.annotations.Test;
3+
4+
public class RansomTest {
5+
6+
@Test
7+
public void testCanRansom() throws Exception {
8+
boolean yayRansom = Ransom.canRansom("dying wool is what you will be doing", "you will be dying");
9+
System.out.println("You " + (yayRansom ? "can" : "can't") + " write a ransom letter");
10+
boolean failRansom = Ransom.canRansom("can you believe Justin Beiber's new shirt?", "give me all your money");
11+
System.out.println("You " + (failRansom ? "can" : "can't") + " write a ransom letter");
12+
13+
Assert.assertTrue(yayRansom);
14+
Assert.assertFalse(failRansom);
15+
}
16+
}

0 commit comments

Comments
 (0)