diff --git a/src/main/java/io/zipcoder/Problem1.java b/src/main/java/io/zipcoder/Problem1.java index 6cd6024..1e5e83e 100644 --- a/src/main/java/io/zipcoder/Problem1.java +++ b/src/main/java/io/zipcoder/Problem1.java @@ -1,4 +1,28 @@ package io.zipcoder; +import java.util.*; + public class Problem1 { + + public static String replaceWithIteration(HashMap map, String input) { + Set keys = map.keySet(); + for(String key : keys) { + input = input.replaceAll(key, "\\" + map.get(key)); + } + return input; + } + + public static String replaceWithRecursion(HashMap map, String input) { + Set keys = map.keySet(); + + if(keys.isEmpty()) { + return input; + } else { + String s = keys.iterator().next(); + input = input.replaceAll(s, "\\" + map.get(s)); + map.remove(s); + } + + return replaceWithRecursion(map, input); + } } diff --git a/src/test/java/io/zipcoder/Problem1Test.java b/src/test/java/io/zipcoder/Problem1Test.java index de82e99..a42b3c5 100644 --- a/src/test/java/io/zipcoder/Problem1Test.java +++ b/src/test/java/io/zipcoder/Problem1Test.java @@ -1,4 +1,43 @@ package io.zipcoder; +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; + public class Problem1Test { + + @Test + public void replaceTest() { + + HashMap map = new HashMap<>(); + map.put("f", "7"); + map.put("s", "$"); + map.put("1", "!"); + map.put("a", "@"); + + String input = "the farmer went to the store to get 1 dollar’s worth of fertilizer"; + String expected = "the 7@rmer went to the $tore to get ! doll@r’$ worth o7 7ertilizer"; + + String actual = Problem1.replaceWithIteration(map, input); + + Assert.assertEquals(expected, actual); + } + + @Test + public void replaceTest2() { + HashMap map = new HashMap<>(); + map.put("f", "7"); + map.put("s", "$"); + map.put("1", "!"); + map.put("a", "@"); + + String input = "the farmer went to the store to get 1 dollar’s worth of fertilizer"; + String expected = "the 7@rmer went to the $tore to get ! doll@r’$ worth o7 7ertilizer"; + + + String actual = Problem1.replaceWithRecursion(map, input); + + Assert.assertEquals(expected, actual); + } }