我使用这些表来存储课程one
部分的主题名称。我的问题是,我怎样才能将主题名称从一个表格插入到另一个表格中,以便在同一时间不会出现两个主题。
示例:
Table-1
Hour Subject-name
1 C#
2 Java
3 OS
4 C++
5 DBMS
我需要以这样的方式将同一组值输入另一个表格table-2
:
Table-2
Hour Subject-name
1 OS
2 DBMS
3 C#
4 Java
5 C++
我习惯于对列表进行随机操作,以便随机地对元素进行随机播放。但是,有可能两次发生同一主题。
public static void Shuffle<T>(IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
答案 0 :(得分:0)
您需要随机播放,然后检查您的规则是否被违反,然后重试。
以下是这样做的一种方法:
Random rng = new Random();
private IList<Course> SmartShuffle(IList<Course> oldList)
{
IList<Course> newList = new List<Course>();
while (true)
{
var randomOrder = oldList.OrderBy(x => rng.Next()).ToList();
int counter = 0;
foreach(var course in oldList)
{
newList.Add(new Course() { Name = randomOrder[counter].Name, Hour = course.Hour });
counter++;
}
int differenceCount = newList.Count(n => oldList.Any(o => o.Name == n.Name && o.Hour != n.Hour));
// leave only one of the below if statements
// case at least 1 element should be different
if (differenceCount > 0)
break;
// case all elements must be different
if (differenceCount == oldList.Count)
break;
}
return newList;
}
public class Course
{
public string Name { set; get; }
public int Hour { set; get; }
}