You are viewing a single comment's thread. Return to all comments →
Here's what worked for me in C++. After taking values of n and k:
while(k greater than n)k=k-n;
The value of k can be several times greater than n, so by putting this can lead to referencing an index in the array greater than n, which causes segmentation fault. And the output will be correct because performing 5 rotations in an array of 4 elements is same as performing 1 rotation.
you could use k=k%n, what if the k is doulble or trible the size of n. subtraction always reduce one rotation.
Consider if k = 3n => k = 3n -n => k = 2n. but in case of
modular it reduces to n rotation. k = 3n => k = 3n%n => k = 0.
If K=2n then the loop will run twice and k will be set to 0. If k is a multiple of n then the array after k rotations will be same as initial array. k=k%n could also do the trick.
if k is a multiple of n then won't the remainder be 0?
Yes. Which means, in effect, that no rotation should be performed upon the array, because rotating each element by k will have each of them end up right back where they started. Using 0 for k will have that effect.
thank you sir.
This helped me out thanks
how it worked please can u explain me??
You can determine where in the array each element will end up with a simple calculation using the number of elements (n), the number of times you perform the operation (k), and an incrementing variable (use a for loop). Try to figure out the equation and use that answer as the array assignment. You need to use the while loop right before the array assignment because sometimes the calculation you perform will leave you with an array assignment value that is greater (hint) than the amount of array values so you just repeat the same equation until you get a valid value (something < n).
Here i have explained it in detail.
Circular Array Rotation
Thanks, It worked in Python.
In fact, it would work in any language.