프로그래밍 문제/c# 문제
c# 문제 63. 배열의 요소를 입력 값만큼 밀어서 재정렬
지나팩
2025. 2. 17. 17:10
MergeSlime - Google Play 앱
귀여운 슬라임을 합성하여 모든 슬라임을 구출하세요
play.google.com
입력한 값만큼 배열의 요소를 뒤로 밀고, 배열을 벗어나는 요소의 경우 제일 앞으로 대입하는 코드를 작성하세요.
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
입력 예) 이동할 칸 수를 입력하세요: 3
출력 예)
이동 전 배열: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
이동 후 배열: 8, 9, 10, 1, 2, 3, 4, 5, 6, 7
코드는 아래에~~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
using System;
class Program
{
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Console.WriteLine("원본 배열: " + string.Join(", ", arr));
Console.Write("이동할 칸 수를 입력하세요: ");
int shift = int.Parse(Console.ReadLine());
// 이동할 칸 수가 배열 크기를 초과하는 경우 최적화
shift = shift % arr.Length;
// 요소를 한 칸씩 뒤로 이동하는 연산을 shift 번 반복
for (int j = 0; j < shift; j++)
{
int lastElement = arr[arr.Length - 1]; // 마지막 요소 저장
// 모든 요소를 뒤로 한 칸씩 이동
for (int i = arr.Length - 1; i > 0; i--)
{
arr[i] = arr[i - 1];
}
arr[0] = lastElement; // 마지막 요소를 첫 번째 요소로 이동
}
Console.WriteLine("이동 후 배열: " + string.Join(", ", arr));
}
}
|
cs |