การเลื่อนสมาชิกในอาเรย์ไปทางซ้าย
โจทย์
Write a Java program that takes n integers, stores them in an array, and shifts all elements left by one position (the first element moves to the last).
Input:
- The first line contains an integer n representing the size of the array.
- The second line contains n integers, the elements of the array.
Output:
- A single line with the array after shifting all elements left by one position.
| Input | Output |
|---|---|
| 5 1 2 3 4 5 | 2 3 4 5 1 |
โค้ด
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
int shiftIndex = i == 0 ? size - 1 : i - 1;
numbers[shiftIndex] = scanner.nextInt();
}
for (int i = 0; i < size; i++) {
System.out.print(numbers[i] + " ");
}
}
}คำอธิบาย
1. การประกาศคลาสและรับขนาดอาเรย์
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt(); // ขนาดของอาเรย์2. การสร้างและรับข้อมูลพร้อมเลื่อนตำแหน่ง
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
int shiftIndex = i == 0 ? size - 1 : i - 1; // คำนวณตำแหน่งที่จะเลื่อนไป
numbers[shiftIndex] = scanner.nextInt(); // เก็บค่าในตำแหน่งที่เลื่อนแล้ว
}- สร้างอาเรย์ขนาด size
- ใช้ Ternary operator ในการคำนวณตำแหน่งใหม่:
- ถ้า i = 0: เก็บที่ตำแหน่งสุดท้าย (size - 1)
- ถ้าไม่ใช่: เก็บที่ตำแหน่ง i - 1
3. การแสดงผลอาเรย์
for (int i = 0; i < size; i++) {
System.out.print(numbers[i] + " "); // แสดงสมาชิกแต่ละตัวพร้อมเว้นวรรค
}- วนลูปแสดงสมาชิกทุกตัวในอาเรย์
- เว้นวรรคระหว่างแต่ละตัว
แผนภาพการทำงาน
การเลื่อนตำแหน่งในอาเรย์
อาเรย์ต้นฉบับ:
[0] [1] [2] [3] [4]
1 2 3 4 5
การเลื่อนไปทางซ้าย 1 ตำแหน่ง:
[0] [1] [2] [3] [4]
2 3 4 5 1ตัวอย่างการทำงาน
ตัวอย่างที่ 1
Input:
5
1 2 3 4 5
การทำงาน:
i = 0: shiftIndex = 4 (size-1) → numbers[4] = 1
i = 1: shiftIndex = 0 (1-1) → numbers[0] = 2
i = 2: shiftIndex = 1 (2-1) → numbers[1] = 3
i = 3: shiftIndex = 2 (3-1) → numbers[2] = 4
i = 4: shiftIndex = 3 (4-1) → numbers[3] = 5
Output: 2 3 4 5 1ตัวอย่างที่ 2
Input:
3
10 20 30
การทำงาน:
i = 0: shiftIndex = 2 → numbers[2] = 10
i = 1: shiftIndex = 0 → numbers[0] = 20
i = 2: shiftIndex = 1 → numbers[1] = 30
Output: 20 30 10ปรับปรุงล่าสุด