Advertisement
Guest User

Rotate array A by K elements in C#

a guest
Mar 19th, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class Solution {
  5.     public int[] solution(int[] A, int K) {
  6.        
  7.         // If we got an empty array, just return it
  8.         if (A.Length == 0) {
  9.             return A;
  10.         }
  11.        
  12.         // Set that allows us to track which indexes we rotated already
  13.         var rotatedIndexes = new HashSet<int>();
  14.        
  15.         // We start from the first index
  16.         int currentIndex = 0;
  17.        
  18.         // We get the value at the current index
  19.         int currentValue = A[currentIndex];;
  20.        
  21.         // Number of rotations is the number of elements in A
  22.         for (int r = 0; r < A.Length; r++) {
  23.            
  24.             // If the index was already rotated
  25.             while (rotatedIndexes.Contains(currentIndex)) {
  26.                
  27.                 // Go to the next index
  28.                 currentIndex++;
  29.                
  30.                 // If we are past the length, get the correct one [index % length is a value ranging from 0 to length-1 (a valid index)]
  31.                 currentIndex %= A.Length;
  32.                
  33.                 // Update the value to move to the current index
  34.                 currentValue = A[currentIndex];
  35.             }
  36.            
  37.             // Calculate the next index
  38.             int nextIndex = currentIndex + K;
  39.            
  40.             // Check again if we are past the length and calculate the corret index in case we do
  41.             nextIndex %= A.Length;
  42.        
  43.             // Set temp value
  44.             int tempValue = A[nextIndex];
  45.            
  46.             // Swap
  47.             A[nextIndex] = currentValue;
  48.            
  49.             // Set next value
  50.             currentValue = tempValue;
  51.            
  52.             // Add current index to rotated
  53.             rotatedIndexes.Add(currentIndex);
  54.            
  55.             // Set the current index
  56.             currentIndex = nextIndex;
  57.         }
  58.        
  59.         return A;
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement