Tuesday, 15 November 2016

https://www.hackerrank.com/challenges/ctci-array-left-rotation

 http://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/
#import <Foundation/Foundation.h>

// C/C++ program for reversal algorithm of array rotation
#include<stdio.h>



@interface Demo: NSObject{
   
}
-(void) rvereseArray:(int []) arr  s:(int) start  e:(int) end;
@end
@implementation Demo
/* Function to left rotate arr[] of size n by d */
-(void) leftRotate:(int []) arr rotation:(int) d  size:(int) n
{
   [self rvereseArray:arr s:0 e:d-1];
   [self rvereseArray:arr s:d e:n-1];
   [self rvereseArray:arr s:0 e: n-1];
}

/*UTILITY FUNCTIONS*/
/* function to print an array */
-(void) printArray:(int [])arr length: (int) size
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
}

/*Function to reverse arr[] from index start to end*/
-(void) rvereseArray:(int []) arr  s:(int) start  e:(int) end
{
    int temp;
    while (start < end)
    {
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}
@end  

int main(int argc, const char * argv[]){
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int n;
    int k;
    scanf("%i %i",&n,&k);
    int a[n];
    for(int a_i = 0; a_i < n; a_i++){
       scanf("%d",&a[a_i]);
    }
    int first = a[0];
    int length = (sizeof a )/( sizeof a[0]);
 
    Demo *obj = [[Demo alloc]init];
    [obj leftRotate:a rotation:k size:n];
    [obj printArray:a  length:n];
    [pool drain];
    return 0;
}

No comments:

Post a Comment