2016年10月4日火曜日

開発環境

アルゴリズムパズル(Anany Levitin (著)、Maria Levitin (著)、黒川 洋 (翻訳)、松崎 公紀 (翻訳)、オライリージャパン)の中級パズル、63.(プラスとマイナス(Pluses and Minuses))をJavaScriptで。

63.(プラスとマイナス(Pluses and Minuses))

i=1 n i = n( n+1 ) 2 n( n+1 ) 2 2 = n( n+1 ) 4 n=4k i( i+1 )( i+2 )+( i+3 )=0( i=1,5,···,n3 ) n+1=4k n=4k1=3+4( k1 ) 1+23=0 i( i+1 )( i+2 )+( i+3 )=0( i=4,···,n3 ) n0,3( mod4 )

コード(Emacs)

HTML5

<label for="0">n = </label>
<input id="n0" type="number" min="1" step="1" value="100">
<div id="output0"></div>
<script src="sample63.js"></script>

JavaScript

{
    'use strict';
    Array.range = function (start, end, step) {
        var nums = [],
            i;

        if (step === 0) {
            throw {
                name: 'ValueError',
                message: 'range() arg 3 must not be zero',
            };
        }
        if (step === undefined) {
            step = 1;
        }
        if (end === undefined) {
            end = start;
            start = 0;
        }
        if (step > 0) {
            for (i = start; i < end; i += step) {
                nums.push(i);
            }
        } else {
            for (i = start; i > end; i += step) {
                nums.push(i);
            }
        }
        return nums;
    };
    let div_output = document.querySelector('#output0'),
        input_n = document.querySelector('#n0');

    let nums2str = (nums) => {
        return nums.map((n) => {
            if (n >= 0) {
                return `+${n}`;
            }
            return n.toString();
        }).join('');
    };
    let sum = (nums) => {
        return nums.reduce((x, y) => x + y, 0);
    };
    let output = () => {
        let n = parseInt(input_n.value, 10),
            nums = Array.range(1, n + 1),
            output = '',
            r = n % 4;

        if (r === 0) {
            nums = nums.map((n) => {
                let r = n % 4;
                if (r === 0 || r === 1) {
                    return n;
                }
                return -n;
            });
            output = `${nums2str(nums)} = ${sum(nums)}`;
        } else if (r === 3) {
            nums = nums.map((n) => {
                if (n === 1 || n === 2) {
                    return n;
                }
                if (n === 3) {
                    return -n;
                }
                let r = n % 4;
                if (r === 0 || r === 3) {
                    return n
                }
                return -n;
            });        
            output = `${nums2str(nums)} = ${sum(nums)}`;
        } else {
            output = '解は存在しない。';
        }
        div_output.innerText = output;
    };
    input_n.onchange = output;

    output();
}

0 コメント:

コメントを投稿

Comments on Google+: