Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions ransom/Ransom.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import java.util.HashMap;
import java.util.Map;

public class Ransom {
public static boolean canRansom(String magazine, String ransom) {
if (magazine.length() < ransom.length()) {
return false;
}
Map<String, Integer> magMap = new HashMap<>();
for (String word : magazine.split(" ")) {
if (magMap.containsKey(word)) {
magMap.put(word, magMap.get(word) + 1);
} else {
magMap.put(word, 1);
}
}

for (String word : ransom.split(" ")) {
if (!magMap.containsKey(word)) {
return false;
}
if (magMap.get(word) == 1) {
magMap.remove(word);
} else {
magMap.put(word, magMap.get(word) - 1);
}
}
return true;
}
}
16 changes: 16 additions & 0 deletions ransom/RansomTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import org.testng.Assert;
import org.testng.annotations.Test;

public class RansomTest {

@Test
public void testCanRansom() throws Exception {
boolean yayRansom = Ransom.canRansom("dying wool is what you will be doing", "you will be dying");
System.out.println("You " + (yayRansom ? "can" : "can't") + " write a ransom letter");
boolean failRansom = Ransom.canRansom("can you believe Justin Beiber's new shirt?", "give me all your money");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😆

System.out.println("You " + (failRansom ? "can" : "can't") + " write a ransom letter");

Assert.assertTrue(yayRansom);
Assert.assertFalse(failRansom);
}
}