Skip to content
Open

H #27

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
24 changes: 24 additions & 0 deletions src/main/java/io/zipcoder/Problem1.java
Original file line number Diff line number Diff line change
@@ -1,4 +1,28 @@
package io.zipcoder;

import java.util.*;

public class Problem1 {

public static String replaceWithIteration(HashMap<String, String> map, String input) {
Set<String> keys = map.keySet();
for(String key : keys) {
input = input.replaceAll(key, "\\" + map.get(key));
}
return input;
}

public static String replaceWithRecursion(HashMap<String, String> map, String input) {
Set<String> 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);
}
}
39 changes: 39 additions & 0 deletions src/test/java/io/zipcoder/Problem1Test.java
Original file line number Diff line number Diff line change
@@ -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<String, String> 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<String, String> 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);
}
}