2016年9月3日土曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 5(Functions)、24(Anagram Checker)を取り組んでみる。

24(Anagram Checker)

コード(Emacs)

Enter two strings and I'll tell you if tye are anagrams:
<br>
<label for="first_str0">
  Enter the first string:
</label>
<input id="first_str0" type="text" value="note">
<br>
<label for="second_str0">
  Enter the second string:
</label>
<input id="second_str0" type="text" value="tone">
<br>
<div id="output0"></div>

<script src="sample24.js"></script>
(function () {
    'use strict';
    var input_first = document.querySelector('#first_str0'),
        input_second = document.querySelector('#second_str0'),
        inputs = [input_first, input_second],
        div_output = document.querySelector('#output0'),

        isAnagram,
        output;    

    isAnagram = function (str1, str2) {
        var len1 = str1.length,
            len2 = str2.length,
            i,
            j,
            t,
            find;

        if (len1 === len2) {
            for (i = 0; i < len1; i += 1) {
                find = false;
                t = '';
                for (j = 0; j < len2; j += 1) {
                    if (find) {
                        t += str2[j];
                    } else if (str1[i] === str2[j]) {
                        find = true;
                    } else {
                        t += str2[j];
                    }
                }
                if (find) {
                    str2 = t;
                    len2 -= 1;
                } else {
                    return false;
                }
            }
            return true;
        }
        return false;
    };

    output = function () {
        var s1 = input_first.value,
            s2 = input_second.value;

        if (isAnagram(s1, s2)) {
            div_output.innerText =
                '"' + s1 + '" and "' + s2 + '" are anagrams.';
        } else {
            div_output.innerText =
                '"' + s1 + '" and "' + s2 + '" are not anagrams.';
        }
    };

    inputs.forEach(function (input) {
        input.onchange = output;
    });
    output();
}());
Enter two strings and I'll tell you if tye are anagrams:


0 コメント:

コメントを投稿

Comments on Google+: