Friday, 8 April 2022

Array Rotate Problem !!!

 PROBLEM 48: Array Rotate 


A program to rotate 'N' number of elements in an array depending on the size of the rotate. Rotation to be considered from both the ends of an array. (Without using Built-in functions) (INTERVIEW QUESTION)

(For best view experience, view in windows version)


Author - Ajay Zad

Date     - 08/04/2022


n = int(input("Enter the size of the array :"))

m = int(input("Enter the size of rotation :"))

l = []

for i in range(0,n):

        a = int(input("Enter the elements in the array :"))

        l.append(a)

x = 1

while x == 1:

        d = input("Enter the direction for rotation Right(r) or Left(l):")

        if d == 'l':

            l2 = list(l)        

            j = 1

            for i in range(m-1,-1,-1):

                l2[n-j] = l[i]   

                j = j + 1

            j = 0

            for i in range(m,n):

                 l2[j] = l[m+j]

                 j = j + 1

            print(l2)

            l = l2[:]        

        elif d == 'r':

            l2 = list(l)

            j = 0

            for i in range(m-1,-1,-1):

                l2[i] = l[n-(j+1)]

                j = j + 1

            j = 0

            for i in range(m,n):

                l2[m+j] = l[j]

                j = j + 1

            print(l2)

            l = l2[:]

        else:

            print("Enter the correct option")

        x = int(input("Enter 1 to continue or press any other number to exit: "))

   

The above code is in Python language.


Input:

Enter the size of the array : 8
Enter the size of rotation   : 4

Enter the elements in the array : 1
Enter the elements in the array : 2
Enter the elements in the array : 3
Enter the elements in the array : 4
Enter the elements in the array : 5
Enter the elements in the array : 6
Enter the elements in the array : 7
Enter the elements in the array : 8

Enter the direction for rotation Right(r) or Left(l): l
[5, 6, 7, 8, 1, 2, 3, 4]

Enter 1 to continue or press any other number to exit: 1

Enter the direction for rotation Right(r) or Left(l): r
[1, 2, 3, 4, 5, 6, 7, 8]

Enter 1 to continue or press any other number to exit: 2












  



No comments:

Post a Comment

Rearrange an array with O(1) extra space

  PROBLEM 61:  Rearrange an array with O(1) extra space (For best view experience, view in windows version) Problem Reference : GeeksForGeek...