Arrays and for Loops

우리는 배열을 아래와 같이 선언 할 수 있음을 보았습니다:

We saw that an array can be declared like this:

#![allow(unused)] fn main() { let array = [10, 20, 30]; }

배열은 {:?} 형태로 표시하여 출력할 수 있습니다.

You can print such an array by asking for its debug representation with {:?}:

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

러스트에서는 for키워드를 사용해 배열이나 범위를 반복할 수 있습니다:

Rust lets you iterate over things like arrays and ranges using the for keyword:

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

위의 예제에서 행렬을 예쁘게 출력하는 pretty_print함수와 행렬을 전치(행과 열을 변경)시키는 transpose함수를 작성해 보시기 바랍니다.

Use the above to write a function pretty_print which pretty-print a matrix and a function transpose which will transpose a matrix (turn rows into columns):

2584567⎤8⎥9⎦transpose==1473⎤6⎥9⎦123

두 함수 모두 3×3 행렬에서 작동하도록 하드 코딩합니다.

Hard-code both functions to operate on 3 × 3 matrices.

아래 코드를 https://play.rust-lang.org/에 복사해서 구현하시면 됩니다.

Copy the code below to https://play.rust-lang.org/ and implement the functions:

// TODO: 구현이 완료되면 아래 줄은 삭제합니다. // TODO: remove this when you're done with your implementation. #![allow(unused_variables, dead_code)] fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] { unimplemented!() } fn pretty_print(matrix: &[[i32; 3]; 3]) { unimplemented!() } fn main() { let matrix = [ [101, 102, 103], // <-- the comment makes rustfmt add a newline [201, 202, 203], [301, 302, 303], ]; println!("matrix:"); pretty_print(&matrix); let transposed = transpose(matrix); println!("transposed:"); pretty_print(&transposed); }

Bonus Question

하드코딩된 3×3 행렬 입력을 &[i32] 슬라이스를 통해 인수와 반환값을 정의가 가능한가요?

예컨데 &[&[i32]]는 2차원 슬라이스의 슬라이스 입니다. 가능하다면/하지 않다면 왜 그런가요?

Could you use &[i32] slices instead of hard-coded 3 × 3 matrices for your argument and return types? Something like &[&[i32]] for a two-dimensional slice-of-slices. Why or why not?

프로덕션 품질의 구현에 대해서는 ndarray 크레이트를 참조하시기 바랍니다.

See the ndarray crate for a production quality implementation.


역주

  • C/C++나 js에 대해서 어느정도 지식이 있는걸 전제로 하기때문에 첫 문제부터 난이도가 조금 있지 않을까 싶습니다만..
힌트
  • for를 이용한 출력과 for를 이용해 [i][j] 변환하는 함수입니다.