2017年1月25日水曜日

開発環境

色々と他の数でも気軽に試せるように、JavaScript て実装してみた。

f(, ) =
f(, f(, )) =

コード(Emacs)

HTML5

f(<input id="n0" type="number" min="0" step="1" value="10">,
<input id="m0" type="number" min="0" step="1" value="2">) =
<span id="answer0"></span>
<br>
f(<input id="x1" type="number" min="0" step="1" value="5">,
f(<input id="n1" type="number" min="0" step="1" value="2">,
<input id="m1" type="number" min="0" step="1" value="2">)) =
<span id="answer1"></span>
<div id="output0"></div>
<script src="sample1.js"></script>

JavaScript

let input_n0 = document.querySelector('#n0'),
    input_m0 = document.querySelector('#m0'),
    input_x = document.querySelector('#x1'),
    input_n1 = document.querySelector('#n1'),
    input_m1 = document.querySelector('#m1'),
    inputs = [input_n0, input_m0, input_x, input_n1, input_m1],
    div_output0 = document.querySelector('#output0');

let f = (n, m) => {
    if (n === 0) {
        return 1;
    }
    return m * f(n - 1, m);
};
let output = (n, m) => {
    if (n === 0) {
        return '1';
    }
    return `${m} x (${output(n - 1, m)})`;
}

let answer = () => {
    let n0 = parseInt(input_n0.value, 10),
        m0 = parseInt(input_m0.value, 10),
        x = parseInt(input_x.value, 10),
        n1 = parseInt(input_n1.value, 10),
        m1 = parseInt(input_m1.value, 10),
        answer0 = document.querySelector('#answer0'),
        answer1 = document.querySelector('#answer1');
    

    answer0.innerText = f(n0, m0);
    answer1.innerText = f(x, f(n1, m1));
    div_output0.innerHTML =
        `${output(n0, m0)} = ${f(n0, m0)}<br>` +
        `${output(n1, m1)} = ${f(n1, m1)}<br>` +
        `${output(x, f(n1, m1))} = ${f(x, f(n1, m1))}`;
};

inputs.forEach((input) => input.onchange = answer);

answer();

0 コメント:

コメントを投稿