การสลับมิติของเมทริกซ์ 3 มิติ (3D Matrix Transposition)
โจทย์
You are tasked with implementing a program that transposes a given 3D array. Transposing a matrix involves swapping its dimensions, and the values of the original array should be reflected across the main diagonal.
Input:
- The input is a 3D array, originalArray, of dimensions .
- The first line contains values of x, y and z.
- The following is the matrix of 3D matrix values.
Output:
- The program should output a transposed 3D array.
| Input | Output |
|---|---|
| 2 2 3 1 2 3 4 5 6 7 8 9 10 11 12 | 1 7 2 8 3 9 4 10 5 11 6 12 |
โค้ด
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
int z = scanner.nextInt();
int[][][] matrix = new int[x][y][z];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
for (int k = 0; k < z; k++) {
matrix[i][j][k] = scanner.nextInt();
}
}
}
for (int j = 0; j < y; j++) {
for (int k = 0; k < z; k++) {
for (int i = 0; i < x; i++) {
System.out.print(matrix[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}คำอธิบาย
1. การรับขนาดมิติ
int x = scanner.nextInt();
int y = scanner.nextInt();
int z = scanner.nextInt();- รับค่าขนาดของแต่ละมิติ (x, y, z)
- แต่ละมิติมีค่าระหว่าง 0 ถึง 10
2. การสร้างและรับข้อมูลเมทริกซ์
int[][][] matrix = new int[x][y][z];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
for (int k = 0; k < z; k++) {
matrix[i][j][k] = scanner.nextInt();
}
}
}- สร้างเมทริกซ์ 3 มิติด้วยขนาดที่กำหนด
- ใช้ลูปซ้อน 3 ชั้นในการรับค่า
- ลำดับการเข้าถึง: x → y → z
3. การแสดงผลเมทริกซ์ที่สลับมิติ
for (int j = 0; j < y; j++) {
for (int k = 0; k < z; k++) {
for (int i = 0; i < x; i++) {
System.out.print(matrix[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}- สลับลำดับการวนลูป: j → k → i
- แต่ละบรรทัดคือค่าตามแนว x
- แต่ละกลุ่มคือค่าในแนว y
- เว้นบรรทัดระหว่างกลุ่ม
แผนภาพการทำงาน
ปรับปรุงล่าสุด