-2

For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes.

For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should return [9, 7, 6, 3, 8].

I want this in java. I have tried this.

public static int[] rotation(int[] a,int k) {

    int[] newArray = new int[a.length];
    for(int i = 0 ; i < a.length ; i++) {
        int newPosition = (i + k)%a.length;
        newArray[newPosition] = a[i];
    }
    return newArray;
}
vindev
  • 2,240
  • 2
  • 13
  • 20
Dhaval Mistry
  • 476
  • 1
  • 9
  • 17

19 Answers19

5

I didnt get what exactly wants topic starter but here my code for this task

class Solution {
public int[] solution(int[] arr, int k) {
    int[] newArr = new int[arr.length];

    if (arr.length == 0) return arr;
       k = k%arr.length;
    for (int i=0; i<arr.length; i++) {

      newArr[i] = arr[(i + (arr.length - k)) % (arr.length)];

    }

    return newArr;
}

}

2

You can also use A = B.clone();

public int[] solution(int[] A, int K) {
    // write your code in Java SE 8

    int [] B =new int [A.length];

    for(int l=0;K>l;K--){
        int j=0;
        for(int i=0;i<A.length;i++){
            if(i==0){
                B[j]=A[A.length-1];
                j++;
            }
            else{
                B[j]=A[i-1];
                j++;
            }
        }

        //below part
        /*for(int i= 0;i<A.length;i++){
            A[i]=B[i];
        }*/
        A = B.clone();

    }
    return B;
} 

If you like :D

Talha
  • 524
  • 1
  • 6
  • 22
Hooney
  • 36
  • 2
1

You can print the result using Arrays.toString. For example:

System.out.println(Arrays.toString(rotation(new int[] { 3, 8, 9, 7, 6}, 3)));
mm759
  • 1,404
  • 1
  • 9
  • 7
0
public int[] solution(int[] A, int K) {
    // write your code in Java SE 8

    int [] B =new int [A.length];

    for(int l=0;K>l;K--){
        int j=0;
        for(int i=0;i<A.length;i++){
            if(i==0){
                B[j]=A[A.length-1];
                j++;
            }
            else{
                B[j]=A[i-1];
                j++;
            }
        }
        for(int i= 0;i<A.length;i++){
            A[i]=B[i];
        }

    }
    return B;
} 
Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
0
  function solution(A, K) {

        function shiftArray(arrayToShift, newArray=[] ){
            newArray[0] = arrayToShift[arrayToShift.length-1] ; 
            for (var i=1; i<arrayToShift.length; i++){
                newArray[i] = arrayToShift[i-1];   
            }
            // console.log("arrayToShift");
            // console.log(newArray);
            return newArray;
        }


        var newArray = A;
        for(var i=0; i<K; i++){
            newArray =  shiftArray(newArray);
        }
        return newArray
    }


console.log(solution([3, 8, 9, 7, 6], 3));
0

Achieved 100% correctness

public int[] solution(int[] A, int K) {
    // write your code in Java SE 8
    if(K == A.length || A.length == 0)
        return A;
    if(K > A.length) {
        K = K%A.length;
    }
    int[] arr1 = Arrays.copyOfRange(A, A.length-K, A.length);
    int[] arr2 = Arrays.copyOfRange(A, 0, A.length-K);
    int aLen = arr1.length;
    int bLen = arr2.length;
    int[] result = new int[aLen + bLen];
    System.arraycopy(arr1, 0, result, 0, aLen);
    System.arraycopy(arr2, 0, result, aLen, bLen);
    return result;
}
0

Here's my solution using JavaScript, tested 100%.

function solution(A, K) {
    for(let i=0; i<K; i++) {
        let lastIndex = A.length - 1;
        let lastItem = A[lastIndex];
        for(let j=(A.length-1); j>-1; j--) {
            if(j>0) {
                A[j] = A[j-1];
            } else {
                A[j] = lastItem;
            }
        }
    }
    return A;
}
Chigozie Orunta
  • 448
  • 3
  • 13
0

class Solution { public int[] solution(int[] A, int K){

    if((A.length == 0) || (K == 0)){
        return A;
    }
    int [] B = new int[A.length];
    int c = K;
    while(c != 0){
        for(int i = 1; i< A.length; i++){
            B[i] = A[i-1];
        }
        c--;
        B[0] = A[A.length-1];
        System.arraycopy(B, 0, A, 0, A.length);
    }
    return A;
}

}

0

In Kotlin:

fun flipList(list: List<Int>, times: Int): List<Int> {
    val flippedList = list.toMutableList()
    val referenceList = list.toMutableList()
    repeat(times) {
        var position = 0
        referenceList.forEach {
            position++
            if (position < list.size)
                flippedList[position] = referenceList[position -1]
            else
                flippedList[0] = referenceList.last()
        }
        referenceList.clear()
        referenceList.addAll(flippedList)
    }
    return flippedList
}

Unit Teste

