Print string replacement

Many languages ​​have a function that does something like this:

replace(string, pattern, replacement)
replace("aSb", "S", "ba")
  => "abab"

But is there a way to write a function that does the opposite?

derive_replacement(before_string, after_string)
derive_replacement("space ba ba space ba", "fact ba ba fact ba")
  => ("space", "fact")

I understand that there are several ways to do this, which will return a rule that will lead you from one line to another, but I'm looking for the shortest one. For example, both of the following technologies will technically work, but will not find the shortest string:

derive(before, after) {
    return (before, after)
}

derive(before, after) {
    first_diff = len(commonprefix(before, after))
    last_diff = len(commonsuffix(before, after))
    return (before[first_diff:len(before) - last_diff],
        after[first_diff:len(after) - last_diff])
}

I'm looking for a general way to do this, but if that helps, I'm trying to get this to work in Haskell. However, any language or even pseudo-code will be sufficient.

+4
source share
1 answer

This is not an easy problem.

. , ,

( "foo foo foo", "foo baz foo" ).

, , . ( c-like psuedocode)

if (before==after) return "",""
for (pl=1;pl<(len(before)-1);pl++) {
  for (ps=0;ps<=len(before)-pl;ps++) {
    for (rl=1;rl<len(after)-ps;rl++) {
      pattern=substr(before,ps,pl);
      replacement=substr(after,ps,rl);
      if (replace(before,pattern,replacement) == after) {
        return(pattern,replacement);
      }
    }
  }
}
return (before,after);

, .

+1

Source: https://habr.com/ru/post/1611044/


All Articles