0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

「決まり字」を解くために : part2

Posted at

今回は paiza の「「決まり字」を解くために : part2」の問題に挑戦!


問題概要

2つの和歌の上の句(文字列)を比べ、
各文字が同じかどうか を順番に調べる問題。


具体的には:

  • 1文字目同士が同じ → 「Yes
  • 違う → 「No
  • これを 短い方の文字数分だけ 繰り返す。


入力例:

2
aaaaaa
aaab

出力例:

Yes
Yes
Yes
No






✅ OK例:

const rl = require('readline').createInterface({ input:process.stdin });

const lines = [];

rl.on('line', (input) => lines.push(input));

rl.on('close', () => {
    const N = Number(lines[0]);   // 和歌の数(今回は 2)
    const s = lines.slice(1);     // 2つの和歌文字列
    const a = s[0];
    const b = s[1];
        
    // 文字数の短い方までループ
    for (let i = 0; i < Math.min(a.length, b.length); i++) {
        if (a[i] === b[i]) {
            console.log('Yes');   // j文字目が同じ
        } else {
            console.log('No');    // j文字目が違う
        }
    }
});

🧩 コードの流れ

  1. readline モジュールを準備
    → 標準入力(process.stdin)からデータを1行ずつ受け取る仕組みを作る。
  2. 入力行を配列に格納
    rl.on('line', …) で読み取った各行を lines 配列に追加。
  3. 入力がすべて終わったら処理開始
    rl.on('close', …) 内で、メインの処理を実行。
  4. 1行目(lines[0])から和歌の数 N を取得
    → この問題では常に 2 が入る。
  5. 残りの2行を取得
    lines.slice(1) で和歌の上の句2つを配列 s にまとめる。
    a = s[0], b = s[1] としてそれぞれ取り出す。
  6. 短い方の文字数までループ
    for (let i = 0; i < Math.min(a.length, b.length); i++)
  7. 各文字を比較
    a[i] === b[i] が真なら "Yes"、違えば "No" を出力。
  8. すべての文字を比較し終えたら終了






🎓 まとめ

  • 文字列のインデックスアクセス
    a[i]b[i] で i文字目を取得できる。
  • 短い方の長さまでループ
    Math.min(a.length, b.length) を使うのが安全。
  • シンプルな比較問題
    if文とループで実現可能。文字列処理の基本。




僕の失敗談(´;ω;`)と解決法🐈

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?