2010-01-26 98 views
1

我试图排序元素的Dictionary<int,Elem>/SortedList<int,Elem>时遇到问题。c#元素排序

我应该出现在列表上X倍,但 如果一个元素是i指数则无法i - 1i + 1再现N元素的列表。我也必须尊重名单限制(elem N在elem 1之前,elem 1在elem N旁边)。

我有两个可能的出发点:

  1. 其具有Times属性,其具有元件应该出现在结果列表上的次数的元素的列表。

    示例输入:

    List<elem> elements = new List<elem>(){new Elem("star", 3), new Elem("square", 2), new Elem("circle", 3)}; 
    //Elem construct take element name, and number of times on result list 
    
  2. 列表,包含所有我要排序,显然的元素,在一unssorted方式。

    List<elem> elements = new List<elem>(){new Elem("star"),new Elem("star"),new Elem("star"),new Elem("circle"),("circle"),("circle"),new Elem("sqare"),new Elem("sqare")}; 
    

预期输出:

star circle star sqare circle sqare star circle 

// or any other combination in which any element is not preceded by itself 

更好的性能排序算法的欢迎,但这里不是必须的,因为这将是很少进行。

我正在使用C#4.0和.Net Framework 4.0。

+4

我完全不理解这个问题。也许有几个例子会说明你正在尝试做什么。你能否给这些输入提供一些示例输入和预期输出? – 2010-01-26 17:42:16

+0

在没有这种排序的情况下会发生什么?例如,“星星星圈”没有这样的顺序。 – jason 2010-01-26 18:17:00

+0

在这种情况下,应该抛出异常:NoSortingPosibleException或类似的东西,但这很容易通过使用max(elem.times)* 3 2010-01-26 18:28:53

回答

1

你可以用一个非常简单的回溯算法(类似于标准的解决eight queens puzzle做到这一点。让我知道如果如果它存在,或者添加了一个新的密钥,你需要的细节。

0

我没有时间测试这个,因为我目前无法访问视觉工作室,但生病让你开始。

首先,身份证建议把所有的对象和排序到三个不同的名单。 (这是由事实去你会使用列表,编辑为nessisary,

List<string> circle = new List<string>(); 
List<string> square = new List<string>(); 
List<string> star = new List<string>(); 
foreach(string item in yourList) 
{ 
    switch(item) 
    { 
     case "circle": 
      circle.Add(item); 
      break; 
     case "star": 
      star.Add(item); 
      break; 
     case "square": 
      square.Add(item); 
      break; 
    } 
} 
//then you would move to sorting them into one list, which would be 
List<string> finnished = new List<string>(); 
int count = 0; 
while(count != square.Count -1) 
{ 
    finished.Add(square[count]); 
    finished.Add(star[count]); 
    finished.Add(circle[count]); 
    count++ 
} 
+0

显然这不是一个确切的答案,但我希望它足以让你开始! – caesay 2010-01-26 18:53:00

+0

是的,我想过类似的东西,但是元素的类型是未知的,可能有3,5,10甚至20个元素,所以这将是这个解决方案的问题。 – 2010-01-26 19:09:49

0

的排序列表实现自定义键类。如

class MyKey : IComparer 
{ 
    int count; 
    int index; // Or maybe something else 
    ... 
} 

添加到您的排序列表将包括增加在计数变量值的自定义键腠如果不是,则为1。