有好几个字符串,其中有重复的,想随机重新排列,怎么办?
比如"加","拿","大","大","大"……
现在是“加拿大大大”
随机重排,并要求重字调开,并且首字不能为“加”
比如可以生成:大加大拿大
大拿大加大……
一次一个样。

解决方案 »

  1.   

    try:            string[] array = { "加", "拿", "大", "大", "大" };
                List<string> list = new List<string>(array);
                StringBuilder sb = new StringBuilder();
                Random r = new Random(Environment.TickCount);
                int i = -1;
                while (list.Count > 1)
                {
                    i = r.Next(0, list.Count);
                    sb.Append(list[i]);
                    list.RemoveAt(i);
                }
                sb.Append(list[0]);
                Console.WriteLine(sb.ToString());
      

  2.   

    while (list.Count > 1)
                {
                    i = r.Next(0, list.Count);
                    sb.Append(list[i]);
                    list.RemoveAt(i);
                }好熟悉的用法...
      

  3.   

                string[] array = { "加", "拿", "大", "大", "大" };
                List<string> list = new List<string>(array);
                StringBuilder sb = new StringBuilder();
                Random r = new Random(Environment.TickCount);
                int i = -1;
                while (list.Count > 1)
                {
                    i = r.Next(0, list.Count);
                    sb.Append(list[i]);
                    list.RemoveAt(i);
                }
                sb.Append(list[0]);
                Console.WriteLine(sb.ToString());
      

  4.   

    try...
    string[] array = { "加", "拿", "大", "大", "大" };
                List<string> list;
                string sb="";
                Random r = new Random(Environment.TickCount);
                int i = -1;
                bool B=true;
                while (B)
                {
                    list = new List<string>(array);
                    sb = "";
                    
                    while (list.Count > 0)
                    {
                        i = r.Next(0, list.Count);
                        sb += list[i];
                        list.RemoveAt(i);
                    }
                    if (sb[0] != '加')
                    {
                        int j;
                        for (j = 0; j < array.Length-1; j++)
                            if (sb[j] == sb[j + 1])
                                break;
                        if (j == array.Length - 1)
                            B = false;
                    }
                }
                Console.WriteLine(sb.ToString());
      

  5.   

    用最笨的方法:
    1.首先以“加”为开始的所有字符全排列,生成很多字符串
    2.相邻字符不为重判断如果性能要求高,可以进一步优化,字符串查找比较采用hashtable