繁体   English   中英

将2D数组的元素复制到1D数组

[英]Copying elements of a 2D array into a 1D array

我正在尝试将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;
    }
}

假设它的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];
    }
}

如果您有mn列,则需要一维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];
       }
 }

这是假设您的索引首选项是从左到右,即每列第一。

请记住,我在嵌套for循环内的if语句解决了出站异常等问题。 我想确保您注意到OutOfBounds异常的机会。 如果您认为不需要,请删除if block

是的,您那里有代码,但是只需要一小段代码即可了解答案。 我仅讨论如何将2维数组复制到1维数组中。 未经测试的代码和语法错误可能很多。

// 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];
    }
}

col * 10 +行(IE列乘以行大小加行)是一种神奇的公式,它可以将2D数组转换为1D数组,实际上通常是2D数组通常存储在内存中的方式。 (您可能要仔细检查一下,因为它可能先是行然后是列,但我在不同平台上用不同的语言却看到了不同的结果)。

嗨,请检查我到目前为止所做的事情,我正在使用第二种方法http://pastebin.com/XDsp6ze7

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

public class A{

   // 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: silver-saad21@hotmail.com






 }


    // 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");
  }
 }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM