I have been trying to read a string and then one by one for each character run a random number if a 5 is generated then change the character from a 1 to a 0 or vice versa. I feel I am almost there this is my thirds attempt at this, but I have a slight problem with writing to the index, as it tells me it is read only. Here is my code:
string mutate = "1010";
for (int i = 0; i < 4; i++)
{
int MutProbablity = random.Next(1, 1000);
if (MutProbablity == 5)
{
if (mutate[i] == '0')
{
mutate[i] = '1';
}
else if (mutate[i] == '1')
{
mutate[i] = '0';
}
}
}
This is my error:
Property or indexer '
string.this[int]' cannot be assigned to -- it is read only
Can someone tell me how I can get around this issue or perhaps suggest a different way I can achieve my goal?
Strings in .NET are immutable, so you won't be able to modify any characters, but you can accomplish your goal by first converting it to a char[], which is mutable.
Like this:
var chars = mutate.ToCharArray(); // convert to char[]
for (int i = 0; i < 4; i++)
{
int MutProbablity = random.Next(1, 1000);
if (MutProbablity == 5)
{
if (chars[i] == '0')
{
chars[i] = '1';
}
else if (chars[i] == '1')
{
chars[i] = '0';
}
}
}
mutate = new String(chars); // convert to back to string
Another way to do this would be to use Linq (and an admittedly very ugly string of ternary operators).
var new string(mutate.Select(c =>
(random.Next(1, 1000) == 5) ? ((c == '0') ? '1' : (c == '1') ? '0' : c) : c).ToArray());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With