我有串行二维数据。
例如 原始数据是5x2。 我想转换 3x4。
数据量是可变的。 所以必须循环重复。
// serial data (serial)
1-1 1-2 1-3 1-4 1-5 2-1 2-2 2-3 2-4 2-5
// original data for (5x2)
1-1 1-2 1-3 1-4 1-5
2-1 2-2 2-3 2-4 2-5
// wish data to (3x4)
1-1 1-2 1-3
2-1 2-2 2-3
1-4 1-5
2-4 2-5
// wish data (serial)
1-1 1-2 1-3 2-1 2-2 2-3 1-4 1-5 2-4 2-5
我尝试通过以下代码(java)。 但我找不到更多的循环。
import java.util.*;
public class Main {
static int ORIGINAL_COLUMNS = 5;
static int MAX_COLUMNS = 3;
static List<String> serialList = new ArrayList<String>() {{
add("1-1");
add("1-2");
add("1-3");
add("1-4");
add("1-5");
add("2-1");
add("2-2");
add("2-3");
add("2-4");
add("2-5");
}};
public static void main(String[] args) throws Exception {
List finalList = new ArrayList<String>();
for (int i = 0; i < serialList.size(); i += ORIGINAL_COLUMNS) {
for (int j = i; j < i + MAX_COLUMNS; j++) {
finalList.add(serialList.get(j));
}
}
System.out.println(finalList);
}
}
// result (wrong)
// second row is gone.
[1-1, 1-2, 1-3, 2-1, 2-2, 2-3]
你可以通过 paiza.io 进行测试和检查(我无法附加片段。为什么?)
https://paiza.io/projects/hN8d5ObIElcZIkdd8hlVmA?language=java
最简单的解决方案之一是引入一个附加列表来存储其余值:
public static void main(String[] args) throws Exception {
List<String> finalList = new ArrayList<>();
List<String> restList = new ArrayList<>();
for (int i = 0; i < serialList.size(); i += ORIGINAL_COLUMNS) {
for (int j = i; j < i + MAX_COLUMNS; j++) {
finalList.add(serialList.get(j));
}
for (int j = i + MAX_COLUMNS; j < i + ORIGINAL_COLUMNS; j++) {
restList.add(serialList.get(j));
}
}
finalList.addAll(restList);
System.out.println(finalList);
}
可以进一步简化为单个循环:
public static void main(String[] args) throws Exception {
List<String> finalList = new ArrayList<>();
List<String> restList = new ArrayList<>();
for (int i = 0; i < serialList.size(); i += ORIGINAL_COLUMNS) {
for (int j = i; j < i + ORIGINAL_COLUMNS; j++) {
List<String> list = (j < i + MAX_COLUMNS) ? finalList : restList;
list.add(serialList.get(j));
}
}
finalList.addAll(restList);
System.out.println(finalList);
}
输出:
[1-1, 1-2, 1-3, 2-1, 2-2, 2-3, 1-4, 1-5, 2-4, 2-5]