How do I correctly sort this array?

时间:2016-12-09 12:47:54

标签: c# arrays sorting

Im trying to sort through an array of stacked cubes. The Array looks like this(an example)

Nth Cube | Position (0, its on the desk, >0,  its on another cube)
---
1|6
---
2|8
---
3|0
---
4|0
---
5|0
---
6|0
---
7|1
---
8|4
---

which would look like this visualized

[7] [2]
---
[1] [8]
---
[6] [4] [3] [5]
---

I sorted out the cubes that are on another one:

string[,] t in this case is the entire Array

static string[,] stackedCubes(string[,] t)
    {
        string[,] stackedHelp = new string[NumberOfStacked(),2];
        int j = 0;
        for (int i = 0; i < t.GetLength(0); i++)
        {
            if (t[i, 1]!="0")
            {

                stackedHelp[j, 0] = t[i, 0];
                stackedHelp[j, 1] = t[i, 1];
                j++;
            }
        }
        return stackedHelp;
    }

which comes out as :

1|6
---
2|8
---
7|1
---
8|4
---

now im trying to put them down from the top(so 7/2 then 1/8)

string[,] t from here on is stackedCubes

static string[,] Putdown(string[,] t)
    {
        string[,] stackedOrder = new string[NumberOfStacked(), 2];
        int j = 0;
        do
        {
            for (int i = 0; i < t.GetLength(0); i++)
            {
                if (t[i, 1] == t[j, 0])
                {
                    j = i;
                }
                else if(IsSomethingOnTheCube(t[j,0],t)==false)
                {
                    stackedOrder[i, 0] = t[j, 0];
                    stackedOrder[i, 1] = "0";
                    t[i, 1] = "0";
                }
            }
        }
        while (AreAllTheCubesOnTable(t) != true);

        return stackedOrder;
    }

here im going from the first Cube 1(t[j,0]) and check if there is something on it, it finds it on t[i,1] and gives back the 7(t[j,0]) and goes back. I check if there is something on the Cube here

    static bool IsSomethingOnTheCube(string Cube,string[,] t)
    {
        for (int i = 0; i < t.GetLength(0); i++)
        {
            if(Cube==t[i,1])
            {
                return true;
            }
        }
        return false;
    }

I also check whether or not are they all on the desk (with the do-while)

    static bool AreAllTheCubesOnTable(string[,] t)
    {
        for (int i = 0; i < t.GetLength(0); i++)
        {
            if (t[i, 1] != "0")
            {
                return false;
            }
        }
        return true;
    }

And the output is all wrong:

7|0
---
7|0
---
7|0
---
7|0
---

when it should be something like:

7|0
---
1|0
---
2|0
---
8|0
---

Where am I indexing wrong?(or something else)

2 个答案:

答案 0 :(得分:0)

在提供的样本中

string[] cubes = new string[]
  {"1|6", "2|8", "3|0", "4|0", "5|0", "6|0", "7|1", "8|4"};

问题的底线看起来像是随机的。我们订购吧 最低的立方体(比如说,按字典顺序),因此可视化将是:

lines:
   2:        [2]     [7]
   1:        [8]     [1]
   0:    [3] [4] [5] [6]  <- bottom line is sorted
------------------------
files:    0   1   2   3

完成此操作后,我们可以实现两个帮助方法

   // Line: 0 for lowest cubes
   private static int CubeLine(string value, IEnumerable<String> stack) {
      for (int line = 0; ; ++line) {
        string parent = value.Substring(value.IndexOf('|') + 1);

        if ("0".Equals(parent))
          return line;

        value = stack.First(item => item.StartsWith(parent + "|"));
      }
    }

并且

    // File: 0 for leftmost cubes
    private static int CubeFile(string value, IEnumerable<String> stack) {
      string root = value;

      while (true) {
        string parent = root.Substring(root.IndexOf('|') + 1);

        if ("0".Equals(parent))
          break;

        root = stack.First(item => item.StartsWith(parent + "|"));
      }

      return stack
        .Where(item => item.Substring(value.IndexOf('|') + 1) == "0")
        .OrderBy(item => item)
        .Select((item, index) => new {
          item = item,
          index = index
        })
        .First(item => item.item == root)
        .index;
    }

然后你可以轻松地对你喜欢的任何东西进行排序。例如,让我们排序 首先是最顶层的立方体,如果是最左边的第一个:

 string[] cubes = new string[]
   {"1|6", "2|8", "3|0", "4|0", "5|0", "6|0", "7|1", "8|4"};

  var result = cubes
    .Select (cube => new {
      name = cube.Substring(0, cube.IndexOf('|')),
      file = CubeFile(cube, cubes),
      line = CubeLine(cube, cubes) })
    .OrderByDescending(cube => cube.line)
    .ThenBy(cube => cube.file)
    .Select(cube => cube.name);

  Console.Write(string.Join(", ", result));

结果是

  2, 7, 8, 1, 3, 4, 5, 6

修改:如果您想从左到右排序,从上到下排序:

  var result = cubes
    .Select (cube => new {
      name = cube.Substring(0, cube.IndexOf('|')),
      file = CubeFile(cube, cubes),
      line = CubeLine(cube, cubes) })
    .OrderBy(cube => cube.file)
    .ThenByDescending(cube => cube.line)
    .Select(cube => cube.name);  

结果是

 3, 2, 8, 4, 5, 7, 1, 6

编辑2 :放下顺序:首先是底部,绑定任意

  var result = cubes
    .Select (cube => new {
      name = cube.Substring(0, cube.IndexOf('|')),
      file = CubeFile(cube, cubes),
      line = CubeLine(cube, cubes) })
    .OrderBy(cube => cube.line)
    .Select(cube => cube.name);  

结果:

  3, 4, 5, 6, 1, 8, 2, 7 

答案 1 :(得分:0)

虽然在开始编程时在许多示例中使用了多维数组,但通常建议使用强类型类的数组。也就是说,当多维数组仍然可以解析为另一种格式,例如字典。例如:

string[,] cubes = {{"1","6"} ,{ "2","8"} ,{ "3","0"} ,{ "4","0"} ,{ "5","0"} ,{ "6","0"} ,{ "7","1"} ,{ "8","4"}};


//create a dictionary of all cube-parents
var parents = (from i in Enumerable.Range(0, cubes.GetLength(0))                    
                group cubes[i,0] by cubes[i,1])
                .ToDictionary(g=>g.Key, g=>g.ToArray());    

var layer = parents["0"]; //table level cubes [3,4,5,6]
var layers=  new List<string[]>();
while(layer != null){
    layers.Add(layer);
    string[] children, nextlayer = null;
    for(int i = 0; i < layer.Length; i++)
        if(layer[i] != null && parents.TryGetValue(layer[i], out children)){
            if(nextlayer==null)nextlayer= new string[layer.Length];
            nextlayer[i] = children[0]; //what to do with multiple children?
        }
    layer= nextlayer;
};

完成上述操作后,layers包含{[3,4,5,6],[null,8,null,1], [null,2,null,7]},换言之,包含多个图层。我不完全确定哪个是最终结果。是视觉表现还是像桌子上没有的所有立方体(对于后者,它只是所有没有父母的物品&#39; 0&#39;)