diff --git a/README.md b/README.md index 0cab3f7..a4a10ec 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,6 @@ UNIT TESTING IS MANDATORY !!! Given the following map { ‘f’ : ‘7’, ‘s’:’$’, ‘1’:’!’, ‘a’.:’@’}, your method should replace any character represented by a key in the map, with its corresponding value. -Input = “The Farmer went to the store to get 1 dollar’s worth of fertilizer” +Input = “The farmer went to the store to get 1 dollar’s worth of fertilizer” Output = “The 7@rmer went to the $tore to get ! doll@r’$ worth of 7ertilizer” diff --git a/src/main/java/io/zipcoder/Problem1.java b/src/main/java/io/zipcoder/Problem1.java index 6cd6024..d308ba5 100644 --- a/src/main/java/io/zipcoder/Problem1.java +++ b/src/main/java/io/zipcoder/Problem1.java @@ -1,4 +1,39 @@ package io.zipcoder; +import java.util.Map; + public class Problem1 { + + public String replaceByIteration(Map aMap, String input) { + StringBuilder output = new StringBuilder(); + for (String aChar : input.split("")){ + if (aMap.containsKey(aChar)){ + output.append(aMap.get(aChar)); + } + else { + output.append(aChar); + } + } + return output.toString(); + } + + public String replaceByRecursion(Map aMap, String input, String output, Integer index) { + String[] inputSplit = input.split(""); + + String currentChar = inputSplit[index]; + if (aMap.containsKey(currentChar)){ + output += aMap.get(currentChar); + } + else { + output += currentChar; + } + + if (index mapKey = new HashMap(); + + mapKey.put("f","7"); + mapKey.put("s","$"); + mapKey.put("1","!"); + mapKey.put("a","@"); + + Problem1 problem1 = new Problem1(); + + String actual = problem1.replaceByIteration(mapKey, input); + + Assert.assertEquals(expected,actual); + } + + @Test + public void replaceByRecursionTest() { + 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"; + Map mapKey = new HashMap(); + + mapKey.put("f","7"); + mapKey.put("s","$"); + mapKey.put("1","!"); + mapKey.put("a","@"); + + Problem1 problem1 = new Problem1(); + String output = ""; + + String actual = problem1.replaceByRecursion(mapKey, input, output,0); + + Assert.assertEquals(expected,actual); + } }