簡體   English   中英

您如何按照最小到大多數非零元素的順序迭代排列?

[英]How do you iterate through permutations in order of least to most non-zero elements?

我正在嘗試編寫一個C#函數,給定像new int[] { 2, 3, 2 } IEnumberable<int[]> new int[] { 2, 3, 2 }這樣的參數,它為每個元素指定上限+ 1,將返回以下內容(通過IEnumberable<int[]> ):

0 0 0
0 0 1
0 1 0
0 2 0
1 0 0
0 1 1
0 2 1
1 0 1
1 1 0
1 2 0
1 1 1
1 2 1

請注意,順序很重要:所有具有0個非零元素的排列,然后是具有1個非零元素的所有排列,依此類推。在這些組之一內,順序無關緊要。

我意識到這些從技術上講可能不是排列,但這是我所知道的最接近的術語。 我也意識到一種方法是按某種順序返回所有排列,然后根據一個計算存在多少非零元素的函數對它們進行排序,但是我希望有一種更優雅,更有效的方法。

如果該代碼存在語法錯誤(無法測試),我深表歉意,但希望您能理解。

IEnumerable<int[]> Permutations(int[] upperBounds) {
    int[] c = new int[upperBounds.Length] {};

    while(true) {
        int i = c.Length - 1;

        while(i >= 0 && c[i] == upperBounds[i]) {
            c[i] = 0;
            i--;
        }

        if(i == -1) break;

        c[i]++;

        yield return (int[]) c.Clone();
    }
}

如果您使用回調並保留相同的數組引用,但要求IEnumerable會更好。 如果絕對不能使用Clone ,請使用它-它將大大提高效率。

我想要一個不會先計算所有內容然后進行排序的答案,而仍然只經歷最短的時間。 這就是我所擁有的。 請注意,在外部修改int[]可能會使結果搞砸(或者,可能返回new int[] )。

第一種方法告訴輔助方法在輸出中需要多少個0。 然后,助手將計算結果,如果無法填寫足夠的0或遍歷所有數據,則停止。

static IEnumerable<int[]> Permutation(int[] bounds)
{
  for(int num0s = bounds.Length; num0s >= 0; --num0s)
  {
    foreach(int[] ret in PermHelper(num0s, 0, bounds, new int[bounds.Length]))
      yield return ret;
  }
}

static IEnumerable<int[]> PermHelper(int num0s, int index, int[] bounds, int[] result)
{
  //Last index.
  if(index == bounds.Length - 1)
  {
    if(num0s > 0)
    {
      result[index] = 0;
      yield return result;
    }
    else
    {
      for(int i = 1; i < bounds[index]; ++i)
      {
        result[index] = i;
        yield return result;
      }
    }
  }
  //Others.
  else
  {
    //still need more 0s.
    if(num0s > 0)
    {
      result[index] = 0;
      foreach(int[] perm in PermHelper(num0s - 1, index + 1, bounds, result))
        yield return perm;
    }
    //Make sure there are enough 0s left if this one isn't a 0.
    if(num0s < bounds.Length - index)
    {
      for(int i = 1; i < bounds[index]; ++i)
      {
        result[index] = i;
        foreach(int[] perm in PermHelper(num0s, index + 1, bounds, result))
          yield return perm;
      }
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM