今回はpaizaの「ソートと検索」の問題に挑戦!
過去に、indexOfは一回使ったことある気がする…?
問題概要
- クラスの人数
- 元々 N 人
- paiza 君本人(身長 P)を入れて N + 1 人
- さらに転校生(身長 X)が来て N + 2 人
- その全員を 背の順(昇順) に並べる
- 並べたとき、paiza 君の位置(前から何番目) を求める
入力例:
3 188 174 // N X P
181
177
113
出力例:
2
✅ OK例:
const rl = require('readline').createInterface({ input: process.stdin });
const lines = [];
rl.on('line', (input) => lines.push(input));
rl.on('close', () => {
const [N, X, P] = lines[0].split(' ').map(Number);
const heights = lines.slice(1).map(Number);
heights.push(X, P);
const sortedHeights = heights.sort((a,b) => a - b);
for(let i = 0; i < sortedHeights.length; i++){
if(sortedHeights[i] === P){
console.log(i + 1)
}
}
});
✅ OK例:indexOf()
const sortedHeights = heights.sort((a,b) => a - b);
const position = sortedHeights.indexOf(P) + 1;
console.log(position);
💡 indexOf とは
配列(や文字列)で 「指定した値が最初に現れる位置(インデックス)」 を返すメソッド。
見つからない場合は -1 を返す。
✅ 基本構文
array.indexOf(searchElement [, fromIndex])
-
searchElement: 探したい要素。 -
fromIndex: 探し始める位置(省略すると0から)。
✅ 例:配列で使う
const arr = [10, 20, 30, 20];
console.log(arr.indexOf(20)); // 1 ← 最初の 20
console.log(arr.indexOf(20, 2)); // 3 ← index 2 以降で探す
console.log(arr.indexOf(40)); // -1 ← 見つからない
✅ 例:文字列で使う
文字列にも indexOf は使える!
const str = "hello world";
console.log(str.indexOf("o")); // 4
console.log(str.indexOf("l")); // 2
console.log(str.indexOf("z")); // -1
✅ よくある使い方
- 含まれているかどうかの判定
if (arr.indexOf(value) !== -1) {
// 含まれている
}
→ 最近は includes が便利!
if (arr.includes(value)) {
// 同じ意味
}
- 位置を使って何かを取り出す
const idx = arr.indexOf(30);
if (idx !== -1) {
console.log(arr[idx]); // 30
}
🔍 lastIndexOf との違い
-
indexOf→ 最初に見つかった位置 -
lastIndexOf→ 最後に見つかった位置
const arr = [1, 2, 3, 2, 1];
console.log(arr.indexOf(2)); // 1
console.log(arr.lastIndexOf(2)); // 3
🗒️ まとめ
| 特徴 | 説明 |
|---|---|
| 最初に一致した位置だけ | 複数一致しても、最初の位置だけ返す |
| 部分一致 | 文字列なら部分文字列を探す |
| 見つからないと -1 | -1 は見つからなかったサイン |
| 厳密比較 | === と同じく厳密比較(型が違うと一致しない) |