Link to Question:
https://www.hackerrank.com/challenges/array-left-rotation/problem
https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem
Program:
#include <stdio.h>
main()
{
int n,i,d;
scanf("%d%d",&n,&d);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=d;i<d+n;i++)
printf("%d ",a[i%n]); // we start printing from last index
}
==============================================================
Circular Array Rotation
Link to Question
https://www.hackerrank.com/challenges/circular-array-rotation/problem
Program
#include <stdio.h>
int main()
{
int n,i,k,q,j=0;
scanf("%d%d%d",&n,&k,&q);
int a[n],b[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
//after every n rotations, the rotated array becomes original array
int r=k%n;
for(int i=0;i<n;i++)
b[(i+r)%n]=a[i];
while(q--)
{
int id;
scanf("%d",&id);
printf("%d\n",b[id]);
}
}
You can write the above program without using array b
by using
printf("%d\n",a[(n-(k%n)+m)%n]);
===============================================================================by using
printf("%d\n",a[(n-(k%n)+m)%n]);
output:
5
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4
1 2 3 4 5
#include <stdio.h>
main()
{
int n,i,j;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n+1;i++)
{
for(j=i;j<i+n;j++)
printf("%d ",a[j%n]); // we start printing from first index
printf("\n");
}
}
=======================================================================
output:
5
1 2 3 4 5
5 1 2 3 4
4 5 1 2 3
3 4 5 1 2
2 3 4 5 1
1 2 3 4 5
#include <stdio.h>
main()
{
int n,i,j;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=n-1;i>=0;i--)
{
for(j=i;j<i+n;j++)
printf("%d ",a[j%n]); // we start printing from last index
printf("\n");
}
}
No comments:
Post a Comment