2017年5月25日木曜日

開発環境

Think Perl 6: How to Think Like a Computer Scientist (Laurent Rosenfeld(著)、Allen B. Downey(著)、Oreilly & Associates Inc)の Part 1(Starting with the basics)、Chapter 11(Case Study: Data Structure Selection)の Random Numbers、Exercise: 5.を JavaScript で取り組んでみる。

Exercise: 5.

コード(Emacs)

HTML5

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

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

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    p = (x) => pre0.textContent += x + '\n',
    range = (start, end, step=1) => {
        let result = [];

        for (let i = start; i < end; i += 1) {
            result.push(i);
        }
        return result;
    };

let histogram = (s) => {
    let histo = {};
    s.split('')
        .forEach((letter) => {
            if (histo[letter]) {
                histo[letter] += 1;
            } else {
                histo[letter] = 1;
            }
        });
    return histo;
};

let chooseFromHist = (histo) => {
    let letters = Object.keys(histo),
        letter = letters[Math.floor(Math.random() * letters.length)];

    return [letter, histo[letter] / Object.values(histo).reduce((x, y) => x + y, 0)];
};
let output = () => {
    p(chooseFromHist(histogram('We all live in a yellow submarine')));
    range(1, 10).forEach((i) => p(chooseFromHist(histogram('aab'))));
};

let clear = () => pre0.textContent = '';

btn0.onclick = output;
btn1.onclick = clear;

output();













						

0 コメント:

コメントを投稿