Word Scrambling Fun

Sunday, February 19, 2006

I am a very briong prseon. To porve to eoyrvene that I sepak the turth I will dcseribe the way I sepnt a few munties of my life Sudnay ngiht.

A wihle back I read an actrile aobut how well popele can dhpcieer smlcbared wrods. It truns out that ppoele can sitll uarsntdend a srmcblaed word as long as you keep the frist and last letetrs the same.
I find this very inseettring from a pocsyholgy pecesrtpive. But, that is nteiher here nor tehre. I diecded I sohuld wirte a pgroram to do it for me. Why would I "watse" my time doing siheotmng so folvroius, uelsess, and "sutpid"? I wtaned to. So I sat down and hrmemaed out the prgroam in C# 2.0. (I cohose C# 2.0 because it was at hand, nhtiong more.) I would conidser it ftfeien munties well spent.


private void replace(ref string s, int startpos,string newvalue)
{
StringBuilder sb = new StringBuilder();
if(startpos > 0) sb.Append(s.Substring(0, startpos));
sb.Append(newvalue);
if (startpos + newvalue.Length < s.Length) sb.Append(s.Substring(startpos + newvalue.Length));
s = sb.ToString();
}

private string scramblestring(string s)
{
if (s.Length > 3)
{
StringBuilder sb = new StringBuilder();
Random r = new Random();
do
{
sb = new StringBuilder();
int val = 0;
List ca = new List(s.ToCharArray(1, s.Length - 2));
sb.Append(s[0]);
while (ca.Count > 0)
{

val = r.Next(0, ca.Count-1);
sb.Append(ca[val]);
ca.RemoveAt(val);
}
sb.Append(s[s.Length-1]);
}while(s.Length > 4 && sb.ToString() == s);
return sb.ToString();
}
else
{
return s;
}
}

private string scramble(string s)
{
Regex r = new Regex(@"\b[^\W\d]{4,}\b");
MatchCollection m = r.Matches(s);
if (m.Count > 0)
{
foreach (Match ma in m)
{
replace(ref s, ma.Index, scramblestring(ma.Value));
}
}
return s;
}