1、假定已经获取题库中的提好书,并存放数组中。例如,int[] arrayKT={10,13,18,19,20,22,30,31……}。定义一个静,成员方法,该方法实现从上述数组中随机抽取给定数量(n,1<=n<=arrayKT.Length)的考题,并组成一个考题数组,。比如,随即从arrayKT中抽取5题组成考题字符串:“10,18,20,22,30”。要求,组成考题字符串中考题不重复,且一定在数组中存在。
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] s = Console.ReadLine().Split(',');
int[] a = new int[s.Length];
for (int i = 0; i < s.Length; i++)
{
a[i] = int.Parse(s[i]);
}
string ss = Console.ReadLine();
int n = int.Parse(ss);
Console.WriteLine(getKTH(n, a));
Console.ReadKey();
}
public static string getKTH(int n, int[] arrayKTH)
{
Random rd = new Random();
int[] m = new int[n];
string s = "";
bool f = true;
int count = 0;
while(count!=n)
{
int i=0;
m[i] = rd.Next(arrayKTH.Length);
for (int j = 0; j < i; j++)
{
if (m[j] == m[i])
f = false;
}
if (f)
{
s += arrayKTH[m[i]];
count++;
}
if (count!= n)
s += ",";
i++;
}
return s;
}
}
}
2、编写一个控制台程序,创建哈希集合实例,内涵部分国家的名称和首都,提示用户输入一个国家名称,则在河西集合中查找该国家首都名称并输出
代码:
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Hashtable hst = new Hashtable();
hst.Add("中国", "北京");
hst.Add("美国", "华盛顿");
hst.Add("英国","伦敦");
hst.Add("日本","东京");
hst.Add("韩国", "首尔");
hst.Add("加拿大", "渥太华");
hst.Add("巴西", "哈瓦那");
hst.Add("意大利", "罗马");
hst.Add("法国", "巴黎");
hst.Add("伊拉克", "巴格达");
Console.WriteLine("请输入要查找的国家:");
string s=Console.ReadLine();
if (!hst.Contains(s))
Console.WriteLine("您查找的国家未在哈希表中!");
else
{
foreach (DictionaryEntry item in hst)
{
if(item.Key.ToString()==s)
Console.WriteLine("{0}",item.Value);
}
}
Console.ReadKey();
}
}
}