2017年4月29日土曜日

開発環境

行列プログラマー(Philip N. Klein (著)、 松田 晃一 (翻訳)、 弓林 司 (翻訳)、 脇本 佑紀 (翻訳)、 中田 洋 (翻訳)、 齋藤 大吾 (翻訳)、オライリージャパン)の2章(ベクトル)、2.14(問題)、GF(2)上の線形方程式の解を求める、問題 2.14.6 を JavaScript で取り組んでみる。

問題 2.14.6

voting_record_dump109.txt

コード(Emacs)

HTML5

<pre id="output0"></pre>
<button id="run0">run</button>
<button id="clear0">clear</button>

<script src="sample14_6.js"></script>

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    p = (x) => pre0.textContent += x + '\n';

let gf2mul = (u, v) => {
    let mul = (x, y) => x === 0 || y === 0 ? 0 : 1;
    return u.map((x, i) => mul(x, v[i]));
};
let gf2add = (u, v) => {
    let add = (x, y) => x === y ? 1 : 0;
    return u.map((x, i) => add(x, v[i]));
};

let arrayIsEqual = (u, v) =>
    u.map((x, i) => x === v[i])
    .every((x) => x);

let dot = (u, v) =>
    gf2mul(u, v).reduce((x, y) => x + y);

let UnitTest = () => {
    let that = {},
        run = () => {            
            Object.keys(that).forEach((key) => {
                that.setUp();
                if (/^test/.test(key)) {
                    if (that[key]()) {
                        p(`${key} - ok`);
                    } else {
                        p(`${key} - failure`);
                    }
                }
                that.tearDown();
            });        
        },
        assertEqual = (x, y) => x === y;

    that.run = run;
    that.assertEqual = assertEqual;

    return that;
};

let Test = () => {
    let that = UnitTest(),
        
        a, b, c, x1, x2;

    that.setUp = () => {
        a = [1, 1, 0, 0]
        b = [1, 0, 1, 0]
        c = [1, 1, 1, 1]
        x1 = [1, 0, 0, 0]
        x2 = gf2add(x1, [1, 1, 1, 1])
    };
    that.tearDown = () => {};
    that.test_x1a = () => that.assertEqual(dot(a, x1), 1);
    that.test_x1b = () => that.assertEqual(dot(b, x1), 1);
    that.test_x1c = () => that.assertEqual(dot(c, x1), 1);
    that.test_x2a = () => that.assertEqual(dot(a, x2), 1);
    that.test_x2b = () => that.assertEqual(dot(b, x2), 1);
    that.test_x2c = () => that.assertEqual(dot(c, x2), 1);

    return that;
};

let output = () => {
    Test().run();
};

btn0.onclick = output;
btn1.onclick = () => pre0.textContent = '';

output();













						

0 コメント:

コメントを投稿

Comments on Google+: