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?

「値の計算」を解くために:part4

Posted at

今回は paiza の「「値の計算」を解くために:part4」の問題に挑戦!


問題概要

テーマ: 抵抗回路の合成抵抗を求める(今回は 並列のみ)。

入力:

  • N:抵抗の種類数
  • s_i w_i:抵抗名とその抵抗値(N行分)
  • M:抵抗列の数(今回は必ず1)
  • t_1:並列接続を表す文字列(例: "ABB" → AとBとBが並列)

計算ルール:

  • 並列接続の場合、抵抗値は次で求める: 1 / (1 / A + 1 / B)
  • 計算過程では小数を使うが、出力は 切り捨て整数。

出力:

  • 並列合成抵抗(小数切り捨て)

※ 空白区切りの場合は直列、区切りがない場合は並列でつながれていることを表す。



入力例:

2
A 100
B 200
1
ABB

出力例:

50






✅OK例:

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

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

rl.on('close', () => {
    // --- 1. 入力の取得 ---
    const N = Number(lines[0]);   // 抵抗の種類数
    
    // 抵抗名と抵抗値を Map に格納
    const sw = new Map(lines.slice(1, N+1).map(line => {
        const [s, w] = line.split(' ');
        return ([s, Number(w)]);
    }));
    
    const M = Number(lines[N+1]);     // 抵抗列の個数(必ず1)
    const t = lines[N+2].split('');   // 並列のつなぎ方(例: "ABB" → ["A","B","B"])

    // --- 2. 並列合成の計算 ---
    // 逆数の和を作り、それを逆数に戻す
    const ans = Math.floor(1 / t.reduce((acc, cur) => acc + 1 / sw.get(cur), 0));

    // --- 3. 出力 ---
    console.log(ans);
});

  • t.reduce((acc, cur) => acc + 1 / sw.get(cur), 0)
    → すべての抵抗値の逆数を合計。

  • 1 / その合計
    → 最後に逆数を取って合成抵抗を算出。

  • Math.floor()
    → 小数点以下を切り捨て。






📝まとめ


  • 直列:単純に足すだけ。
    • 空白区切りの場合は直列
    • 直列 A + B

  • 並列:逆数を扱う。
    • 区切りがない場合は並列
    • 並列 1 / (1 / A + 1 / B)




僕の失敗談(´;ω;`)と解決法🐈

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?