Подтвердить что ты не робот

Java, перемещение элементов в массиве

У меня есть массив объектов в Java, и я пытаюсь потянуть один элемент в начало и сместить остальные на один.

Предположим, у меня есть массив размером 10, и я пытаюсь вытащить пятый элемент. Пятый элемент переходит в положение 0, и все элементы от 0 до 5 будут сбрасываться на один.

Этот алгоритм неправильно сдвигает элементы:

Object temp = pool[position];

for (int i = 0; i < position; i++) {                
    array[i+1] = array[i];
}
array[0] = temp;

Как мне это сделать правильно?

4b9b3361

Ответ 1

Предполагая, что ваш массив {10,20,30,40,50,60,70,80,90,100}

Что делает ваша петля:

Итерация 1: массив [1] = массив [0]; {10,10,30,40,50,60,70,80,90,100}

Итерация 2: массив [2] = массив [1]; {10,10,10,40,50,60,70,80,90,100}

Что вы должны делать, это

Object temp = pool[position];

for (int i = (position - 1); i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;

Ответ 2

Логически это не работает, и вы должны поменять свой цикл:

for (int i = position-1; i >= 0; i--) {                
    array[i+1] = array[i];
}

В качестве альтернативы вы можете использовать

System.arraycopy(array, 0, array, 1, position);

Ответ 4

Манипуляция массивами таким образом подвержена ошибкам, как вы обнаружили. Лучшим вариантом может быть использование LinkedList в вашей ситуации. Со связанным списком и всеми наборами Java управление массивом обрабатывается внутри, поэтому вам не нужно беспокоиться о перемещении элементов вокруг. С LinkedList вы просто вызываете remove, а затем addLast, и все готово.

Ответ 5

Просто для полноты: потоковое решение начиная с Java 8.

final String[] shiftedArray = Arrays.stream(array)
        .skip(1)
        .toArray(String[]::new);

Я думаю, что я придерживался System.arraycopy() в вашей ситуации. Но самое лучшее долгосрочное решение может быть, чтобы преобразовать все в непреложные коллекции (гуава, Vavr), до тех пор, как эти коллекции недолговечны.

Ответ 6

Попробуйте следующее:

Object temp = pool[position];

for (int i = position-1; i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;

Посмотрите, как это работает: http://www.ideone.com/5JfAg

Ответ 7

В первой итерации вашего цикла вы перезаписываете значение в array[1]. Вы должны пройти через указатели в обратном порядке.

Ответ 8

static void pushZerosToEnd(int arr[])
    {   int n = arr.length;
        int count = 0;  // Count of non-zero elements
        // Traverse the array. If element encountered is non-zero, then
        // replace the element at index 'count' with this element
        for (int i = 0; i < n; i++){
            if (arr[i] != 0)`enter code here`
               // arr[count++] = arr[i]; // here count is incremented
                swapNumbers(arr,count++,i);
        }
        for (int j = 0; j < n; j++){
            System.out.print(arr[j]+",");
        }
     }

    public static void swapNumbers(int [] arr, int pos1, int pos2){
        int temp  = arr[pos2];
        arr[pos2] = arr[pos1];
        arr[pos1] = temp;
    }

Ответ 9

Попробуйте следующее:

public class NewClass3 {

 public static void main (String args[]){

 int a [] = {1,2,};

 int temp ;

 for(int i = 0; i<a.length -1; i++){

     temp = a[i];
     a[i] = a[i+1];
     a[i+1] = temp;

 }

 for(int p : a)
 System.out.print(p);
 }

}

Ответ 10

Еще один вариант, если у вас есть данные массива как Java-List

    listOfStuff.add( 
            0, 
            listOfStuff.remove(listOfStuff.size() - 1) );

Просто поделись другим вариантом, который я натолкнулся на это, но я думаю, что ответ от @Murat Mustafin - это путь со списком

Ответ 11

import java.util.Scanner;

public class Shift {

    public static void main(String[] args) {

        Scanner input = new Scanner (System.in);
        int array[] = new int [5];
        int array1[] = new int [5];
        int i, temp;

        for (i=0; i<5; i++) {
            System.out.printf("Enter array[%d]: \n", i);
            array[i] = input.nextInt(); //Taking input in the array
        }

        System.out.println("\nEntered datas are: \n");
        for (i=0; i<5; i++) {
            System.out.printf("array[%d] = %d\n", i, array[i]); //This will show the data you entered (Not the shifting one)
        }

        temp = array[4]; //We declared the variable "temp" and put the last number of the array there...

        System.out.println("\nAfter Shifting: \n");

        for(i=3; i>=0; i--) {
            array1[i+1] = array[i]; //New array is "array1" & Old array is "array". When array[4] then the value of array[3] will be assigned in it and this goes on..
            array1[0] = temp; //Finally the value of last array which was assigned in temp goes to the first of the new array
        }


        for (i=0; i<5; i++) {
            System.out.printf("array[%d] = %d\n", i, array1[i]);
        }

        input.close();

    }

}

Ответ 12

public class Test1 {

    public static void main(String[] args) {

        int[] x = { 1, 2, 3, 4, 5, 6 };
        Test1 test = new Test1();
        x = test.shiftArray(x, 2);
        for (int i = 0; i < x.length; i++) {
            System.out.print(x[i] + " ");
        }
    }

    public int[] pushFirstElementToLast(int[] x, int position) {
        int temp = x[0];
        for (int i = 0; i < x.length - 1; i++) {
            x[i] = x[i + 1];
        }
        x[x.length - 1] = temp;
        return x;
    }

    public int[] shiftArray(int[] x, int position) {
        for (int i = position - 1; i >= 0; i--) {
            x = pushFirstElementToLast(x, position);
        }
        return x;
    }
}

Ответ 13

Вместо смещения на одну позицию вы можете сделать эту функцию более общей, используя такой модуль.

int[] original = { 1, 2, 3, 4, 5, 6 };
int[] reordered = new int[original.length];
int shift = 1;

for(int i=0; i<original.length;i++)
     reordered[i] = original[(shift+i)%original.length];

Ответ 14

Операция поворота влево на массиве размера n сдвигает каждый из элементов массива влево, проверьте это !!!!!!

public class Solution {
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        String[] nd = scanner.nextLine().split(" ");

        int n = Integer.parseInt(nd[0]);  //no. of elements in the array

        int d = Integer.parseInt(nd[1]);  //number of left rotations

        int[] a = new int[n]; 

      for(int i=0;i<n;i++){
          a[i]=scanner.nextInt();
      }

        Solution s= new Solution();     
//number of left rotations
        for(int j=0;j<d;j++){
              s.rotate(a,n);
        }
   //print the shifted array  
        for(int i:a){System.out.print(i+" ");}
    }

//shift each elements to the left by one 
   public static void rotate(int a[],int n){
            int  temp=a[0];
        for(int i=0;i<n;i++){
            if(i<n-1){a[i]=a[i+1];}
            else{a[i]=temp;}
      }}
}