【问题标题】:C# byte array sorting it's rotationsC# 字节数组排序它的旋转
【发布时间】:2015-05-23 13:22:56
【问题描述】:

我有一个字节数组,例如byte[] = new byte[3] { 97, 98, 99, 99, 96 } 在实际情况下字节数组要长得多。

如何获取该数组的所有旋转并对其进行排序?而且我还需要将原始索引保留在排序列表中。

旋转应该是这样的:

{ 97, 98, 99, 99, 96 },
{ 98, 99, 99, 96, 97 },
{ 99, 99, 96, 97, 98 },
{ 99, 96, 97, 98, 99 },
{ 96, 97, 98, 99, 99 }

那我需要排序得到:

{ 96, 97, 98, 99, 99 },
{ 97, 98, 99, 99, 96 },  // <- index in rotated list/array
{ 98, 99, 99, 96, 97 },
{ 99, 96, 97, 98, 99 },
{ 99, 99, 96, 97, 98 }

我使用效率不高的方法将 byte[] 转换为字符串,然后创建字符串数组,每个数组元素保持其旋转,然后对字符串数组进行排序。我还使用了内置函数“排序”,所以我无法捕捉到我的索引。也许可以用 LINQ 或类似的东西来做这个?

【问题讨论】:

    标签: c# arrays sorting byte


    【解决方案1】:

    您可以扩展数组并在那里进行排序。您需要创建自己的排序机制:

    public static int[] SortAndReturnIndexes(this byte[])
    {
        var indexArray = new int[];
        // Your sort logic goes here
        return indexArray;
    }
    

    【讨论】:

      【解决方案2】:

      根据您在完成这些操作后想要用它做什么,实际产生结果可能不是最好的做法。以下面的类为例:

      public class Rotation[T] {
      
        private int init;
        private T[] src;
      
        public Rotation(T[] src, init){
          this.init = init;
          this.src = src;
        }
      
        public T this[int i] { //indexer
          get {
            int realindex = (i + init) % src.Length; //rotate the index
            return src[realindex];
          }
        }
      }
      

      你可以把它当作

      byte[] src = new byte[5] { 97, 98, 99, 99, 96 }
      
      //rotate by 2
      
      Rotation[byte] rotation = new Rotation(src, 2);
      
      rotation[0] == 99
      

      要对其进行排序,最好创建一个自定义 IComparer,您可以将其提供给排序方法:https://msdn.microsoft.com/en-us/library/8ehhxeaf%28v=vs.110%29.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-25
        • 1970-01-01
        • 1970-01-01
        • 2012-12-19
        • 2021-01-29
        • 2018-06-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多