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?

fs.readFileSync() + Math.max() 標準入力と最大値の求め方を学んだ!

Posted at

高2の僕、Paizaの「最大値を求めよ」という問題で、なぜかsort()を使って遠回り(´;ω;`) 調べたらMath.max()で一発だったし、fs.readFileSync()を使えば競プロ向きのやり方を知ったから使ってみた!

NG①:sort()で最大値?無駄に遠回り

const lines = [...標準入力...];  
const sorted = lines.slice(1).map(Number).sort((a, b) => b - a);  
console.log(sorted[0]);  

・比較のコストが無駄(最大値だけ知りたいのに全体を並べ替えてる)。
・sort()はデフォルトだと文字列比較なので、意図しない並びになることも。

何でこうなったか… まずは、調べずに今知っている知識で頑張ってみようと頭をひねった結果、最近.sortで並び替えをできると学んだからこれで一番大きい数字を配列の一番初めに入れて出力すればいいじゃん!ってなったから(/ω\)

↓readlineで1行ずつ読むのは遅い

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

const lines = [];
rl.on('line', (line) => lines.push(line));
rl.on('close', () => {
    console.log(Math.max(...lines.slice(1).map(Number)));
});

・非同期処理で1行ずつ読み込むため、行数が増えると遅くなる。
・競技プログラミングではこの方法は非推奨らしい。

OK:fs.readFileSync() + Math.max()で最適化!

const fs = require("fs");

const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");
console.log(Math.max(...lines.slice(1).map(Number)));

・同期処理なので一発で入力を読み取れる。
・.split("\n") で即配列化、map(Number) で型変換もスッキリ。
・Math.max(...配列) で最大値を瞬時に取得(sort()いらない!)。

結論:競プロならfs.readFileSync() + Math.max()一択!

僕の失敗談と解決話

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?