2017年4月28日金曜日

開発環境

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 5(Fruitful Subroutines)の Exercises. を JavaScript で取り組んでみる。

Exercises.

コード(Emacs)

HTML5

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

<script src="sample1.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 += step) {
            result.push(i);
        }
        return result;
    };

let ack = (m, n) => {
    if (m === 0) {
        return n + 1;
    }
    if (m > 0 && n === 0) {
        return ack(m - 1, 1);
    }
    return ack(m - 1, ack(m, n - 1));
};
let firstL = (word) => word.substring(0, 1),
    lastL = (word) => word.substring(word.length - 1),
    middleL = (word) => word.substring(1, word.length - 1);

let isPalindrome = (word) =>
    word.length <= 1 ? true :
    firstL(word) === lastL(word) ? isPalindrome(middleL(word)) :
    false;

let isPowerOf = (a, b) => a === 1 ? true :
    a % b === 0 && isPowerOf(Math.floor(a / b), b);

let gcd = (a, b) =>
    b === 0 ? a :
    gcd(b, a % b);

let output = () => {
    p('2.');
    range(1, 4)
    .forEach((m) =>
             range(1, 5)
             .forEach((n) => p(`ack(${m}, ${n}) => ${ack(m, n)}`)));
    p('3-3');
    p(isPalindrome(''));
    p(isPalindrome('a'));
    p(!isPalindrome('ab'));
    p(isPalindrome('aba'));
    p(!isPalindrome('abc'));
    p(isPalindrome('abba'));
    p(!isPalindrome('abca'));

    p('4.');
    range(1, 21)
        .forEach((a) =>
                 range(2, 4)
                 .forEach((b) => {
                     if (isPowerOf(a, b)) {
                         p(`${a} is power of ${b}`);
                     } else {
                         p(`${a} is not power of ${b}`);
                     }
                 }));
    p('5.');
    range(2, 11)
        .forEach((a) =>
                 range(2, 11)
                 .forEach((b) => p(`(${a}, ${b}) = ${gcd(a, b)}`)));
};

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

output();










 
						

0 コメント:

コメントを投稿

Comments on Google+: