随机抽取20道题目,组合成100分
最近在计划一个动态考试的系统。其中想做到这样的效果,除了比较正规的命题考试外(例如规定5分题多少道,10分题多少道),我们想增加动态随机命题的功能。就是说用户可以自己给定一个题目数,然后程序在题库中随机抽出来,组合成一份试卷。(当然,总分是要100分)
这个算法的简单做法如下,还有待优化
static Random rnd = new Random();
static void Main(string[] args)
{
int count = 20;//题目数量
int min = 1;//最低分
int max = 10; //最高分
while (true)
{
List<int> temp = FillList(count, max, min);
if (SumList(temp) == 100)
WriteList(temp);
}
}
/// <summary>
/// 随机填充一个列表
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
static List<int> FillList(int count,int max,int min)
{
List<int> result = new List<int>();
for (int i = 0; i < count; i++)
{
result.Add(rnd.Next(min, max));
}
return result;
}
/// <summary>
/// 返回列表的总和
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
static int SumList(List<int> input)
{
int result = 0;
foreach (int i in input)
{
result += i;
}
return result;
}
/// <summary>
/// 打印列表
/// </summary>
/// <param name="input"></param>
static void WriteList(List<int> input)
{
StringBuilder sb = new StringBuilder();
int count = 1;
foreach (int i in input)
{
if (count < input.Count)
sb.Append(i.ToString() + ",");
else
sb.Append(i.ToString());
count++;
}
Console.WriteLine(sb.ToString());
}
常见的结果如下
5,7,7,6,1,4,4,3,2,6,5,8,9,4,3,5,5,5,7,4
1,5,6,4,4,7,7,2,6,4,1,9,5,7,1,4,5,7,7,8
3,8,9,2,1,9,6,8,4,1,4,6,3,1,3,5,8,7,8,4
9,6,6,6,3,4,5,4,2,3,4,3,7,2,9,9,1,3,7,7
3,8,2,6,6,2,2,4,1,8,8,2,2,6,8,6,2,9,6,9
7,2,1,6,4,5,9,2,5,1,4,7,8,5,3,6,6,7,8,4
5,6,3,8,4,7,4,4,6,3,8,3,4,9,9,6,1,7,2,1
8,1,6,7,3,5,7,5,6,8,5,7,8,9,4,1,4,3,2,1
8,4,3,2,1,7,4,9,7,5,9,8,1,8,6,4,6,2,4,2
5,3,8,3,1,8,1,8,3,5,5,9,9,4,3,5,2,6,9,3