2010-01-26 184 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。