class FlipListUnitTest {
        private val referenceListMock = listOf(1,2,3,4)
        private val referenceListOneTimeFlipResultMock = listOf(4,1,2,3)
        private val referenceListFourTimesFlipResultMock = listOf(1,2,3,4)
        @Test
        fun `check test api is working`(){
            assertTrue(true)
        }

        @Test
        fun `check list flip 1 time`(){
            assertTrue(flipList(referenceListMock, 1) == referenceListOneTimeFlipResultMock)
        }

        @Test
        fun `check list flip 4 time`(){
            assertTrue(flipList(referenceListMock, 4) == referenceListFourTimesFlipResultMock)
        }
}
Rodrigo Salomao
  • 143
  • 1
  • 10
0

Here in my code

public static int[] solution(int[] A, int K){
    if(A.length > 0) {
        for(int i = 0; i < K ; i++){
            int temp = A[A.length - 1];
            for(int j = A.length - 2; j >= 0; j--){
                A[j + 1] = A[j];
            }
            A[0] = temp;
        }
    }
    return A;
}
0
public static int[] solution(int[] A, int K) {
    if(A.length<1)
        return A;
    int[] newArray = new int[A.length];

    while (K>0){
        newArray[0]=A[A.length-1];
        for(int i=0; i<A.length-1; i++){
            newArray[i+1]=A[i];
        }
        for (int i=0; i<newArray.length; i++) {
            A[i]=newArray[i];
        }
        K--;
    }
    return A;
}
Mwas
  • 153
  • 2
  • 6
  • 17
0

An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place.

Hi everyone here is another simple solution for this problem in JAVA, 100% working.

class Solution {
    public int[] solution(int[] A, int K) {
        
        // Corner cases to save resources
         if(K == 0 || A.length <= 0 || A.length == K){
             return A;
         }
         
         // Loop to traverse K times
         for(int i=0; i<K; i++){
             int last = A[A.length - 1]; // Last digit
             
             // Loop to traverse A.Length times in swing order,
             // so that first element can be set
             for(int j=A.length-1; j>0; j--){
              A[j] = A[j-1];   
             }
             
             // Set last element
             A[0] = last;
         }
         
         // Return result
         return A;
    }
}

0

Here is my answer in JavaScript

function solution(A, K){
let arr = [];
let lastIndex = A.length -1;
        let rotation = K-1;
    for(let i = 0; i < K; i++){
        arr[rotation] = A[lastIndex];
        --lastIndex; 
        --rotation;
    }

    for(let j = 0; j <= lastIndex; j++){
        arr.push(A[j]);
    }
    return arr;
}
0

Here is my answer in Python without loop and using string substitution

def solution(A, K):
    K = K % len(A) if K > len(A) else K
    if (K == 0) or (K == len(A)) or (len(A) in [0, 1]):
        return A
    
    first_index = len(A) - K
    return A[first_index:] + A[:first_index]
EmreAydin
  • 183
  • 2
  • 7
0
function solution(A, K) {
   let tmpA = [];
   for (let i = 1; i <= K; i++){
       tmpA.unshift(A.pop());
   }
   for (let i = 1; i <= K; i++){
       A.unshift(tmpA.pop());
   }
   return A;   
}
  • This answer appears to be Javascript code. The question requested Java code and gave an attempt in Java, not Javascript. – user9712582 Jul 24 '22 at 01:20
0

This is the code written in PHP but logic can be used in any language.

function solution($A, $K) {
// write your code in PHP7.0      
    $cnt = count($A);
    for($i=1; $i<=$K; $i++){ 
        foreach($A as $key=>$val){
            $key++;
            if($key==$cnt){
                $A[0] = $val;
            }
            else
            {   
                $A[$key] = $val;
            }
        }
    }
    return $A;
}
Mohneesh
  • 1
  • 1
0
public static int[] rotateArrayKTimes(int[] A, int K) {

        if (A.length == 0 || A.length > 1000 || K > 100) {
            return new int[]{};
        }
        for (int index = 0; index < K; index++) {
            int temp = A[A.length - 1];
            System.arraycopy(A, 0, A, 1, A.length - 1);
            A[0] = temp;
        }
        return A;
    }
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
0

javascript | score: 100%

function solution(A, K) {

for(let i=0 ; i<K ; i++){
    let lastIndex = A.length-1;
    let lastNumber = A[lastIndex];
    A.unshift(lastNumber);
    A.pop();
}
return A;

}

  • Your post is mostly code, please add some more explanation of how it works – André Walker Oct 14 '22 at 14:49
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 14 '22 at 14:50
0

JAVA solution -

class Solution2 {
    public int[] solution(int[] arr, int k) {
        int temp;
        int startindex = 0;
        if (arr.length != 0) {
            for (int i = 1; i <= k; i++) {
                temp = arr[arr.length - 1];
                for (int j = arr.length - 1; j >= startindex; j--) {

                    if (j != (startindex)) {
                        arr[j] = arr[j - 1];
                    } else
                        arr[startindex] = temp;
                }
            }
        } else
            System.out.println("This is empty array");
        return arr;
    }

}