[Project] 좌석 2차원 배열

김호정's avatar
Oct 09, 2024
[Project] 좌석 2차원 배열
 
테스트
@Test public void mFindAllByShowtimeId_test(){ //given Long showtimeId = 8L; // 열과 행의 최댓값 (초기화) int maxCols = 0; int maxRows = 0; //when List<Seat> seats = seatRepository.mFindAllByShowtimeId(showtimeId); System.out.println(seats.size()); // 9 // 좌석 정보에서 최대 열과 행을 찾아야 하므로 먼저 탐색 for(Seat seat : seats){ Character colNum = seat.getColNum(); //System.out.println(colNum); // 2 3 4 5 1 2 3 4 5 Character rowNum = seat.getRowNum(); // A B //System.out.println(rowNum); // colNum이 문자여서 숫자로 변환 int colIndex = Character.getNumericValue(colNum); //System.out.println("colIndex: " + colIndex); // 2 3 4 5 1 2 3 4 5 int rowIndex = rowNum - 'A' + 1; // A = 1, B = 2 // 1 1 1 2 2 2 2 2 //System.out.println("rowIndex: " + rowIndex); // 최대 열과 행을 업데이트 if(colIndex > maxCols){ maxCols = colIndex; } if(rowIndex > maxRows){ maxRows = rowIndex; } } System.out.println(maxCols); // 5 System.out.println(maxRows); // 2 // 계산된 최대 열과 행을 사용하여 배열 생성 Seat[][] seatArray = new Seat[maxRows][maxCols]; // seat[2][5] // 다시 좌석 정보를 배열에 넣는 작업 for(Seat seat : seats){ Character colNum = seat.getColNum(); // 1, 2, 3, 4, 5 Character rowNum = seat.getRowNum(); // A, B int colIndex = Character.getNumericValue(colNum) - 1; // 배열 인덱스는 0부터 시작하므로 -1 int rowIndex = rowNum - 'A'; // 배열 인덱스는 0부터 시작하므로 'A'는 0, 'B'는 1 seatArray[rowIndex][colIndex] = seat; } //eye //System.out.println(seatNumbers); System.out.println("이차원배열 길이 : " + seatArray.length); // 좌석 배열 확인용 출력 for (int i = 0; i < seatArray.length; i++) { for (int j = 0; j < seatArray[i].length; j++) { Seat seat = seatArray[i][j]; if (seat != null) { System.out.print("[" + seat.getRowNum() + seat.getColNum() + "] "); } else { System.out.print("[ ] "); // 중간에 빈 좌석 } } System.out.println(); // 행이 끝나면 줄 바꿈 } // 확인용 출력 System.out.println("Max Columns: " + maxCols); System.out.println("Max Rows: " + maxRows); }
 
SeatRepository
@Query("select s from Seat s join fetch s.showtime st where st.id = :showtimeId") List<Seat> mFindAllByShowtimeId(@Param("showtimeId") Long showtimeId);
 
실행 시키면
 
notion image
 
쿼리가 실행되면서
 
 
notion image
 
2차원 배열 안에 좌석 정보가 담기게 된다.
 
 
아쉬운 점 : 테스트 코드랑 서비스 레이어의 비즈니스 로직 부분에서는 이렇게 2차원 배열을 활용하였는데, ResponseDTO 에 담을 때 이차원 배열로 넘어온 걸 다시
행과 열을 따로 분리시켜서 담았다. ( 왜 그랬을까 ..? )
이차원 배열 형태로 DTO에 담아서 return 한 뒤 자바스크립트 코드를 사용해
그대로 렌더링 했으면 코드가 더 깔끔했을 것 같다.
 
Share article

keepgoing