【发布时间】:2016-01-21 20:42:43
【问题描述】:
我有一个数组中的数据,这些数据被填充到一个表中。数组的索引对应于它在表中的位置,如下所示:
0,1,2 0,1,2 0,1,2
3,4,5 or 3,4,5 or 3,4,5
6,7,8 6,7 6
也就是说它是从左到右,从上到下排列的。我需要想出一个从上到下,从左到右排序的函数。像这样:
0,3,6
1,4,7
2,5,8
有几点需要注意。表格中可以包含任意数量的元素,但永远只有 3 列。
总而言之,我需要这样的东西:
Array indexes = [0,1,2,3,4,5,6,7,8]
Indexes after converting= [0,3,6,1,4,7,2,5,8]
现在我可以在某些情况下使用它,例如如果有九个值。我真的很难为任意案例解决这个问题。我正在使用 Javascript,但实际上任何语言的任何答案都会有所帮助。
为此,我需要以不同的方式布置表格,但不想触摸 html。我想重新排序索引,以便它们从上到下、从左到右排列。
这是我目前所拥有的:
scope.correctIndexData = function (data) {
var colors = ['#92278f', '#f15a29', '#006838', '#27aae1', '#262262', '#754c29', '#ee2a7b', '#8dc63f', '#fff200'];
var row = 0;
var column = 0;
var correctedData = new Array(data.length);
for (var index = 0; index < data.length; index++) {
var newIndex = scope.getCorrectedIndex(row,column,data);
if(data.length>=10){
correctedData[index] = data[newIndex];
}
else{
correctedData[newIndex] = data[index];
correctedData[newIndex].color = colors[newIndex];
}
if (column === 2) {
column = 0;
row++;
} else {
column++;
}
}
return correctedData;
};
scope.getCorrectedIndex = function (row, column, data) {
var newIndex;
var rows = Math.ceil(data.length/3.0); //number of rows in table
//handle the first row since there can be verying number of columns per row
if (row === 0) {
if(column === 0){
newIndex = 0;
}
else if (column === 1) {
newIndex = rows;
} else if(column == 2){
if(data.length % 3 == 1){
newIndex = rows * 2 -1;
}
else{
newIndex = rows * 2;
}
}
} else {
if(data.length % 3 === 0){
newIndex = (row) + (3 * column);
}
else if(data.length % 3 == 1){
if(column === 0 || data.length % 7 === 0){
newIndex = (row) + (3 * column);
}
else{
newIndex = (row) + (3 * column) + 1;
}
}
else{
if(column === 0){
newIndex = (row) + (3 * column);
}
else{
newIndex = (row) + (3 * column) + 2;
}
}
}
return newIndex;
};
【问题讨论】:
-
那么输入数组的长度会一直是7、8还是9?
-
可以是任意长度。我只是以这些为例。
-
好的,谢谢你的澄清。所以唯一的限制总是 3 列。
-
输入
[0,1,2,3,4,5,6]的预期输出数组是什么? -
@user489041 我不明白为什么这是期望的行为。这根本不遵循您描述的转置算法。
标签: javascript arrays algorithm sorting matrix