Dear factor list,
thought to ask for your opinion and learn something on the way:
sort of the weekly factor challenge with code I actually intend to use :)
so I'm dusting some old code, and trying to finish this last word
'replace-all'
Thought it would be atleast a nice exercise for the knowledgeable among you,
and a way for the beginners to learn by seeing different solutions and
different approaches.
here's my idea for the implementation. I have most of the supporting
words already so you can assume them to be there for you, the problem is
this word is relatively large, and it got real messy really quick. I
present my plan for solution below.
I was thinking maybe you guys can enlighten me - is there an elegant
solution,
where I can actually use some built in words?
or should I just stop whining, get busy and implement shorter words to
take care of it all.
without further ado:
input: string replace-pairs-in-a-seq
example: "abcde" { { "ab" "zy" } { "yc" "xo" } { "b" "Go go go go go go
gooo!!!" } } ! { source target } pairs
output: string
( in this case, should output: "zycde" )
the algorithm: ( the plan )
sort replace pairs by source length
get indices and their source's range (as { begin end } pairs)
remove overlaps - consider the longer source as more important. (since
we sorted it's just by order)
now that we have the list of indices+ranges,
get the indices' complement (the parts of the string that don't match)
for example: if the string has length 17, { { 3 5 } { 9 10 } }
complement => { { 0 2 } { 6 8 } { 11 16 } }
put between the complements the target from the replace-pairs.
then combine everything to one string again.
would u use locals, some kind of combinator i haven't encountered, or
entirely different algorithm? show me your elegance! ;-)
Many thanks for any attempts or suggestions
Kobi
PS: if you want more exercises I have plenty of ideas :))
------------------------------------------------------------------------------
Stay on top of everything new and different, both inside and
around Java (TM) technology - register by April 22, and save
$200 on the JavaOne (SM) conference, June 2-5, 2009, San Francisco.
300 plus technical and hands-on sessions. Register today.
Use priority code J9JMT32. http://p.sf.net/sfu/p
_______________________________________________
Factor-talk mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/factor-talk