Created
April 3, 2019 14:41
-
-
Save nicola88/5e97ed6c18ae36b57af9ced33fd0e74d to your computer and use it in GitHub Desktop.
String replacement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def concat(heads: List[Char], tails: List[String]): List[String] = { | |
for { | |
h <- heads | |
t <- tails | |
} yield h.toString + t | |
} | |
def replace(str: String, replacement_rules: Map[Char, List[Char]], max_replacements: Int): List[String] = { | |
def replaceStep(str: String, replacements_count: Int): List[String] = { | |
if (replacements_count == 0) List(str) | |
else if (str.length == 0) List() | |
else { | |
val head = str.charAt(0) | |
val tail = str.substring(1) | |
val substitutions = replacement_rules.getOrElse(head, List()) | |
concat(List(head), replaceStep(tail, replacements_count)) ::: | |
concat(substitutions, replaceStep(tail, replacements_count - 1)) | |
} | |
} | |
(0 to max_replacements).flatMap(replacements => replaceStep(str, replacements)).toList | |
} | |
val replacement_rules = Map('i' -> List('x','y'), 'e' -> List('3', '5')) | |
print(replace("casine", replacement_rules, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment