1
$\begingroup$

Let's say I have a group of X's characters that I want to cut down. I want to use a method similar to 'find-and-replace-all' tool from Word, which takes an amount of X's each time, deletes them, and replaces them with another, smaller amount. For example, I can state that I want an amount of 8 X's to be replaced with 5 X's from an original amount of 14 X's. This cycle happens forever, or until there isn't a sufficient remainder left to replace anymore. To visualise the example I just provided:

(XXXXXXXX)XXXXXX --> [XXXXX]XXXXXX

(XXXXXXXX)XXX --> [XXXXX]XXX

(XXXXXXXX) --> [XXXXX]

So, you start with 14 X's and end with 5 X's, and the process carried out here can be summarised as '14, 11, 8, 5'. The process that was undergoing in terms of finding and replacing can be described as (8,5) as 8 X's are replaced with 5 each time.

If you guys need a more mathematical way of me putting it, divide the amount of X's by a in (a,b), subtract the remainder in integer form, multiply the total by b, then finally add the remainder to the total. Continue this until Amount of X's/a < 1.

Now, I was wondering if there is a way to do this in Wolfram Alpha/Mathematica. Can anyone help me do this. If not, can anyone redirect me to an appropriate scripting language that can handle this? Thank you.

$\endgroup$
1
  • $\begingroup$ it's not clear if your algorithm needs to be recursive or one-off and if it needs to be recursive, what should happen with intermediate results; also, the end result seems that it can be achieved using the "Find and replace" dialog (Ctrl+F on win); on first sight, you could benefit from reading about ReplaceAll and StringExpression. $\endgroup$
    – user42582
    Commented May 26, 2019 at 19:44

1 Answer 1

7
$\begingroup$

You can use StringReplace to define a function to make the replacement and use FixedPointList to get the result of applying the function recursively to an input list:

ClearAll[sR]
sR = StringReplace[StartOfString ~~ Repeated["X", {8}] :> "XXXXX"];

str = StringJoin@ConstantArray["X", 14]

"XXXXXXXXXXXXXX"

FixedPointList[sR, str]

{"XXXXXXXXXXXXXX", "XXXXXXXXXXX", "XXXXXXXX", "XXXXX", "XXXXX"}

FixedPoint[sR, str]

"XXXXX"

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.