Conversation
| println!("zip(s.chars()); (row_index,c) -> ({},{})", row_index, c) | ||
| }) | ||
| .collect::<Vec<_>>(); | ||
| zigzags.sort_by_key(|(row_index, _)| *row_index); |
There was a problem hiding this comment.
https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort_by_key
This sort is stable
を利用していますね。
この解法きれいですね。
|
|
||
| let mut rows = vec![String::new(); num_rows]; | ||
| let mut i = 0; | ||
| let mut is_down_direction = true; |
There was a problem hiding this comment.
英語としてこなれた命名としては is_downward, is_descending, is_going_down あたりが思いつきました。現状でも意図は通じるので問題ありません。
| - rowをi32として扱えば少し良くなりそう。 | ||
|
|
||
| 所感 | ||
| - step1.rsと比べて少し行数は増えたものの読み手の認知負荷が下がったように感じる。 |
| let mut zigzags = (0..num_rows) | ||
| .chain((1..num_rows - 1).rev()) | ||
| .cycle() | ||
| .zip(s.chars()) | ||
| // 複数のイテレータを連結しているコードのデバッグ手法の例として意図的にinspect()のコードを残しています | ||
| .inspect(|(row_index, c)| { | ||
| println!("zip(s.chars()); (row_index,c) -> ({},{})", row_index, c) | ||
| }) | ||
| .collect::<Vec<_>>(); |
There was a problem hiding this comment.
メソッドチェーンでまとめて書けると美しい一方で、Rustに不慣れな私としてはインデックス作成を分けていただけると読みやすかったです。
| let mut zigzags = (0..num_rows) | |
| .chain((1..num_rows - 1).rev()) | |
| .cycle() | |
| .zip(s.chars()) | |
| // 複数のイテレータを連結しているコードのデバッグ手法の例として意図的にinspect()のコードを残しています | |
| .inspect(|(row_index, c)| { | |
| println!("zip(s.chars()); (row_index,c) -> ({},{})", row_index, c) | |
| }) | |
| .collect::<Vec<_>>(); | |
| // Zig-zag order indices. e.g. [0,1,2,1,0,1, ...] for num_rows = 3 | |
| let row_indices = (0..num_rows) | |
| .chain((1..num_rows - 1).rev()) | |
| .cycle(); | |
| let mut zigzags: Vec<(i32, char)> = row_indices | |
| .zip(s.chars()) | |
| .collect(); |
| if num_rows == 0 { | ||
| return "".to_string(); | ||
| } |
There was a problem hiding this comment.
本筋ではありませんが、ユーザーがうっかり0を渡して(失敗せずに)空文字が返ってくると困るケースがありそうです。誤ったパラメータを渡していることを気づかせてあげるほうが親切に思いました。
There was a problem hiding this comment.
確かにnum_rowsは 1 <= num_rows <= 1000 となっているので、誤ったパラメーター0を渡してきていることを知らせるという観点は良いなと思いました。
Leet Codeの採点システムを通らなくなってしまいますが、型で表すことも可能なのでそもそも符号付き32ビット整数i32ではなく、非ゼロの32ビット整数NonZeroU32などを活用できるなと思いました。
pub fn convert(s: String, num_rows: NonZeroU32) -> String|
|
||
| for c in s.chars() { | ||
| rows[row].push(c); | ||
| row = ((row as i32) + direction) as usize; |
There was a problem hiding this comment.
row を s のインデックスから計算式で求める方法もあります。興味があれば探してみてください。
ただ、ぱっと見で理解しやすい計算式ではないため、もし書いたとしても、コメントで内容を説明したほうが良いと思います。
問題: 6. Zigzag Conversion
次にやること: コーディング練習会に参加した感想を書く
ファイルの構成:
./src/bin/<各ステップ>.rs