## 2016年11月1日火曜日

### 数学 - JavaScript - パスカルの三角形と剰余 - パスカルカラーの世界

コード(Emacs)

HTML5

```<div id="graph0"></div>
<label for="row0">段数: </label>
<input id="row0" type="number" min="0" step="1" value="63">
<label for="m0">除数: </label>
<input id="m0" type="number" min="1" step="1" max="12" value="3">
<label for="r0">点の半径: </label>
<input id="r0" type="number" min="1" step="1" value="4">

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.6/d3.min.js" integrity="sha256-5idA201uSwHAROtCops7codXJ0vja+6wbBrZdQ6ETQc=" crossorigin="anonymous"></script>

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

```

JavaScript

```{
let div_graph = document.querySelector('#graph0'),
input_row = document.querySelector('#row0'),
input_m = document.querySelector('#m0'),
input_r = document.querySelector('#r0'),
inputs = [input_row, input_m, input_r],
width = 600,
height = 600,
svg,
colors = ['yellow', 'black', 'orange', 'yelloGreen ', 'green',
'lightBlue', 'purple', 'red', 'brown', 'blue', 'pink',
'white'];

let iota = (start, end, step=1) => {
let result = [];

for (let i = start; i <= end; i += step) {
result.push(i);
}
return result;
};
let fact = (n) => {
let result = 1;
for (let i = 2; i <= n; i += 1) {
result *= i;
}
return result;
};
let bc = (n, r) => {
return Math.round(fact(n) / (fact(r) * fact(n - r)));
};
let row = (n) => {
return iota(0, n).map((x) => bc(n, x));
};
let row_mod = (n, m) => {
return row(n).map((x) => Math.round(x % m));
};
let tri_n = (n) => {
let y = -n;

return iota(y, n, 2).map((x) => [x, y]);
};
let mod_xy = (n, m) => {
let a = tri_n(n),
b = row_mod(n, m),
result = [];

for (let i = 0; i < a.length; i += 1) {
let x = a[i].slice();
x.push(b[i]);
result.push(x);
}
return result;
};
let plot_data = (n, m) => {
return iota(0, n).map((x) => mod_xy(x, m))
.reduce((x, y) => x.concat(y), []);
};
let draw = () => {
let n = parseInt(input_row.value, 10) - 1,
m = parseInt(input_m.value, 10),
r = parseInt(input_r.value, 10),
// dataset = build(n, m),
dataset = plot_data(n, m),
xscale,
yscale;

xscale = d3.scaleLinear()
.domain([-n, n])
yscale = d3.scaleLinear()
.domain([0, -n])

div_graph.innerHTML = '';
svg = d3.select('#graph0')
.append('svg')
.attr('width', width)
.attr('height', height);

svg.selectAll('circle')
.data(dataset)
.enter()
.append('circle')
.attr('cx', (d) => xscale(d[0]))
.attr('cy', (d) => yscale(d[1]))
.attr('r', r)
.attr('fill', (d) => {
return colors[d[2]];
});
};

inputs.forEach((input) => input.onchange = draw);
draw();
}
```