2014-11-15 3 views
0

Я пытаюсь скопировать элементы 2D-массива в 1D-массив. Я знаю, что мне нужно использовать вложенный цикл для копирования элементов, но я не знаю, с чего начать. Вот то, что я до сих пор:Копирование элементов 2D-массива в 1D-массив

import java.util.Scanner; 
import java.io.IOException; 

public class assignment{ 

    public static void main(String args[]) { 
     Scanner keyboard = new Scanner(System.in); 

     System.out.println("Welcome to Memory Game"); 

     int board_side;  

     do { 
      System.out.println("\n For 2x2 board game press 2"+ 
       "\n For 4x4 board game press 4"+ 
       "\n For 6x6 board game press 6"); 
      board_side=keyboard.nextInt(); 
     } while(board_side!=2 && board_side!=4 && board_side!=6); 

     char[][] board = createBoard(board_side); 

     shuffleBoard(board); 

     playGame(board); 
    } 




    public static void shuffleBoard(char[][] board) 
    { 
     int N = board.length*board.length; 
     char[] board1D = new char[N]; 

     // Copy the elements of 2D array into that 1D array here 

    } 

    public static char[][] createBoard(int side) 
    { 
     char[][] tmp = new char[side][side]; 
     int letter_count=0; 

     for (int row = 0; row < tmp.length/2; row++) { 
      for(int col = 0; col < tmp[row].length; col++) { 
       tmp[row][col]=(char)('A'+letter_count); 
       tmp[row+tmp.length/2 ][col]=tmp[row][col]; 
       letter_count++; 
      } 
     } 
     return tmp; 
    } 
} 

ответ

0

Предполагая, что его N * N матрицу, вы могли бы сделать что-то вроде:

int N = board.length*board.length; 
char[] board1D = new char[N]; 

int k = 0; 
for (int i =0; i<board.length; i++) { 
    for (int j =0; j<board.length; j++) { 
     board1D[k++] = board[i][j]; 
    } 
} 
0

, если у вас есть m строки и n столбцы, то вам нужно массив 1-D с m*n пробелами.

Вот пример кода:

int k = 0; // counter 
int max_size = m*n; // maximum 1-D array size possible 

for(i = 0; i<m; i++) { // adjust your m and n values 
    for(j = 0; j<n; j++) { 
     if(k > max_size){ 
      // You need to consider what happens here - I simply put it as a stub 
      throw new IndexOutOfBoundsException("Index " + k + " is out of bounds!"); 
     } 
     target_matrix[k++] = source_matrix[i][j]; 
     } 
} 

Это при условии, что ваше предпочтение индексации слева направо, т.е. каждый столбец первой.

Помните, что мой оператор if внутри цикла вложенных циклов учитывал такие проблемы, как исключение outofbounds. Я хотел убедиться, что вы заметили вероятность исключения OutOfBounds. Пожалуйста, удалите if block, если вы не чувствуете, что вам когда-либо понадобится.

0

Да, у вас есть код, но вам нужен только небольшой кусок кода, чтобы понять ответ. Я только перейду к тому, как вы скопируете 2 массивных массивов в один размерный массив. Неисцеденный код и синтаксические ошибки могут изобиловать.

// Presume TwoDArray contains [10][10] elements. 
// Presume OneDArray contains [100] elements. 

for (column = 0; column < 10; ++column) { 
    for (row = 0; row < 10; ++row) { 
     OneDArray[column*10 + row] = TwoDArray[column][row]; 
    } 
} 

седловины * 10 + строки (IE столбцы раз размер строки плюс строка) является волшебной формулой, которая преобразует из 2D массива в массив 1D и на самом деле, как 2D-массив, как правило, хранящийся в памяти все равно , как правило. (Возможно, вы захотите дважды проверить, так как это могут быть строки сначала, а затем столбцы, я видел, как это делалось по-другому на разных языках на разных платформах).

0

проверка Привет, что я до сих пор, я на втором методе http://pastebin.com/XDsp6ze7

// Family name, Given name: 
// Student number: 
// Course: IT1 1120 
// Assignment: 4 


import java.util.Scanner; 
import java.io.IOException; 

public class A4_8044047{ 

