Programing Challenge: Replace String Pairs

By Xah Lee. Date:

A coding challenge.

write a function “replace_string_pairs”. The function will take a ‹input string› and ‹pairs›, and returns a string.

the ‹pairs› is a list of pairs:

[
 [‹search string 1›, ‹replace string 1›]
 [‹search string 2›, ‹replace string 2›]
 [‹search string 3›, ‹replace string 3›]
 …
]

but here's the tricky part:

Once a subsring in the input string is replaced, that part is not changed again. (the replacement start with first pair, then second, etc) For example:

# -*- coding: utf-8 -*-
# python 3

replace_string_pairs("abcd", [["a", "c"], ["c", "d"]])

then, result should be "cbdd", not "dbdd".

Write this in any lang. Emacs Lisp, Perl, Python, Ruby, JavaScript, PHP, or others. The datatype for pairs can be anything appropriate for the lang. For example, nested array/list/tuple/vector. (but don't use hash table, even if your lang preserves order.)

I'll run your program in linux, on the command line, with the linux time utility.

I'll post a solution in emacs lisp in 3 days. If no solution is given in one of the language, i'll supply one, after a week.

the langs i'll be able to run are, on linux command line: