[英]How can I change the size of a 2D array?
如何在不重新排列數組中的數字的情況下更改二維數組的大小,主要使用 for 循環並且僅使用內置方法? 例如 {{4,5,6,7,10}, {8,4,3,9,13}} 變為 {{4}, {5,6}, {7,10,8}, { 4,3,9,13}}。
我嘗試將二維數組分成兩個單獨的部分,然后將其添加回新的二維數組。 我不確定如何創建第二個二維數組。
有很多方法可以做到這一點。 這是一個適用於任何三角數的
源自二維數組的元素。
首先,將它們全部展平為一個數組。
int[] oneD = Arrays.stream(src).flatMapToInt(Arrays::stream).toArray();
然后反轉應該為k
的長度,其中k = n(n+1)/2
行數如下。 並且 2D 結果是部分分配的。
int rows = (int)(Math.sqrt(2*oneD.length + .25) -.5);
int[][] dest = new int[rows][];
現在只需從oneD
數組復制到目標即可。
for (int i = 0, s = 0, e = 1; i < rows; i++) {
dest[i] = Arrays.copyOfRange(oneD, s, e );
s = e;
e += i+2;
}
for (int[] arr : dest) {
System.out.println(Arrays.toString(arr));
}
印刷
[4]
[5, 6]
[7, 10, 8]
[4, 3, 9, 13]
如果我理解您的問題,我建議您使用List<List<Integer>>
,例如 ArrayList,插入純 arrays,您可以像這樣設置聚合:
List<List<Integer>> matrix = new ArrayList<>();
List<Integer> values = new ArrayList<>();
// add {4,5,6,7,10} to array, result = {{4,5,6,7,10}}
values = new ArrayList<>(Arrays.asList(4,5,6,7,10));
matrix.add(values);
// add {8,4,3,9,13} to last array, result = {{4,5,6,7,10}, {8,4,3,9,13}}
values = new ArrayList<>(Arrays.asList(8,4,3,9,13));
matrix.add(values);
System.out.println("start="+ matrix);
// reset array or you can use another array to copy
matrix = new ArrayList<>();
values = new ArrayList<>(Arrays.asList(4));
matrix.add(values);
values = new ArrayList<>(Arrays.asList(5,6));
matrix.add(values);
values = new ArrayList<>(Arrays.asList(7,10,8));
matrix.add(values);
values = new ArrayList<>(Arrays.asList(4,3,9,13));
matrix.add(values);
System.out.println("end="+ matrix);
Output: 開始=[[4, 5, 6, 7, 10], [8, 4, 3, 9, 13]] 結束=[[4], [5, 6], [7, 10, 8], [4, 3, 9, 13]]
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class ArrayResize {
public static void main(String[] args) {
Integer[][] input = new Integer[][] {{10, 11, 12 ,13, 14}, {15, 16, 17, 18, 19}};
AtomicInteger index = new AtomicInteger(0);
AtomicInteger group = new AtomicInteger(1);
Collection<List<Integer>> out = Arrays.stream(input)
.flatMap(i -> Arrays.stream(i)) // flatten
.collect(Collectors.groupingBy(i -> {
final int currentIndex = index.getAndIncrement();
return (group.get() * (group.get() + 1)) / 2 == currentIndex
? group.incrementAndGet() // increment group if index matches the summation of the range
: group.get(); // return the group
}))
.values();
System.out.println(out);
}
}
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class ArrayResize {
public static void main(String[] args) {
Integer[][] input = new Integer[][] {{10, 11, 12 ,13, 14}, {15, 16, 17, 18, 19}};
AtomicInteger index = new AtomicInteger(0);
AtomicInteger group = new AtomicInteger(1);
Integer[][] output = Arrays.stream(input)
.flatMap(i -> Arrays.stream(i)) // flatten
.collect(Collectors.groupingBy(i -> {
final int currentIndex = index.getAndIncrement();
return (group.get() * (group.get() + 1)) / 2 == currentIndex
? group.incrementAndGet() // increment group if index matches the summation of the range
: group.get(); // return the group
})).values().stream() // stream collection
.map(subgroup -> subgroup.toArray(new Integer[0])) // map subgroups to arrays
.collect(Collectors.toList()) // collect as list of arrays
.toArray(new Integer[0][0]); // convert to array
System.out.println(Arrays.deepToString(output));
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ArrayResize {
public static void main(String[] args) {
Integer[][] input = new Integer[][] {{10, 11, 12 ,13, 14}, {15, 16, 17, 18, 19}};
List<Integer> flattened = Arrays.stream(input).flatMap(i -> Arrays.stream(i)).collect(Collectors.toList());
List<Integer[]> temporary = new ArrayList<>();
final int count = flattened.size();
int start = 0;
int range = 1;
while (start < count) {
temporary.add(flattened.subList(start, Math.min(start + range, count)).toArray(new Integer[0]));
start += range;
range++;
}
Integer[][] result = temporary.toArray(new Integer[0][0]);
System.out.println(Arrays.deepToString(result));
}
}
這是一種方法,使用純 Java 代碼(例如循環)並且根本沒有方法。
static int[][] toTriangle(int[][] input) {
// Count number of values
int valueCount = 0;
for (int[] inputRow : input)
valueCount += inputRow.length;
if (valueCount == 0)
return new int[0][0];
// Determine number of result rows, and how many values that can store
int resultRowCount = 0, resultCount = 0;
for (int row = 0; resultCount < valueCount; row++) {
resultRowCount++;
resultCount += row + 1;
}
int oversize = resultCount - valueCount;
// Build result jagged array (last row is likely truncated)
int[][] result = new int[resultRowCount][];
for (int row = 0; row < resultRowCount - 1; row++)
result[row] = new int[row + 1];
result[resultRowCount - 1] = new int[resultRowCount - oversize];
// Copy values
int inputRow = 0, inputCol = 0;
for (int[] resultRow : result) {
for (int i = 0; i < resultRow.length; i++) {
while (inputCol == input[inputRow].length) {
inputRow++;
inputCol = 0;
}
resultRow[i] = input[inputRow][inputCol++];
}
}
return result;
}
測試
test(new int[][] {{4,5,6,7,10}, {8,4,3,9,13}});
test(new int[][] {{1,2,3,4}, {}, {5,6,7}});
static void test(int[][] input) {
print("Input", input);
print("Result", toTriangle(input));
}
static void print(String label, int[][] arr) {
System.out.println(label + ":");
for (int[] row : arr) {
System.out.print(" [");
String sep = "";
for (int val : row) {
System.out.print(sep + val);
sep = ", ";
}
System.out.println("]");
}
}
輸出
Input:
[4, 5, 6, 7, 10]
[8, 4, 3, 9, 13]
Result:
[4]
[5, 6]
[7, 10, 8]
[4, 3, 9, 13]
Input:
[1, 2, 3, 4]
[]
[5, 6, 7]
Result:
[1]
[2, 3]
[4, 5, 6]
[7]
注意最后一行的長度是如何被截斷的,因為沒有足夠的值來填充三角形。 第二個示例還表明它可以處理輸入中的空子數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.