【问题标题】:Shuffle string c#随机字符串 c#
【发布时间】:2011-01-19 19:45:18
【问题描述】:

我想知道随机字符串

示例字符串

string word;

//I want to shuffle it
word = "hello"  

我可以得到:

rand == "ohlel"
rand == "lleho"
etc.

【问题讨论】:

    标签: c# algorithm ironpython


    【解决方案1】:

    这个解决方案(以扩展方法的形式)很好:

        public static string  Shuffle(this string str)
        {
            char[] array = str.ToCharArray();
            Random rng = new Random();
            int n = array.Length;
            while (n > 1)
            {
                n--;
                int k = rng.Next(n + 1);
                var value = array[k];
                array[k] = array[n];
                array[n] = value;
            }
            return new string(array);
        }
    

    【讨论】:

    • 对实现者的注意——在流程实例中多次初始化随机并不是好的做法。线 Random rng = new Random();不应该在方法中,而是作为静态变量
    【解决方案2】:

    C#:

    string str = "hello";
    
    // The random number sequence
    Random num = new Random();
    
    // Create new string from the reordered char array
    string rand = new string(str.ToCharArray().
                    OrderBy(s => (num.Next(2) % 2) == 0).ToArray());
    

    【讨论】:

    • 这不会产生好的随机结果。根据 MSDN,OrderBy 将使用稳定的排序并保留那些被赋予相同值的字符的顺序。要将“hello”中的“h”放在最后,“h”需要滚动“false”,其余的滚动“true”。然而,结果将是“elloh”,这不是很令人兴奋。 msdn.microsoft.com/en-us/library/bb534966.aspx
    【解决方案3】:

    我用这个扩展来完成这个:

    public static class Extensions{
        public static string Scramble(this string s){
            return new string(s.ToCharArray().OrderBy(x=>Guid.NewGuid()).ToArray());
        }
    }
    

    【讨论】:

    • 说真的,我想知道这有什么问题。它速度非常快,只有一行代码,易于阅读,而且很有效。
    【解决方案4】:

    试试 Fisher-Yates Shuffle:

    class Shuffle
    {
        static System.Random rnd = new System.Random();
    
        static void Fisher_Yates(int[] array)
        {
            int arraysize = array.Length;
            int random;
            int temp;
    
            for (int i = 0; i < arraysize; i++)
            {
                random = i + (int)(rnd.NextDouble() * (arraysize - i));
    
                temp = array[random];
                array[random] = array[i];
                array[i] = temp;
            }
        }
    
        public static string StringMixer(string s)
        {
            string output = "";
            int arraysize = s.Length;
            int[] randomArray = new int[arraysize];
    
            for (int i = 0; i < arraysize; i++)
            {
                randomArray[i] = i;
            }
    
            Fisher_Yates(randomArray);
    
            for (int i = 0; i < arraysize; i++)
            {
                output += s[randomArray[i]];
            }
    
            return output;
        }
    }
    
    class Program
    {
        static void Main()
        {
            string original = "Hello World!";
    
            string mixedOriginal = Shuffle.StringMixer(original);
    
            System.Console.WriteLine("The original string: {0}", original);
            System.Console.WriteLine("A mix of characters from the original string: {0}", mixedOriginal);
    
            System.Console.ReadKey();
        }
    }
    

    【讨论】:

    【解决方案5】:

    您正在寻找类似Fisher–Yates shuffle 的东西。该页面上实际上有一个 Python 示例:

    import random
    
    def shuffle(x):
        for i in reversed(range(1, len(x))):
            # pick an element in x[:i+1] with which to exchange x[i]
            j = random.randrange(i+1)
            x[i], x[j] = x[j], x[i]
    

    编辑:由于您的问题同时被标记为ironpython 和c#,因此这里还有一个Java 示例,它很容易转换为C#。

    【讨论】:

      【解决方案6】:

      需要注意的一点是,输入字符串可能包含代理对和组合变音符号等内容。如果这些是一个问题,您可能想尝试改组文本元素:

      using System;
      using System.Globalization;
      using System.Linq;
      using System.Text;
      
      public static class StringExtensions
      {
          public static string ShuffleByTextElements(this string source, Random random)
          {
              if (source == null) throw new ArgumentNullException(nameof(source));
              if (random == null) throw new ArgumentNullException(nameof(random));
      
              var info = new StringInfo(source);
              var indices = Enumerable.Range(0, info.LengthInTextElements).ToArray();
      
              // Fisher-Yates shuffle
              for (var i = indices.Length; i-- > 1;)
              {
                  var j = random.Next(i + 1);
                  if (i != j)
                  {
                      var temp = indices[i];
                      indices[i] = indices[j];
                      indices[j] = temp;
                  }
              }
      
              var builder = new StringBuilder(source.Length);
              foreach (var index in indices)
              {
                  builder.Append(info.SubstringByTextElements(index, 1));
              }
      
              return builder.ToString();
          }
      }
      

      请注意,上面的代码仍然不能正确处理某些 Unicode 功能,例如双向覆盖,也不能处理某些字母形式取决于它在单词中的位置的脚本的细节。这方面的一个例子是希腊小写 sigma,它被编码为 U+03C3 GREEK SMALL LETTER SIGMA (σ),除了在单词的末尾使用 U+03C2 GREEK SMALL LETTER FINAL SIGMA (ς) 代替。

      【讨论】:

        【解决方案7】:

        灵感来自 tsql' order by newid()

        static string shuffle(string input)
        {
            var q = from c in input.ToCharArray()
                    orderby Guid.NewGuid()
                    select c;
            string s = string.Empty;
            foreach (var r in q)
                s += r;
            return s;
        }
        

        【讨论】:

          【解决方案8】:

          打乱字符串或字符串列表的最佳方式是使用这种方式。在这里你不会得到重复:

          class CardsDeck
          {
              public static Random r = new Random();
          
              private static List<string> cards = new List<string>{ "♣ King", "♣ Queen", "♣ Jack", " ♣", "♣ 7", "♣ 8", "♣ 9", "♣ 10",
                                                                    "♦ King", "♦ Queen", "♦ Jack", " ♦", "♦ 7", "♦ 8", "♦ 9", "♦ 10",
                                                                    "♥ King", "♥ Queen", "♥ Jack", " ♥", "♥ 7", "♥ 8", "♥ 9", "♥ 10",
                                                                    "♠ King", "♠ Queen", "♠ Jack", " ♠", "♠ 7", "♠ 8", "♠ 9", "♠ 10" };
              public string ReceiveCards()
              {
                  if (cards.Count > 0)
                  {
                      int index = r.Next(cards.Count);
                      var card = cards[index];
                      cards.RemoveAt(index);
                      return card;
                  }
                  else
                  {
                      return "";
                  }
              }
          }
          

          【讨论】:

          • 不,这不是最好的方法。尽管它避免了重复,但它的效率非常低。其他地方提到的 Fisher-Yates 洗牌是一种更好的方法。
          【解决方案9】:

          你可以试试这样的..

          class Program
          {
              static bool IsPositionfilled(int Position, List<int> WordPositions)
              {
                  return WordPositions.Exists(a => a == Position);
              }
          
              public static string shufflestring(string word)
              {
                  List<int> WordPositions = new List<int>();
                  Random r = new Random();
                  string shuffledstring = null;
                  foreach (char c in word)
                  {
                      while (true)
                      {
          
                          int position = r.Next(word.Length);
                          if (!IsPositionfilled(position, WordPositions))
                          {
                              shuffledstring += word[position];
                              WordPositions.Add(position);
                              break;
                          }
                      }
          
          
                  }
                  return shuffledstring;
              }
              static void Main(string[] args)
              {
          
                  string word = "Hel";
                  Hashtable h = new Hashtable();
                  for (int count = 0; count < 1000; count++)
                  {
                      Thread.Sleep(1);
                      string shuffledstring = shufflestring(word);
                      if (h.Contains(shuffledstring))
                          h[shuffledstring] = ((int)h[shuffledstring]) + 1;
                      else
                          h.Add(shuffledstring,1);
                  }
          
                  Console.WriteLine(word);
                  foreach (DictionaryEntry e in h)
                  {
                      Console.WriteLine(e.Key.ToString() + " , " + e.Value.ToString()); 
                  }
              }
          }
          

          【讨论】:

            【解决方案10】:
            class Program
            {
            
                static void Main(string[] args)
                {
                    string word = "hello";
                    string temp = word;
                    string result = string.Empty;
                    Random rand = new Random();
            
                    for (int a = 0; a < word.Length; a++)
                    {
                        //multiplied by a number to get a better result, it was less likely for the last index to be picked
                        int temp1 = rand.Next(0, (temp.Length - 1) * 3);
            
                        result += temp[temp1 % temp.Length];
                        temp = temp.Remove(temp1 % temp.Length, 1);
                    }
                    Console.WriteLine(result);
                }
            }
            

            【讨论】:

              【解决方案11】:

              我尝试了老派的做法,这个很好用。

                  static void Main()
                  {        
                      string input = "hello";
                      string output = "";
                      int ranIndex = 0;
                      List<int> indexes = new List<int>();
                      char[] split = input.ToCharArray();
                      Random ran = new Random();
              
                      for (int i = 0; i < input.Length; i++) 
                      {
                          ranIndex = ran.Next(0, input.Length);
              
                          if (!indexes.Contains(ranIndex))
                          {
                              indexes.Add(ranIndex);
                          }
                          else 
                          {
                              i--;
                          }
                      }
              
                      foreach (int value in indexes) 
                      {
                          output += split[value];
                      }
              
                          Console.WriteLine(output);
                          Console.ReadLine();
                  }
              

              【讨论】:

                【解决方案12】:

                费舍尔-耶茨

                static Random rand = new Random();
                public static string ShuffleString(string s)
                {
                    if (string.IsNullOrEmpty(s))
                        return s;
                    char[] chars = s.ToCharArray();
                    char c;
                    int j;
                    for(int i = chars.Length - 1; i > 0; i--)
                    {
                        j = rand.Next(i + 1);  // Next max is exclusive
                        if (j == i)
                            continue;
                        c = chars[j];
                        chars[j] = chars[i];
                        chars[i] = c;
                    }
                    return chars.ToString();
                }
                

                【讨论】:

                • 运行良好,但 chars.ToString() 总是返回文字“System.Char[]”。 return chars.ToString(); 应该是 return new string(chars);
                • 这不会保留原始设置,它会覆盖未使用的字符。
                猜你喜欢
                • 2020-11-22
                • 1970-01-01
                • 2019-08-07
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-04-28
                • 2013-10-14
                • 1970-01-01
                相关资源
                最近更新 更多