0

I am having trouble with an output for my code and cant understand why I am getting this output. The problem is: "Given an array of n elements and an integer k, 0 < k ≤ n, design and implement an algorithm that shifts the array to the left by k positions and “wraps around” any elements that “fall” from the front of the array to the back of the array. The algorithm can use O(n) time and O(n) space, where n is the number of elements in the input array."

import java.util.Scanner;

public class ShiftingArrayElements{
    public static void main(String [] args) {
        int x = 0;
        int j=0;

        Scanner sc = new Scanner(System.in);

        String data = sc.nextLine();
        x = sc.nextInt();
        String tmpDataArray[] = data.split(" ");

        int dataArray[] = new int[tmpDataArray.length];
        for (int i = 0; i < dataArray.length; ++i) {
            dataArray[i] = Integer.parseInt(tmpDataArray[i]);   
        }

        if(x > dataArray.length) 
            x = x%dataArray.length;

        int result[] = new int[dataArray.length];

        for(int i=0; i < x; i++){
            result[i] = dataArray[dataArray.length-x+i];
        }

        for(int i=x; i<dataArray.length; i++){
            result[i] = dataArray[j];
            j++;
        }
        System.out.print("Output:" + result + " ");
        System.arraycopy( result, 0, dataArray, 0, dataArray.length );

        sc.close();
    }
}

My Input should look like this:

3 4 5 19 10
2

My output should look like this:

Output: 5 19 10 3 4

My output when I run it is:

Output:[I@42a57993
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Luke J
  • 1
  • 1

1 Answers1

3

In Java, if you write something like

System.out.print("Output:" + result + " ");

then result will be converted to a string by calling the built-in array class's toString() method, which by default just prints out a not particularly human-readable string consisting of the array type and the array's hash code. In this case, since it's an array of ints, you're seeing the type ([I) and the hash code (@42a57993).

If you want to see a human-readable version of the array, use the Arrays.toString method, which is in java.util:

System.out.print("Output:" + Arrays.toString(result) + " ");

For what it's worth, there are a number of algorithms for rotating an array in-place, using only O(1) auxiliary memory. You may want to read up on them - they're pretty clever!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • i tried this but my output now is the original array i type into the scanner – Luke J Sep 19 '17 at 01:15
  • @LukeJ That's an independent issue. Look back at your code. When are you printing the array? Where does that happen relative to when you copy the elements over? – templatetypedef Sep 19 '17 at 01:27