How to resolve the algorithm Selectively replace multiple instances of a character within a string step by step in the Factor programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Selectively replace multiple instances of a character within a string step by step in the Factor programming language
Table of Contents
Problem Statement
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it. Given the string: "abracadabra", replace programatically:
Note that there is no replacement for the third 'a', second 'b' or first 'r'. The answer should, of course, be : "AErBcadCbFD".
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Selectively replace multiple instances of a character within a string step by step in the Factor programming language
Source code in the factor programming language
USING: assocs formatting grouping kernel random sequences ;
CONSTANT: instrs {
CHAR: a 1 CHAR: A
CHAR: a 2 CHAR: B
CHAR: a 4 CHAR: C
CHAR: a 5 CHAR: D
CHAR: b 1 CHAR: E
CHAR: r 2 CHAR: F
}
: counts ( seq -- assoc )
H{ } clone swap [ 2dup swap inc-at dupd of ] zip-with nip ;
: replace-nths ( seq instrs -- seq' )
[ counts ] dip 3 group [ f suffix 2 group ] map substitute keys ;
: test ( str -- )
dup instrs replace-nths "" like "%s -> %s\n" printf ;
"abracadabra" test
"abracadabra" randomize test
You may also check:How to resolve the algorithm A+B step by step in the Ra programming language
You may also check:How to resolve the algorithm MAC vendor lookup step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the Erlang programming language
You may also check:How to resolve the algorithm Luhn test of credit card numbers step by step in the Scheme programming language
You may also check:How to resolve the algorithm Numbers which are the cube roots of the product of their proper divisors step by step in the Go programming language