2017年5月17日水曜日

開発環境

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 9(Arrays and Lists)の Exercise 9-11、12.を JavaScript で取り組んでみる。

Exercise 9-11、12.

words.txt

コード(Emacs)

HTML5

<pre id="output0"></pre>
<input id="file0" type="file">

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

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

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    input_file0 = document.querySelector('#file0'),
    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 bisect = (array, item) => {
    let inner = (idx1, idx2) => {
        if (idx1 > idx2) {
            return false;
        }

        let idx = Math.floor((idx1 + idx2) / 2),
            middle = array[idx];

        if (item === middle) {
            return true;
        }
        if (item < middle) {
            return inner(idx1, idx - 1);
        }
        return inner(idx + 1, idx2);
    };
    return inner(0, array.length - 1);
};


let output = () => {
    let reader = new FileReader();

    reader.onload = () => {
        let words = reader.result.split('\n')
            .filter((word) => word !== '')
            .map((word) => word.trim());

        p('11.');
        words.forEach((word) => {
            let word0 = word.split('').reverse().join('');

            if (word < word0 && bisect(words, word0)) {
                p(`${word}, ${word0}`);
            }            
        });

        p('12.');
        words.forEach((word) => {
            let word1 = word.split('').filter((c, i) => i % 2 == 0).join(''),
                word2 = word.split('').filter((c, i) => i % 2 == 1).join('');

            if (bisect(words, word1) && bisect(words, word2)) {
                p(`"${word1}" and "${word2}" interlock to form "${word}".`);
            }            
        });
    };
    reader.readAsText(input_file0.files[0]);
};

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

// output();















						

0 コメント:

コメントを投稿