開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- Node.js, Safari(JavaScript エンジン)
- Learning JavaScript [邦訳](参考書籍)
行列プログラマー(Philip N. Klein (著)、 松田 晃一 (翻訳)、 弓林 司 (翻訳)、 脇本 佑紀 (翻訳)、 中田 洋 (翻訳)、 齋藤 大吾 (翻訳)、オライリージャパン)の2章(ベクトル)、2.14(問題)、ベクトルの加法の練習、問題 2.14.1、2.14.2、2.14.3 を JavaScript で取り組んでみる。
課題 2.12.9
コード(Emacs)
HTML5
<pre id="output0"></pre> <button id="run0">run</button> <button id="clear0">clear</button> <script src="sample14_1.js"></script>
JavaScript
let btn0 = document.querySelector('#run0'),
btn1 = document.querySelector('#clear0'),
pre0 = document.querySelector('#output0'),
p = (x) => pre0.textContent += x + '\n';
let Vector = (labels, func={}) => {
let that = {},
d = labels,
f = func,
setItem = (d, val) => {
f[d] = val;
},
getItem = (d) => {
return f[d] === undefined ? 0 : f[d];
},
scalarMul = (a) => {
let func = {};
d.forEach((k) => {
func[k] = f[k] * a;
});
return Vector(d, func);
},
add = (v) => {
let func = {};
d.forEach((k) => {
func[k] = f[k] + v.getItem(k);
});
return Vector(d, func);
},
sub = (v) => that.add(v.scalarMul(-1)),
neg = () => that.scalarMul(-1),
dot = (v) => {
return d.map((i) => that.getItem(i) * v.getItem(i))
.reduce((x, y) => x + y);
},
isEqual = (v) => {
return d.every((x, i) => that.getItem(i) === v.getItem(i));
},
toString = () => {
return '{' +
d.map((k) => `${k}: ${that.getItem(k)}`).join(', ') +
'}';
};
that.d = () => d;
that.f = () => f;
that.getItem = getItem;
that.setItem = setItem;
that.scalarMul = scalarMul;
that.add = add;
that.sub = sub;
that.neg = neg;
that.dot = dot;
that.isEqual = isEqual;
that.toString = toString;
return that;
};
let arrayToVector = (a) => {
let l = [],
f = {};
a.forEach((x, i) => {
l.push(i);
f[i] = x;
});
return Vector(l, f);
};
let gf2mul = (u, v) => {
let mul = (x, y) => x === 0 || y === 0 ? 0 : 'one';
return u.map((x, i) => mul(x, v[i]));
};
let gf2add = (u, v) => {
let add = (x, y) => x === y ? 0 : 'one';
return u.map((x, i) => add(x, v[i]));
};
let arrayIsEqual = (u, v) => {
return u.map((x, i) => x === v[i])
.every((x) => x);
};
let v = arrayToVector([-1, 3]),
u = arrayToVector([0, 4]),
v1 = [0, 'one', 'one'],
u1 = ['one', 'one', 'one'];
let output = () => {
[[v.add(u), arrayToVector([-1, 7])],
[v.sub(u), arrayToVector([-1, -1])]]
.forEach((a) => {
let [left, right] = a;
p(left.isEqual(right));
});
[[gf2add(v1, u1), ['one', 0, 0]],
[gf2mul(v1, u1), [0, 'one', 'one']]]
.forEach((a) => {
let [left, right] = a;
p(arrayIsEqual(left, right));
});
};
btn0.onclick = output;
btn1.onclick = () => pre0.textContent = '';
output();
0 コメント:
コメントを投稿