본문 바로가기
프로그래밍 문제/c# 문제

c# 문제 64. 입력한 값만큼 2차원 배열의 행으로 요소 밀기

by 지나팩 2025. 2. 24.

 

MergeSlime - Google Play 앱

귀여운 슬라임을 합성하여 모든 슬라임을 구출하세요

play.google.com

 

입력한 값만큼 2차원 배열의 요소를 아래로 밀고, 배열을 벗어나는 요소의 경우 제일 앞으로 대입하는 코드를 작성하세요.

 

예)

 

 

이동할 행 수를 입력하세요: 2

 

 

 

코드는 아래에~~~~~~~~

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
 
class Program
{
    static void Main()
    {
        int[,] arr = {
            {  1,  2,  3,  4,  5 },
            {  6,  7,  8,  910 },
            { 1112131415 },
            { 1617181920 },
            { 2122232425 }
        };
 
        Console.WriteLine("원본 배열:");
        PrintArray(arr);
 
        Console.Write("이동할 행 수를 입력하세요: ");
        int shift = int.Parse(Console.ReadLine());
 
        // 이동할 행 수가 배열 크기를 초과하는 경우 최적화
        shift = shift % arr.GetLength(0);
 
        // 행 이동 수행
        for (int i = 0; i < shift; i++)
        {
            ShiftRows(arr);
        }
 
        Console.WriteLine("\n이동 후 배열:");
        PrintArray(arr);
    }
 
    static void ShiftRows(int[,] arr)
    {
        int rows = arr.GetLength(0);
        int cols = arr.GetLength(1);
 
        // 마지막 행을 저장
        int[] lastRow = new int[cols];
        for (int i = 0; i < cols; i++)
        {
            lastRow[i] = arr[rows - 1, i];
        }
 
        // 아래로 행을 한 칸씩 이동
        for (int i = rows - 1; i > 0; i--)
        {
            for (int j = 0; j < cols; j++)
            {
                arr[i, j] = arr[i - 1, j];
            }
        }
 
        // 저장한 마지막 행을 첫 번째 행에 배치
        for (int i = 0; i < cols; i++)
        {
            arr[0, i] = lastRow[i];
        }
    }
 
    static void PrintArray(int[,] arr)
    {
        int rows = arr.GetLength(0);
        int cols = arr.GetLength(1);
        
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                Console.Write(arr[i, j].ToString().PadLeft(3+ " ");
            }
            Console.WriteLine();
        }
    }
}
 
cs

댓글