二维到一维数组在C [英] 2D to 1D array in c

查看:230
本文介绍了二维到一维数组在C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习的遗传算法和C语言编程。我的任务是读入一个矩阵,再presents则连通图计算基于节点之间的距离健身,该教授已经明确这并不一定是确切的,也不一定遵循约束图。所以我的想法是读取矩阵到一个二维数组,它的工作原理。我现在需要获得二维数组转换成一维数组,我们将调用机架,我们再混杂机架,它分为长度相等的两个较小的数组。

该矩阵是20 * 20,机架有是尺寸400

反正这是我的code这样做,尽管这是行不通的。

 无效TwoDtoOneD(int数组[] [SIZE],INT左侧[SIZE * SIZE]){
    INT I,J;
    对于(i = 0; I< SIZE·尺码;我++){
        为(J = 0; J< SIZE·尺码; J ++){
            离开[我] =阵列[I] [J]。
        } //结束
    } //结束
}
 

解决方案

通过做两维权,并使其循环,直到SIZE ^ 2,你让数组[我] 迭代太多。 应该只到20(或大小),至极是的和<$ C $最大C>Ĵ为你的矩阵。 为了使这项工作,你需要一个第三个变量至极每次你改变一个值,你的载体(左)的时间增加,而这个变量无关的for循环变量初始化。

所以,你的榜样,这将是这样的:

 无效TwoDtoOneD(int数组[SIZE] [SIZE],INT左侧[SIZE * SIZE]){/
  INT I,J,K;
  K = 0;
  对于(i = 0; I&LT;大小;我++){
     为(J = 0; J&LT;大小; J ++){
        左[K] =阵列[I] [J]。
        ķ++;
     } //结束
  } //结束
}
 

现在,你的离开[] 阵列 K + 1 元素,你可以通过它遍历到氏/ code>。

刚刚完成,因为你正在使用的图表,试图了解图形路径算法一些东西(的 Dijkstra的普里姆的,的弗洛伊德的,的约翰逊的 ...),你会看到,是您的所有图表的问题(或大部分)。

真的经过深思熟虑的解决方案无边

希望这有助于。祝你好运!

I am studying genetic algorithms and the C programming language. My task is to read in a matrix which represents a connected graph then calculate a fitness based on the distance between nodes, the prof has made it clear this does not have to be exact, nor necessarily follow the constraints on a graph. SO my idea is to read the matrix in to a 2D array which works. I now need to get that 2D array into a 1D array we will call rack, we then jumble the rack and split it into two smaller array of equal length.

The matrix is 20*20 so rack has to be of size 400.

Anyways this is my code for doing this, although it does not work.

void TwoDtoOneD(int array[][SIZE], int left[SIZE*SIZE]){
    int i,j;
    for(i=0;i<SIZE*SIZE;i++){
        for(j=0;j<SIZE*SIZE;j++){
            left[i] = array[i][j];
        }//end for
    }//end for
}

解决方案

By doing two fors and making them iterate untill SIZE^2, you're making array[i] iterate too much. i should only go till 20(or SIZE), wich is the max of the i and the j for your matrix. To make this work, you'll need a third variable wich is incremented every time you change a value to your vector(left), and this variable has nothing to do with the for loop variable initiation.

So, for your example, it would be like this:

void TwoDtoOneD(int array[SIZE][SIZE], int left[SIZE*SIZE]){  /
  int i,j,k;
  k=0;
  for(i=0;i<SIZE;i++){
     for(j=0;j<SIZE;j++){
        left[k] = array[i][j];
        k++;
     }//end for
  }//end for
}

Now, your left[] array has k+1 elements and you can iterate through it till k.

Just to finish, since you're working with graphs, try to read some stuff about graph path algorithms (Dijkstra's, Prim's, Floyd's, Johnson's...), you'll see that are an infinity of really well thought solutions for all your graph's problems (or for most).

Hope this helps. Good luck!

这篇关于二维到一维数组在C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