I am experiencing a problem that I am not sure how to solve and I hope someone here can help me. Currently I have a string variable and later I replace the letters in the string with underscores like the following:
var str = "Hello playground"
let replace = str.replacingOccurrences(of: "\\S", with: "_", options: .regularExpression)
print(str)
Know I would like to randomly generate 25 % of the characters in str (In this case 16 * 0,25 = 4) so it later prints something like these examples:
str = "H__l_ ___yg_____"
str = "_____ play______"
str = "__ll_ ____g____d"
Does anyone have any ideas of how to do this?
The idea is same as above methods, just with a little less code.
You can use a 3-steps algorithm that does the following:
The code could look something like this:
Sample results:
First you need to get the indices of your string and filter the ones that are letters. Then you can shuffle the result and pick the number of elements (%) minus the number of spaces in the original string, iterate through the result replacing the resulting ranges with the underscore. You can extending RangeReplaceable protocol to be able to use it with substrings as well:
Similarly as in Replace specific characters in string, you can map each character, and combine the result to a string. But now you have to keep track of the (remaining) numbers of non-space characters, and the (remaining) numbers of characters that should be displayed. For each (non-space) character it is randomly decided whether to display (keep) it or to replace it by an underscore.
I just came up with the following solution:
Output:
A possible solution:
The idea behind it: Use the same Regular Expression pattern as the one you used.
Pick up n elements in it (in your case 1/4)
Replace every character that isn't in that short list.
Now that you got the idea, it's even faster replacing the for loop with
Thanks to @Martin R's comment for pointing it out.
Output (done 10 times):
You'll see that there is a little difference from your expected result, it's because
matches.count
== 15, so 1/4 of them should be what? It's up to you there to do the correct calculation according to your needs (round up?, etc.) since you didn't specified it.Note that if you don't want to round up, you could also do the reverse, use the randomed for the one to not replace, and then the round might play in your favor.