2012-06-20
问题描述:在N种颜色中随机选择M种颜色(M<=N,无重复)
主要思路:用集合存入所有颜色,随机选择一种颜色,将已选的颜色移出集合,循环直至选出N种颜色。
代码:
1.dictionary实现
public string[] GenerateRandomColourArray(int numberOfRandomColours) { string[] colourPalette = { "Red", "Blue", "White", "Black", "Green", "Yellow", "Purple", "Pink", "Brown", "Grey", "Orange", "Cyan", "Magenta" }; Dictionary<int,string> dic=ToDic(colourPalette); Random random = new Random(); string[] arr = new string[numberOfRandomColours]; int i; for (int j = 0; j < numberOfRandomColours; j++) { i=random.Next(0,13-j); arr[j] = dic[i]; dic.Remove(i); dic=DicToDic(dic); } return arr; } public Dictionary<int,string> ToDic(string[] colors) { int length=colors.Length; Dictionary<int,string> dic=new Dictionary<int,string>(); for(int i=0;i<length;i++) { dic.Add(i,colors[i]); } return dic; } public Dictionary<int,string> DicToDic(Dictionary<int,string> origin) { Dictionary<int,string> result=new Dictionary<int,string>(); int i=0; foreach(string item in origin.Values) { result.Add(i,item); i++; } return result; }
2.List实现
public string[] GenerateRandomColourArray(int numberOfRandomColours) { string[] colourPalette = { "Red", "Blue", "White", "Black", "Green", "Yellow", "Purple", "Pink", "Brown", "Grey", "Orange", "Cyan", "Magenta" }; ArrayList arrList = new ArrayList(); foreach(string item in colourPalette) { arrList.Add(item); } Random random = new Random(); string[] arr = new string[numberOfRandomColours]; int i; for (int j = 0; j < numberOfRandomColours; j++) { i=random.Next(0,13-j); arr[j]=(string)arrList[i]; arrList.RemoveAt(i); } return arr; }
拓展与思考:
1.使用链表应该是解决此类问题比较好的方式,试着用链表解决。
2.注意代码中的数组越界问题。
3.i=random.Next(0,13-j);为什么是13而不是12,13才能运行出所有的颜色,而我理解的逻辑上应该用12.
4.可以用这种方式。先得到0-M间随机的N个无重复的数字,这些数字在作为索引找出对应的颜色。
浙公网安备 33010602011771号