    // main method. DO NOT MODIFY 
public static void main(String args[]) { 
    Scanner keyboard = new Scanner(System.in); 

    System.out.println("Welcome to Memory Game"); 

    int board_side; 

    //this loop obtains the board size, or more specifically 
    // the length of the side of the board 
    do{ 
    System.out.println("\n For 2x2 board game press 2"+ 
    "\n For 4x4 board game press 4"+ 
    "\n For 6x6 board game press 6"); 
    board_side=keyboard.nextInt(); 
    }while(board_side!=2 && board_side!=4 && board_side!=6); 

    char[][] board = createBoard(board_side); 

    // a call the the shuffle method 
    shuffleBoard(board); 

    // a call to the game playing method 
    //playGame(board); 

} 




// The following method should shuffle the input 2D array caled board 
public static void shuffleBoard(char[][] board) 
{ 
    // This creates a 1D array whose size is equal to the size of the board 
    int N = board.length*board.length; 
    char[] board1D = new char[N]; 

    // Copy the elements of 2D array into that 1D array here 
    int a = 0; 
    for (int b=0;b<board.length;b++) 
    { 
    for (int c=0;c<board.length;c++) 
    { 
     board1D[a] = board[b][c]; 
     a++; 
    } 
    } 

    // Shuffle 1D array here 
    for (int d=0;d<board1D.length;d++) 
    { 
    int index=(int)(Math.random()* board1D.length); 
    char temp=board1D[d]; 
    board1D[d]=board1D[index]; 
    board1D[index]=temp; 
    } 
    for(int row2=0;row2<board1D.length;row2++) 
    { 
    //System.out.print(board1D[row2] + " "); 
    } 

    //Copy shuffled 1D array back into 2D array, i.e., back to the board 
    int M; 
    if (N==4) 
    { 
    M=2; 
    } 
    else if (N==16) 
    { 
    M=4; 
    } 
    else 
    { 
    M=6; 
    } 
    int count=0; 
    for (int h=0;h<M;h++) 
    { 
    for (int k=0;k<M;k++) 
    { 
     if (count==board1D.length) 
     { 
     break; 
     } 
     board[h][k]=board1D[count]; 
     count++; 
    } 
    } 

    /*for(int row2=0;row2<M;row2++) 
    { 
    for(int col2=0;col2<M;col2++) 
    { 
     System.out.print(board[row2][col2]+ " "); 
    } 
    System.out.println(); 
    }*/ 
} 



// a game playing method 
public static void playGame(char[][] board) 
{ 
    Scanner keyboard = new Scanner(System.in); 

    // this createst a 2D array indicating what locations are paired, i.e., discovered 
    // at the begining none are, so default initializaiton to false is ok 
    boolean[][]discovered=new boolean[board.length][board[0].length];; 


    // the code for your game playing goes here 

    Still working on this part any help would be nice email: [email protected] 






} 


    // createBoard method. DO NOT MODIFY! 
/* this method, createBoard, creates the board filled with letters of alphabet, 
    where each letter appears exactly 2 times 
    e.g., for 4 x 4, the returned board would look like: 
    A B C D 
    E F G H 
    A B C D 
    E F G H */  
public static char[][] createBoard(int side) 
{ 
    char[][] tmp = new char[side][side]; 
    int letter_count=0; 
    for (int row = 0; row < tmp.length/2; row++){ 
    for(int col = 0; col < tmp[row].length; col++) 
    { 
    tmp[row][col]=(char)('A'+letter_count); 
    tmp[row+tmp.length/2 ][col]=tmp[row][col]; 
    letter_count++; 
    } 
    } 
    return tmp; 
} 


    // waitForPlayer method. Do not modify! 
public static void waitForPlayer() 
{ 
    System.out.print("Press enter to continue"); 
    try { 
    System.in.read(); 
    } 
    catch (IOException e){ 
    System.out.println("Error reading from user"); 
    } 
} 

} 
+0

Хотя эта ссылка может ответить на этот вопрос, то лучше включить основные части ответа здесь и обеспечить ссылка для справки. Ответные ссылки могут стать недействительными, если связанная страница изменится. – Sasa

Смежные вопросы