【问题标题】:Shift through an array sequentially in C在C中按顺序移动数组
【发布时间】:2020-07-12 10:27:06
【问题描述】:

我有一个矩阵,我试图通过将第一行向左移动 n 次直到它处于原始位置,然后将第二行向左移动一次,来“计数”它,然后再次遍历整个第一行,将第二行移动一次,以此类推,直到第二行处于其原始位置,此时第三行将移动一次,我们重新开始。

例如:

0 1 2     1 2 0     2 0 1     0 1 2     1 2 0     2 0 1   a few     0 1 2     1 2 0
0 1 2 ==> 0 1 2 ==> 0 1 2 ==> 1 2 0 ==> 1 2 0 ==> 1 2 0 ==> ==> ==> 0 1 2 ==> 0 1 2 ... ... ...
0 1 2     0 1 2     0 1 2     0 1 2     0 1 2     0 1 2    more     1 2 0     1 2 0

一直到达到所有可能的组合。在 MxN 矩阵中,这应该给我 N^M 种可能性。我正在使用的实际矩阵比这个大得多,所以我试图避免 250 多个嵌套循环。

我已经有了shift方法:

static inline void shift(uint8_t *row){ //a row from a 2D Array
  int a, temp;
  int b = sizeof(row);
  temp = row[0];
  for(a = 0; a < b; a++){
    channel[a] = channel[a+1];
  }
  channel[b] = temp;
}

任何帮助将不胜感激。

【问题讨论】:

  • 这行代码:int b = sizeof(row); 不正确。 row 是一个指针,你无法知道它的大小。您必须将行的大小作为单独的参数传递给函数。
  • @LucaPolito 尼特。可以知道row的大小(它是指针的大小),但与行中元素的个数无关。
  • @WilliamPursell 是的,“指针的大小”我的意思是“指针指向的大小”。我认为前一个短语更“直接”。

标签: c arrays recursion multidimensional-array iteration


【解决方案1】:

非常好的问题,我很感激你。为了更好地理解,我以非常基本的方式做这个问题,必须阅读所有行 cmets 才能理解程序。我通过在每次班次后打印矩阵并根据我的工作在 TurboC 上对此进行了测试。如果您想要一些改进或需要进行一些更改才能达到您的要求,那么您可以尝试或只是发表评论。祝您一切顺利。

#include<stdio.h>

#define MAX 50

void shift(int *rowToShift, int size){
//To circular shift the row
 int i,tmp = rowToShift[0];
 for(i=0;i<size-1;i++){
    rowToShift[i] = rowToShift[i+1];
 }
 rowToShift[size-1] = tmp;
}

void main(){

 //I am just initilizing matrix with your initial data, I tested on this
 int mat[MAX][MAX] = {{0,1,2},{0,1,2},{0,1,2}};
 int row=3,col=3;//you may get it from user

 // We keep it always on row we shifting
 int currentRow=0;

 /*This tracker helps to track which row incremented
 how many times*/
 int shiftTracker[MAX];
 while(currentRow < row){

  //Shift current row to 1 left, (circular left as you ask)
  shift(mat[currentRow],col);

  shiftTracker[currentRow]++;

  if(shiftTracker[currentRow] == row){
   /*if current row shift is completed, means
     Now again in original condition*/

   shiftTracker[currentRow] = 0; //Reset traker for current row

   currentRow++;//Moving to Next row

   if(currentRow == row){
   //if all rows are completed
    break;
   }
  }
  else if(shiftTracker[currentRow] < row && currentRow != 0){
   //if all rows not completed and currentRow not on 0
   currentRow = 0;
  }
 }
}

【讨论】:

    【解决方案2】:

    您的shift() 功能可以这样改进:

    static void shift(uint8_t* row, size_t row_size) {
      uint8_t temp = row[0];
      for (size_t i = 0; i < row_size - 1; i += 1) {
        row[i] = row[i + 1];
      }
      row[row_size - 1] = temp;
    }
    // P.S.: row_size must be at least 1, or the function will break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      相关资源
      最近更新 更多