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?

「ひとりすごろく」を解くために : part1

Posted at

今回は paiza の「「ひとりすごろく」を解くために : part1」の問題に挑戦!


📘 問題概要

  • 6 面ある特殊なサイコロが 1 つある
  • 各面には 位置ID と 数字(1〜6) が対応している
    • 面の ID は次の 6 つ
      • T(上), B(下)
      • U(前), D(後)
      • L(左), R(右)
  • 入力では
    • 1 行目に T B U D L R の順で、それぞれの面に書かれた数字が与えられる
    • 2 行目に整数 Q が与えられる
  • 求めるのは
    • 数字 Q が書かれている面の「裏側(反対側)」の面に書かれた数字
  • 裏表の関係はあらかじめ決まっている
    • TB
    • UD
    • LR
  • 出力は
    • 裏の面に書かれている数字を 1 行で出力



入力例:

2 4 1 3 6 5
5

出力例:

6






✅OK例:愚直な実装

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

const lines = [];

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

rl.on('close', () => {
    const [T, B, U, D, L, R] = lines[0].split(' ').map(Number);
    const Q = Number(lines[1]);
    
    if (T === Q) console.log(B);
    if (B === Q) console.log(T);
    if (U === Q) console.log(D);
    if (D === Q) console.log(U);
    if (L === Q) console.log(R);
    if (R === Q) console.log(L);
});




✨OK例:

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

const lines = [];

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

rl.on('close', () => {
    // サイコロの各面の数字 [T, B, U, D, L, R]
    const num = lines[0].split(' ').map(Number);
    // 探したい数字 Q
    const Q = Number(lines[1]);

    // Q があるインデックスを探す
    const idx = num.indexOf(Q);

    // 偶数 index → 裏は idx + 1
    // 奇数 index → 裏は idx - 1
    if (idx % 2 === 0) {
        console.log(num[idx + 1]);
    } else {
        console.log(num[idx - 1]);
    }
});

🔑 対応関係のポイント

  • 配列の並び
    [T, B, U, D, L, R]
  • 0-indexed なので
    • 01TB
    • 23UD
    • 45LR
  • よって
    index が偶数 → +1、奇数 → -1






📝まとめ

  • 与えられた数字が、どの面ペアに属しているかを判定する
  • 入力順 [T, B, U, D, L, R] を配列にすると
    • (0,1), (2,3), (4,5) が裏表のペアになる
  • そのため
    • 数字 Q の 配列内インデックス を探す
    • インデックスが
      • 偶数 → +1
      • 奇数 → -1
  • 条件分岐を大量に書かなくても、
    配列 + インデックスの性質 だけでシンプルに解ける
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?