Skip to content

Instantly share code, notes, and snippets.

@Rayi
Created November 5, 2012 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rayi/4017251 to your computer and use it in GitHub Desktop.
Save Rayi/4017251 to your computer and use it in GitHub Desktop.
Mess up words but readable.
class Program
{
static void Main(string[] args)
{
string paragraph = "The phrase \"Gangnam Style\" is a Korean neologism that refers to a lifestyle associated with the Gangnam district of Seoul. The song and its accompanying music video went viral in August 2012 and have influenced popular culture since then. \"Gangnam Style\" is considered by some to be a worldwide phenomenon, while others have praised \"Gangnam Style\" for its catchy beat and PSY's amusing dance moves in the music video and during live performances. On September 17, the song was nominated for Best Video at the upcoming 2012 MTV Europe Music Awards to be held in Frankfurt, Germany. On September 20, 2012, \"Gangnam Style\" was recognized by Guinness World Records as the most \"liked\" video in YouTube history.";
Console.WriteLine("-----Paragraph before process:-----");
Console.WriteLine(paragraph);
string result = MakeRandom(paragraph);
Console.WriteLine("-----Paragraph after process:-----");
Console.WriteLine(result);
Console.ReadKey(true);
}
public static string MakeRandom(string content)
{
char[] p = content.ToCharArray();
Random rnd = new Random(DateTime.Now.Millisecond);
int index = 0;
int begin = 0;
int end = 0;
while (index < p.Length)
{
if (CharIsLetter(p[index]))
{
begin = index;
//声明截取索引
int cutIndex = begin;
//这个循环的作用就是确定cutIndex所对应的char是不是字母,
//如果不是字母,那么就可以确定从begin~cutIndex之间是一个word.
while (cutIndex < p.Length)
{
if (!CharIsLetter(p[cutIndex]))
break;
cutIndex++;
}
if (cutIndex < p.Length)
{
end = cutIndex;
//把截取出来的word进行随机置换
ScrewUpTheWord(p, begin, end - 1, rnd);
//这时候把index设置为end,表明这个word已经被处理过了,让index保持在非字母的位置上.
index = end;
}
}
index++;
}
return String.Concat(p);
}
private static void ScrewUpTheWord(char[] p, int startIndex, int endIndex, Random rnd)
{
//如果这个word的长度小于或等于3就没必要执行这个操作了.
if (endIndex - startIndex < 3)
return;
//做了一个简单的置换次数设定.
int times = (endIndex - startIndex) / 2;
if (times == 0)
times = 1;
//第一个字母和最后一个字母是不能动的.但是因为Random.NextDouble()不可能达到1.0,也就是置换的时候
//永远不可能随机到endIndex,所以不用写endIndex--
startIndex++;
for (int i = 0; i < times; i++)
{
var idx1 = GetRangedRandomNumber(rnd, startIndex, endIndex);
var idx2 = GetRangedRandomNumber(rnd, startIndex, endIndex);
char tmp = p[idx1];
p[idx1] = p[idx2];
p[idx2] = tmp;
}
}
private static bool CharIsLetter(char c)
{
return (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
}
private static int GetRangedRandomNumber(Random rnd, int start, int end)
{
return (int)(rnd.NextDouble() * (end - start)) + start;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment