"If you do nothing, nothing will happen."

프로그래밍

[Hackerrank] Left Rotation

tedhong 2023. 2. 20. 12:54
2019-05-27 글쓴이 TED HONG

[Hackerrank] Left Rotation

 배열 a 중에 특정한 숫자  n을  지정한 횟수 d 만큼 왼쪽으로

로테이션 시키는 문제

 

class Solution {



    static void Main(string[] args) {
        string[] nd = Console.ReadLine().Split(' ');

        int n = Convert.ToInt32(nd[0]);

        int d = Convert.ToInt32(nd[1]);

        int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), aTemp => Convert.ToInt32(aTemp))
        ;

        int[] result = GetRotateArray(n, d, a);
        Console.WriteLine(string.Join(" ", result));
    }

    static int[] GetRotateArray(int n, int d, int[] a)
    {
        int length = a.Length;
        int rCnt = d % length;
        
        int[] resultArray = new int[length];
        for(int i = 0 ; i < length; i++)
        {
            int newIndex = GetIndex(i, length, d);
            resultArray[newIndex] = a[i];
        }
        return resultArray;
    }

    static int GetIndex(int index, int l, int d)
    {
        int result = 0;
        result = index + (l - d); 
        if(result > (l - 1)) result -= l;
       
        return result;
    }
}

'프로그래밍' 카테고리의 다른 글

[HackerRank] Common Child  (0) 2023.02.20
[HackerRank] Sparse Arrays  (0) 2023.02.20
[HackerRank] Sherlock and Anagrams  (0) 2023.02.20
[HackerRank] New Year Chaos  (0) 2023.02.20
[Hackerrank] 2D Array – DS  (0) 2023.02.20