代码之家  ›  专栏  ›  技术社区  ›  Mg.

C元素分类

  •  1
  • Mg.  · 技术社区  · 15 年前

    我有一个问题,试图排序 Dictionary<int,Elem> / SortedList<int,Elem> 元素的

    我有一张清单 N 应显示的元素 X 名单上的时间,但是 如果某个元素处于启用状态 i 索引,则不能在上重新出现 i - 1 i + 1 . 我还必须遵守列表限制(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. 一个列表,其中包含我想要以未排序的方式排序的所有元素。

      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。

    3 回复  |  直到 15 年前
        1
  •  1
  •   jason    15 年前

    您可以使用非常简单的回溯算法(类似于 eight queens puzzle . 如果你需要细节,请告诉我。

        2
  •  0
  •   caesay    15 年前

    我没有时间测试这个,因为目前我没有访问Visual Studio的权限,但我会让您开始。

    首先,我建议把所有的对象都放在三个不同的列表中。 (事实上,您将使用一个列表,编辑为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++
    }
    
        3
  •  0
  •   kervin    15 年前

    实现SortedList的自定义键类。例如

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

    添加到SortedList将涉及增加该值自定义键(如果存在)中的count变量。或者添加一个计数为1的新键。