1

Sample Input #1

shift({'a','b','c','d','e'})

Sample Output #1

{'b','c','d','e','a'}

public class ShiftElements {

    static char[] testcase1 = {'a', 'b', 'd', 'c', 'b', 'd', 'c'};

    public static void main(String args[]) {
        ShiftElements testInstance = new ShiftElements();
        char[] result = testInstance.shift(testcase1);
        System.out.println(result);
    }

    public char[] shift(char[] elements) {

        if (elements.length >= 2) {
            int temp = elements[0];
            for (int i = 0; i < elements.length - 1; i++)
            elements[i] = elements[i + 1];
            temp = elements[elements.length - 1];
        }
        return elements;

    }

when i am trying to run testcase it failed my input {'b','c','d','e','a'}'. my output {'c','d','e','a','a'} correct output {'c','d','e','a','b'}.what to do?

singhakash
  • 7,891
  • 6
  • 31
  • 65
Pallavi Singh
  • 133
  • 10
  • FYI: Since you're changing the array in-place, there's no need to return the array. Just print `testcase1`. – Andreas Aug 20 '15 at 17:34

3 Answers3

5
temp=elements[elements.length-1];

That should have been the other way around. You are merely assigning elements[elements.length-1] to your local temporary variable, rather than changing elements[elements.length-1].

Change it to:

elements[elements.length-1] = temp;

Also, make temp a char, it does not need to be an int.

amit
  • 175,853
  • 27
  • 231
  • 333
  • possible loss of precision at elements[elements.length-1]=temp; – Pallavi Singh Aug 20 '15 at 17:27
  • @PallaviSingh That's because you made `temp` an `int` (not a `char`). It's unneeded, and the loss of precision cannot happen. – amit Aug 20 '15 at 17:28
  • @PallaviSingh That is because you defined `temp` as `int`, not as `char`. – Andreas Aug 20 '15 at 17:28
  • @amit can you please help me out with this question? i am sending you link. http://stackoverflow.com/questions/32357614/given-arr1-arr2-that-have-been-sorted-in-descending-order-output-an-array-wh/32357765?noredirect=1#comment52598562_32357765 – Pallavi Singh Sep 03 '15 at 07:53
1

Your last line should be flipped:

elements[elements.length-1] = temp;

The shifting of the elements can also be done using System.arraycopy:

char temp = elements[0];
System.arraycopy(elements, 1, elements, 0, elements.length - 1);
elements[elements.length - 1] = temp;
Andreas
  • 154,647
  • 11
  • 152
  • 247
0

Another way would be to use a String:

public char[] shift(char[] elements) {
    return elements.length < 2 ? 
        elements : 
        (new String(elements, 1, elements.length - 1) + elements[0])
            .toCharArray();
}
fps
  • 33,623
  • 8
  • 55
  • 110