OT: Replacement

  • Thread starter Thread starter Ulf Christenson
  • Start date Start date
U

Ulf Christenson

Hello!
I would like to get all replacements of a letter in a word.
For example "a" can be treated as "e" as well and vice versa
I have the word "abcdefabcdefabcdef".
From this word I would like to get the following "equivalents":

1) "AbcdEfAbcdEfAbcdEf"
2) "EbcdEfAbcdEfAbcdEf"
3) "EbcdAfAbcdEfAbcdEf"
4) "EbcdAfEbcdEfAbcdEf"
5) "EbcdAfEbcdAfAbcdEf"
etc...

But I don't really know how I can put this into a function or call.
Ulf
 
Hi Ulf,

i'm sorry for that i have no visual basic .net development environment
at present time, but the following c# class will do what you want, given
that i understood your requirement right :

private class StringReplacementPermuter
{
private char[] equiChar;
private string inputString;
private int[] indexIntoString;
private int[] indexIntoChar;
public StringReplacementPermuter(string inputString, char
e, char a)
{
equiChar = new char[] { e, a };
this.inputString = inputString;
}

public IEnumerable<string> Permute()
{
Prepare();

return GetReplacementStrings(0);
}

private void Prepare()
{
List<int> occurenceList = new List<int>();
int occurrenceAt = -1;
while ((occurrenceAt = inputString.IndexOfAny(equiChar,
occurrenceAt + 1)) != -1)
{
occurenceList.Add(occurrenceAt);
}

indexIntoString = occurenceList.ToArray();
indexIntoChar = new int[indexIntoString.Length];
}

private IEnumerable<string> GetReplacementStrings(int loop)
{
if (loop == indexIntoString.Length)
{
yield return ReplaceByMap();
}
else
{
for (int i = 0; i < equiChar.Length; i++)
{
indexIntoChar[loop] = i;

foreach (string os in
GetReplacementStrings(loop + 1))
{
yield return os;
}
}

indexIntoChar[loop] = 0;
}
}


private string ReplaceByMap()
{
StringBuilder s = new StringBuilder(inputString);

for (int j = 0; j < indexIntoChar.Length; j++)
{
s[indexIntoString[j]] = equiChar[indexIntoChar[j]];
}

return s.ToString();
}

}

static void Main(string[] args)
{
foreach (string s in new StringReplacementPermuter("abef",
'a', 'e').Permute())
{
Console.WriteLine(s);
}

Console.Read();
}
}

I know, that that there are some tools on the net, to convert this code
to vb.net automatically. This code could be optimized a little more, but
i think this way it is easier to understand

Philipp
 
Back
Top