分享

用WebService实现从指定数组中选择出任意个元素(续)

 昵称10504424 2013-02-20

本文是对 用WebService实现从指定数组中选择出任意个元素 一文的补充,添加了重复约束检查功能: 

        

  1. using System;  
  2. using System.Collections;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Services;  
  8. using System.Web.Services.Protocols;  
  9. using System.Xml.Linq;  
  10.   
  11. namespace RandomWS  
  12. {  
  13.     /// <summary>   
  14.     /// Summary description for Service1   
  15.     /// </summary>   
  16.     [WebService(Namespace = "http:///")]  
  17.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  18.     [ToolboxItem(false)]  
  19.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.    
  20.     // [System.Web.Script.Services.ScriptService]   
  21.     public class Service1 : System.Web.Services.WebService  
  22.     {  
  23.   
  24.         [WebMethod]  
  25.         public string[] GenerateRandomColourArray(int numberOfRandomColours)  
  26.         {  
  27.             if (numberOfRandomColours > 13)  
  28.                 return null;  
  29.             string[] colourPalette = { "Red""Blue""White""Black""Green""Yellow""Purple""Pink""Brown""Grey""Orange""Cyan""Magenta" };  
  30.             Random random = new Random();  
  31.             string[] arr = new string[numberOfRandomColours];  
  32.             bool[] br = new bool[13];//初始值都是false   
  33.             for (int j = 0; j < numberOfRandomColours; j++)  
  34.             {  
  35.                int i = 0;  
  36.                bool b = false;  
  37.                while (b == false)  
  38.                {  
  39.                    i = random.Next(0, 13);  
  40.                    if (br[i] == false)//在br数组中查找br[i]的值是否为false,如果为false,表示i值是第一次得到,如果是true,表示i值已经存在了,就不跳出while循环,继续执行while。   
  41.                        b = true;  
  42.                }  
  43.                br[i] = true;//初次得到i的值时,将br[i]赋值为true。   
  44.                arr[j] = colourPalette[i];//取出colourPalette数组中的颜色,放在arr数组中。   
  45.             }  
  46.             return arr;//返回存放随机找到的颜色的数组arr。   
  47.         }  
  48.           
  49.     }  
  50. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多