2014-05-16 66 views
-5

我想使代码变得简单:在英语上记住单词,并随机排列单词的所有字符。对于激烈的,这个词:“qweasdzxc”应该像这样表示:“adwseqzcx”(随机)。 因此代码:如何使数组的随机循环

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace randomLoop 
{ 
    class Program 
{ 
    static void Main(string[] args) 
    { 
     string s = "qweasdzxc"; 
     string[] q = newArray(s); 
     for (int i = 1; i < s.Length - 1; i++) 
     { 
      Console.Write(q[i]); 
     } 
    } 

    public static char[] getArrayofstring(string s) 
    { 
     char[] c = s.ToCharArray(); 
     return c; 

    } 

    public static Random rnd = new Random(); 

    public static string[] charAndNumber(char c, int lengthOftheWord)//0-char 1-integer 
    { 
     string[] array = new string[2]; 
     array[0] = c.ToString(); 
     array[1] = (rnd.Next(lengthOftheWord)).ToString(); 
     return array; 

    } 

    public static string[] newArray(string s) 
    { 
     string[] c = new string[s.Length]; 
     int j = 1; 
     string[] q = charAndNumber(s[j], s.Length - 1); 

     for (int i = 1; i < c.Length - 1; i++) 
     { 
      c[i] = ""; 

     } 
     int e = 1; 

     while (e.ToString() != q[1]) 
     { 

      c[e] = q[0]; 
      j++;//for the character s[j] see up 
      e++;//for the loop 
     } 


     return c; 
    } 
} 

}

+3

你究竟在哪里卡住? –

+0

我没有看到问题... –

+0

请帮忙!!!! – user3646157

回答

0

看来你只是想洗牌的人物,并生成一个新的string.You可以使用使用Fisher-Yates洗牌算法(从this答案的方法,我修改它为您的情况点点):

public static void Shuffle<T>(this T[] source) 
{ 
    Random rng = new Random(); 
    int n = source.Length; 
    while (n > 1) { 
     n--; 
     int k = rng.Next(n + 1); 
     T value = source[k]; 
     source[k] = source[n]; 
     source[n] = value; 
    } 
} 

然后,只需使用它:

string s = "qweasdzxc"; 
char[] chars = s.ToCharArray(); 
chars.Shuffle(); 
string random = new string(chars); 

还记得这是一个扩展方法,所以你需要把它放到一个公众静态类。

+2

+1的工作实现。在这种情况下,它感觉就像缺少了“教一个人钓鱼”那样,但是OP在这方面并没有给我们太多的帮助。 – BradleyDotNET

+0

http://www.dotnetperls.com/fisher-yates-shuffle – user3646157