## 2016年11月2日水曜日

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

コード(Emacs)

HTML5

```<div id="graph0"></div>
<label for="row0">段数: </label>
<input id="row0" type="number" min="0" step="1" value="50">
<label for="m0">除数: </label>
<input id="m0" type="number" min="1" step="1" max="12" value="5">
<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="sample9.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;

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

for (let i = start; i <= end; i += step) {
result.push(i);
}
return result;
};
let memo = [];
let fact = (n) => {
if (memo[n]) {
return memo[n];
}
let result = 1;
for (let i = 2; i <= n; i += 1) {
result *= i;
}
memo[n] = Math.round(result);
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 pas_mod = (n, m) => iota(0, n).map((x) => row_mod(x, m));
let dis_1 = (k, n, i) =>  [i,
pas_mod(k, n)
.reduce((x, y) => x.concat(y))
.filter((x) => x == i)
.length];
let bc_dis = (k, n) => {
return iota(0, n - 1).map((x) => dis_1(k, n, x));
};
let getColors = (n, m) => {
let y = bc_dis(n, m);
let diff = 255 / y.length;

y.sort((a, b) => a[1] - b[1]);
let colors = {};
y.forEach((d, i) => {
colors[d[0]] = `rgb(\${i * diff}, \${i * diff}, \${i * diff})`;
});
return colors;
};
let draw = () => {
let n = parseInt(input_row.value, 10) - 1,
m = parseInt(input_m.value, 10),
r = parseInt(input_r.value, 10),
colors = getColors(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();
}
```