【发布时间】:2012-11-24 22:59:30
【问题描述】:
假设:
2D array: abcdef
ghijkl
mnopqr
存储在简单的长宽*高字符串中,因此,我们称之为arr。
arr = abcdefghijklmnopqr
width = 6
height = strlen ( arr ) / width
目标是将此数组旋转 45 度 (PI/4) 并得到以下结果:
arr = abgchmdinejofkplqr
width = 3
height = 8
converted to 2D array: a..
bg.
chm
din
ejo
fkp
.lq
..r
我花了几个小时试图弄清楚如何进行这种转换,并提出了一些半功能性的解决方案,但我无法让它完全发挥作用。你能描述/写一个算法来解决这个问题吗?最好在C中。
感谢您的帮助
编辑:这是我已经尝试过的
Edit2: 45度旋转的目的是将对角线变成线,以便可以使用strstr搜索。
// this is 90 degree rotation. pretty simple
for ( i = 0; i < width * height; i++ ) {
if ( i != 0 && !(i % height) ) row++;
fieldVertical[i] = field[( ( i % height ) * width ) + row];
}
// but I just can't get my head over rotating it 45 degrees.
// this is what I've tried. It works untile 'border' is near the first edge.
row = 0;
int border = 1, rowMax = 0, col = 0; // Note that the array may be longer
// than wider and vice versa. In that case rowMax should be called colMax.
for ( i = 0; i < width * height; ) {
for ( j = 0; j < border; j++, i++ ) {
fieldCClockwise[row * width + col] = field[i];
col--;
row++;
}
col = border;
row = 0;
border++;
}
我的代码中的“边界”是一个虚构的边界。在源代码中,它是对角线 分隔对角线的线。结果,这将是一条水平线 每一行。
1 2 3 / 4 5
6 7 / 8 9 10
11 /12 13 14 15
那些斜线是我们的分界线。 该算法应该非常简单,只需阅读 riagonals: 第一个数字 1,然后是 2,然后是 6,然后是 3,然后是 7,然后是 11,然后是 4,依此类推。
【问题讨论】:
-
你是顺时针旋转还是逆时针旋转?
-
请展示您的尝试
-
我需要同时做这两个,但是一旦我有一个算法来旋转它,另一种方式将是相似的。
-
当您说“旋转”时,您的意思是更像“倾斜”吗? “a”在旋转后保持在同一个位置。
-
是的,'a' 保持在同一个位置。我实际上需要将对角线变成线,以便我可以使用 strstr 搜索对角线。