0

不明白如何解决这个问题。我需要接受座位号作为参数(座位)。然后将该座位号转换为二维数组的行列索引。

为了检查自己,我一直假设有 10 排 (0-9) 和 2 个席位每排 (0-1),并从中选择 1-20 个座位来检查数学。但是可以有任意数量的行和列。这正是我用来检查自己的。

static void isAvailable(int seat, boolean seat[][]) {

    int row = 0;
    int column = 0;

    if (seat > 0 && seat <= (getRows() * getSeatsPerRow())){
        row = (seat ) % getRows();
        column = (seat - 1) % getSeatsPerRow;
        seat[row][column] = false;
    }
}

假设座位是这样安排的:

            seatsPerRow
       0   1   2   3   4   5   6 

    0 (1) (2) (3) (4) (5) (6) (7)

 r  1 (8) (9) (10)(11)(12)(13)(14)

 o  2 (15)(16)(17)(18)(19)(20)(21)

 w  3  ...

 s  4  ...

    .

    .

    .

假设我想找到 11 号座位。它将是座位 [1][3]。我不明白如何将座位号转换为二维数组上的位置。

4

3 回答 3

1

The modulus operator will be invaluable here, since it can determine which seat we'll want to wind up using.

First, let's take in our assumptions and convert them to something more abstract:

  • There are N seats, where N = 20. We take N to be our rows.
  • There are K rows, where K = 2. We take K to be our columns.
  • Given this, there are N/K seats per row.

Now, we can use some modulus mathematics to work the rest of the problem out. Let's declare our array of seats now.

boolean[][] seats = new boolean[N][K]; //presumed

If we want to claim seat 13, then we need to figure two things out:

  • What row is the seat in?
  • What column is the seat in?

Given the above, the math for the row is as follows:

int row = (seatWanted % N)-1; // (13 % 10)-1 = 2.

Now, the column is similarly easy to find - we would use integer division instead of modulus, though.

int column = seatWanted / K; // 13 / 10 = 1.

The rest is an exercise to the reader, but we would want to mark seats[2][1] as taken.

于 2013-02-13T05:30:14.700 回答
1

假设座位安排是这样的:

 1  2
 3  4
 5  6
 7  8
 9 10
11 12
13 14
15 16
17 18
19 20



int col = (seat % 2 == 0)? 1:0;
int row = (int)Math.ceil(seat / 2.0f); 
于 2013-02-13T05:23:48.240 回答
1

好吧,假设座位从 1 开始编号,您可以简单地使用以下方法获取列索引:

int column = (seatNum - 1) % seat[0].length;

然后,您可以使用简单的表达式找到该行:

int row = (int) ((seatNum - 1) / seat[0].length);

然后,您将通过执行以下操作获得实际元素:

seats[row][column]

这两个表达式都适用于数组的所有维度seat(0 x 0 除外)。

第一行将使用模数来找到 的余数seatNum / seat[0].length或者基本上是座位数除以每排座位数。这将重建column到正确的范围。

接下来,第二行将座位数除以一排的长度,这将找到该排本身。然后我们将它转​​换为一个带有 的 int (int),它会截断它,删除可能由操作产生的任何小数。在这种情况下,我们实际上是在执行纯整数数学运算,因此不需要强制转换。

于 2013-02-13T05:27:05.300 回答