моя строка двухмерного массива не вращается - PullRequest
0 голосов
/ 01 мая 2020

Я пытаюсь решить проблему поворота строки двумерного массива, и я дал ниже детали ввода ввода
после ввода 1 5 2 1 2 3 4 5 Я получаю вывод : -3 4 5 0 0, но ожидаемый результат равен 3 4 5 1 2

package geeksforgeeks.basic;

import java.util.Scanner;

public class RotationOfAnArray
{
    public static void main( String[] args )
    {

        Scanner sc = new Scanner( System.in );
        //initializing the variables and the matrix
        int i, j, n, k, l, f, p;
        //taking the input
        n = sc.nextInt();
        int[][] arr1 = new int[100][100];
        for( i = 0; i < n; i++ )
        {
            k = sc.nextInt();
            l = sc.nextInt();
            for( j = 0; j < k; j++ )
            {
                arr1[i][j] = sc.nextInt();
            }
            //in the above section taking the input of the elements of the array of the matrix
            for( f = 0; f < l; f++ )
            {
                p = arr1[0][0];
                for( j = 0; j < arr1.length - 1; j++ )
                {
                    arr1[i][j] = arr1[i][j + 1];
                }
                //here the row of the particular matrix is not rotated
                arr1[i][arr1.length - 1] = p;
            }
            for( j = 0; j < k; j++ )
            {
                System.out.print( arr1[0][j] + "  " );
            }
        }
    }
}

Ответы [ 2 ]

0 голосов
/ 01 мая 2020

Проблема с вашим кодом заключается в том, что вы инициализируете размер массива как 100, и когда позже, когда вы пытаетесь заменить последний элемент на arr1[i][arr1.length-1]=p;, он заменяет последний 99-й индекс, а не 4-й индекс. Если вы будете выполнять итерацию по всему массиву, вы увидите, что эти значения наконец-то находятся. Мое предложение инициализировать массив с размером вашей потребности. import java .util.Scanner;

public class RotationOfAnArray {
public static void main(String[] args) {

Scanner sc=new Scanner(System.in);
//initializing the variables and the matrix
int i,j,n,k,l,f,p;
//taking the input
n=sc.nextInt();
int[][] arr1;
for(i=0;i<n;i++){
k=sc.nextInt();

//********Initialise array here instead.******
arr1=new int[k][k];


l=sc.nextInt();
for(j=0;j<k;j++){
arr1[i][j]=sc.nextInt();
}
//in the above section taking the input of the elements of the array of the matrix
for(f=0;f<l;f++) {
p=arr1[0][0];
for(j=0;j<arr1.length-1;j++) {
arr1[i][j]=arr1[i][j+1];
}
//here the row of the particular matrix is not rotated
arr1[i][arr1.length-1]=p;
}  
for(j=0;j<k;j++) {
System.out.print(arr1[0][j]+"  ");
}
}
}
}
0 голосов
/ 01 мая 2020

Я полагаю, что проблема заключалась в том, что вы перезаписывали массив во время его итерации, вот пример использования одномерного массива.

Scanner sc=new Scanner(System.in);
//initializing the variables and the matrix
int n,k,l;
//taking the input
n=sc.nextInt();//TestCases
k=sc.nextInt();//ArrayLength
l=sc.nextInt();//Rotations

int[] arr=new int[k];
for(int i=0;i<k;i++){
arr[i]=sc.nextInt();
}//in the above section taking the input of the elements of the array of the matrix

//Rotating the array
int[] backupArr = new int[k];//Backup is made as not to overwrite array 
for(int i=0;i<arr.length;i++) {
backupArr[((i+arr.length-l)%arr.length)]=arr[i];//Modulo is used to keep index within constraints of array
}
arr=backupArr;//array is set to rotated instance

for(int a : arr)System.out.print(a);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...