dimanche 21 janvier 2018

Shifting elements and printing each step

Im trying to shift elements in an array and print each step until they are back to their original positions. The array has to be filled with random numbers and must not be over the size of 15. I approached the task by creating a new array when the shifting occurs. If anyone has any better suggestions let me know. Ive done the array and the shifting part once, but cant seem to figure out how to repeat it. Here is what I came up with:

public static void main(String[] args) {

    System.out.println("Enter size: ");
    Scanner s = new Scanner(System.in);
    int p = s.nextInt();
    if (p > 15) {
        System.out.println("Too much to handle!");
    }
    int oldArray[] = new int [p];
for (int i = 0; i<oldArray.length;i++) {
        oldArray[i]=(int)(Math.random()*10);
    }
    int newArray[] = moveA(oldArray);
    printA(oldArray);
    printA(newArray);
}

public static int[] moveA(int[] array1) {
int[] array2 = new int[array1.length];

 for (int i = 0; i < array2.length - 1; i++) {
    array2[i+1] = array1[i];
}
array2[0] = array1[array1.length - 1];
return array2;
}

public static void printA(int[] arr) {
    System.out.println(Arrays.toString(arr));
}

The code prints like this:

Enter size: 
4
[1, 5, 9, 3]
[3, 1, 5, 9]

Ive tried doing a for loop at:

for ( int b = 0; b <= oldArray.length; b++)
int newArray[] = moveA(oldArray);
printA(oldArray);
printA(newArray)

but all it does is print it 4 times.




Aucun commentaire:

Enregistrer un commentaire