HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

C program circular array rotation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraycircularprogramrotation

Problem

I'm trying to solve a Hackerrank problem where you perform k array[n] rotations, and at the end, ask for m and print array[m]. My program is probably correct (it runs perfectly for most of tests, but some of them terminate due to timeout), but is inefficient and I don't know how to improve it.

#include 
#include 
#include 
#include 
#include 
#include 
#include 

int main(){
    int n; 
    int k; 
    int q; 
    scanf("%d %d %d",&n,&k,&q);
    int *a = malloc(sizeof(int) * n);
    int *b = malloc(sizeof(int) * n);
    for(int a_i = 0; a_i < n; a_i++){
       scanf("%d",&a[a_i]);
    }
    for(int i = 0; i < k; i++){
        b[0] = a[n-1];
        for(int a_i = 1; a_i < n; a_i++){
        b[a_i] = a[a_i-1];
        }
        for(int a_i = 0; a_i < n; a_i++) a[a_i] = b[a_i];
    }
    for(int a0 = 0; a0 < q; a0++){
    int m; 
    scanf("%d",&m);
    printf("%d\n", b[m]);
    }
    return 0;
}

Solution

Do not do actual rotation.

k rotations (from your code I understand that all rotations are to the right by 1) map an i'th element to an (i + k) % n position. At the time of printing, do some math to figure out which element was mapped to the position m.

The math is trivial, and I intentionally do not spell it out.

Context

StackExchange Code Review Q#145998, answer score: 10

Revisions (0)

No revisions yet.