LoginSignup
1
0

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 ソートメニュー応用編 JavaScript ペアソート

Last updated at Posted at 2022-09-13

ペアソート (paizaランク C 相当)

解答コード例(優先度が低い方からソートする)

2列目の方が優先度が低いので、先にソートします。
1列目の方が優先度が高いので、後にソートします。

JavaScript
const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");
//数値 n
const [n] = lines[0].split(" ").map(Number);
// n 行 2 列の表 a 
const a = lines.slice(1).map(line => line.split(" ").map(Number));

//2 列目の数値に基づいて昇順でソート
a.sort((a, b) => a[1] - b[1]);
//1 列目の数値に基づいて昇順でソート
a.sort((a, b) => a[0] - b[0]);

//ソートした表を各列は半角スペース区切りで、各行は改行区切りで出力
console.log(a.map(row => row.join(" ")).join("\n"));

解答コード例(比較関数自作)

比較関数(sortの中身)を自分で作ります。ifは先の方が優先度が高くなります。

JavaScript
const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");
//数値 n
const [n] = lines[0].split(" ").map(Number);
// n 行 2 列の表 a 
const a = lines.slice(1).map(line => line.split(" ").map(Number));

a.sort((a, b) => {
    //a を行単位で、 1 列目の数値に基づいて昇順でソート    
    if (a[0] !== b[0]) {
        return a[0] - b[0];
    //1 列目の数値が等しい 2 つの行に関しては 2 列目の数値に基づいて昇順でソート
    } else {
        return a[1] - b[1];
    }
});

//ソートした表を各列は半角スペース区切りで、各行は改行区切りで出力
console.log(a.map(row => row.join(" ")).join("\n"));
1
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
1
0