使用二维数组实现影院座位布局的填充问题求助
Fixing Your Cinema Seat Layout Code
Hey there! Let's sort out that issue with your cinema seat layout. I see what's going on here—right now, you're stuffing two seats into a single 2D array element (like setting arr1[0,1] to "o o"), which is why you can't get that continuous, full-row layout like "OOOXOOXO". Each position in your array should represent one individual seat, not a pair of seats.
Here's a corrected approach:
- Treat each
arr[row, col]as a single seat (either"O"for open or"X"for closed). - Initialize all seats to open first (way more efficient than setting each open seat manually), then mark the closed ones.
- Build and print each row by concatenating all the seats in that row to get a continuous string.
Example Code:
// Create a 10x10 2D array where each element is a single seat string[,] cinemaSeats = new string[10, 10]; // First, set every seat to open ("O") for (int row = 0; row < cinemaSeats.GetLength(0); row++) { for (int col = 0; col < cinemaSeats.GetLength(1); col++) { cinemaSeats[row, col] = "O"; } } // Mark closed seats ("X") based on your original setup // Note: I adjusted indices to match single-seat logic—your original arr1[2,1] first character was "x", so that's row 2, column 0 here cinemaSeats[2, 0] = "X"; cinemaSeats[4, 0] = "X"; // Add more closed seats as needed, e.g.: // cinemaSeats[0, 3] = "X"; // Closes the 4th seat in the first row // Print the full cinema layout for (int row = 0; row < cinemaSeats.GetLength(0); row++) { string currentRow = ""; // Concatenate all seats in the row to make a continuous string for (int col = 0; col < cinemaSeats.GetLength(1); col++) { currentRow += cinemaSeats[row, col]; } Console.WriteLine($"Row {row + 1}: {currentRow}"); }
What this does:
- Each array index maps to one seat, so you have full control over every individual spot.
- The nested loops initialize all seats to open in one go, saving you from repetitive code.
- When printing, we build each row into a single string, giving you that clean, continuous layout you want (like
"OXOOOOOOOO"for row 3).
Next steps for your features:
- Add a
CheckSeatAvailability(int row, int col)method that returnstrueif the seat is"O". - Implement a
ReserveSeat(int row, int col)method that sets the seat to"X"only if it's available. - Add seat numbering (e.g., row numbers and column letters) to make the layout more user-friendly.
内容的提问来源于stack exchange,提问作者Jace Yatrakos
相关产品推荐
相关产品推荐

