javip
javip

Reputation: 259

Shifting array to the right - homework

This is what I have so far, but when I run it, I get a Java mismatch error. This is my array:

char[] letters = {'A', 'B' , 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};


/********************************************************************************
    shiftRight() will move the contents of the array one slot to the right
********************************************************************************/
public static void shiftRight( char [] letters )
{
    char last = letters[letters.length-1];          // save off first element

    // shift right
    for( int index =letters.length-1; index >= 0 ; index-- )
        letters[index+1] = letters [index];

    // wrap last element into first slot
    letters[0] = last;
    System.out.print("\nshifted Array: " );
}

Upvotes: 5

Views: 86179

Answers (6)

Senthuran
Senthuran

Reputation: 1837

Following solution worked for me.

   public void rightShiftArray(int[] arr, int n){
        int[] output=new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            int newLocation = (i+(arr.length+n))%arr.length;
            output[newLocation] = arr[i];
        }
        for (int i = 0; i < output.length; i++) {
            System.out.print(output[i]+",");
        }
    }

arr -> Array to be shifted n -> Shift the element by how many position.

Upvotes: 0

Shankar Bhattarai
Shankar Bhattarai

Reputation: 1

For integer Values

You can do something like for integer values:

public static void main(String[] args) {
    int arr[] = {1,2,3,4,5};
    arrayReorder(arr,25);
}



private static void arrayReorder(int[] arr, int repeat) {
    int count = 0;
    int length = arr.length;
    int end = 0;
    int traversedArray[] = new int[length];

    while (count < repeat) {
        end = arr[length-1];
        for (int i = 1; i < length; i++) {
            traversedArray[i] = arr[i-1];
            traversedArray[0] = end;
        }
        System.out.println();
        for (int a : traversedArray) {
            System.out.print(a + " -> ");
        }
        arr = traversedArray.clone();
        count++;
    }
}

Upvotes: 0

Yogendra Singh
Yogendra Singh

Reputation: 34367

When letters[index+1] is executed for the first time in the for-loop (when index = letters.length-1), it's pointing to letters[letters.length] which is not a valid index, since indexes go from 0 to length-1.

Update your for-loop to start index at letters.length-2 and also make sure your array.length>1. That is to say:

   if(letters.length > 1){ //make sure array has minimum two elements
      // shift right
      for( int index = letters.length-2; index >= 0 ; index-- ){
          letters[index+1] = letters [index];
      }
   }

Also in the end, you may print the array as:

   System.out.println("Shifted Array: " +letters); 

EDIT: Sample working code.

If you make the array as Character array e.g. below in your main (this is required for assistance in printing ONLY)

    Character[] letters = {'A', 'B' , 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};

and then pass that to shiftRight method with updated code as below:

  public static void shiftRight( Character [] letters )
  {
    Character last = letters[letters.length-1];  
    if(letters.length >1){ //make sure array has minimum two elements
        // shift right
        for( int index =letters.length-2; index >= 0 ; index-- ){
            letters[index+1] = letters [index];
        }
     }
    letters[0] = last;
    System.out.println(Arrays.toString(letters));
    //^ prints: Shifted Array: [J, A, B, C, D, E, F, G, H, I]
  }

You should be all set.

Upvotes: 2

Mik378
Mik378

Reputation: 22171

Indeed, you obtain an ArrayIndexOutOfBoundsException as soon as you want to read (within the loop):

letters[index+1]

The cause is the your index variable initialization: index = letters.length-1

So letters[index+1] == letters[letters.length] but logically letters.length leads to ArrayIndexOutOfBoundsException.

A simple way to correct your code without changing your logic:

for(int index = letters.length-1; index > 0 ; index--)
   letters[index] = letters [index-1];

Notice the operator sign > instead of >=. Otherwise, this would also lead to the same Exception.

Furthermore, in order to display the final array, use: Arrays.toString(letters)

I've even written my solution keeping your logic:

public static void main(String[] args) {
    char[] letters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
    printShiftedLetters(shiftElementsToRight(letters));
}

public static char[] shiftElementsToRight(char[] array) {
    if (array == null) {
        throw new NullPointerException("array must not be null");
    }
    if(array.length <= 1){
        return array;
    }
    char[] shiftedArray = new char[array.length];
    char lastElement = array[array.length - 1];
    for (int i = array.length - 1; i > 0; i--) {
        shiftedArray[i] = array[i - 1];
    }
    shiftedArray[0] = lastElement;
    return shiftedArray;
}

private static void printShiftedLetters(char[] shiftedLetters) {
    System.out.println(Arrays.toString(shiftedLetters));
}

Upvotes: 0

dan
dan

Reputation: 13262

You can do something like:

 public static void shiftRight( char [] letters )
    {

        char last = letters[letters.length-1];          // save off first element

        // shift right
        for( int index =letters.length-2; index >= 0 ; index-- )
            letters[index+1] = letters [index];

        // wrap last element into first slot
        letters[0] = last;
        System.out.print("\nshifted Array: " + Arrays.toString(letters) );

    }

I only modified your: letters.length-1 into letters.length-2 and printed the array.

Another, easier approach is to use, System.arraycopy like:

last = letters[letters.length-1];
System.arraycopy(letters, 0, letters, 1, letters.length-1 );
letters[0] = last;

To print the array you can also use:

System.out.print("{");
for (int i=0;i<letters.length-1;i++)
    System.out.print("'"+letters[i]+",");
System.out.println("'"+letters[letters.length-1]+"'}");

Upvotes: 12

PermGenError
PermGenError

Reputation: 46398

add

     if(index<letters.length-1)  condition 

inside your for loop before

 letters[index+1] = letters [index]

if you don't check if(index<letters.length-1) condition you'd get ArrayIndexOutOfBounds Exception at your last inddex here letters[index+1] = letters [index]

Upvotes: 0

Related Questions