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?

.sort()でハマらない方法:Set×BigIntは比較関数必須!

Posted at

PaizaのSet問題で、数値が昇順にならないバグに直面しました。原因は .sort() の仕様と BigInt の特性にあった!


🧪 問題の概要

2つの数列A, B与えられ、それぞれの値を重複なく昇順で出力せよ。


入力例:

3
1 2 3
3 4 5

出力例:

1 2 3 4 5


💥 NGコード:文字列としてソートされる罠

const arrA = lines[1].split(' ');
const arrB = lines[2].split(' ');
const seen = new Set([...arrA, ...arrB]);
console.log([...seen].sort().join(' '));

→ 出力が 10 2 3 みたいに崩壊。

なぜ?→ .sort() のデフォルトは文字列ソートだから。


✅ OKコード:BigInt+比較関数

const arrA = lines[1].split(' ').map(BigInt);
const arrB = lines[2].split(' ').map(BigInt);
const seen = new Set([...arrA, ...arrB]);

const sorted = [...seen].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
console.log(sorted.join(' '));

✔ 解説

BigInt型で巨大な数にも対応

.sort() に比較関数が必須(デフォは文字列比較)

a - b はNG → BigInt - BigInt = BigInt なので戻り値が 、
  Number じゃなくて型エラー


📌 技術メモ

  • new Set([...]) は重複除去に便利
  • .sort() は数値比較を明示しないとバグる
  • BigInt 使うなら map(BigInt) + 比較関数必須



僕の失敗談と解決話!

0
0
1

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?