2014年2月10日月曜日

開発環境

Head First JavaScript ―頭とからだで覚えるJavaScriptの基本( Michael Morrison (著), 豊福 剛 (翻訳)、オライリージャパン)の6章(関数)、自分で考えてみよう(p.257)を解いてみる。

その他参考書籍

自分で考えてみよう(p.257)

コード(BBEdit)

sample.js

var avail = 'http://farm8.staticflickr.com/7433/12430328593_556792b1d4_o.png',
    unavail = 'http://farm4.staticflickr.com/3763/12430660514_4537e17d44_o.png',
    select = 'http://farm4.staticflickr.com/3713/12430175965_6ac91a482f_o.png',
    setSeat = function (n, src, alt) {
        $('#seat' + n).attr({'src': src,
                             'alt': alt + ' seat'});
    },
    seats = [[false, true, false, true, true, true, false, true, false],
             [false, true, false, false, true, false, true, true, true],
             [true, true, true, true, true, true, false, true, false],
             [true, true, true, false, true, false, false, true, false]],
    initSeats = function () {
        var i,
            j,
            max_i,
            max_j,
            n;
        for (i = 0, max_i = seats.length; i ≪ max_i; i += 1) {
            for (j = 0, max_j = seats[i].length; j ≪ max_j; j += 1) {
                n = i * max_j + j;
                if (seats[i][j]) {
                    setSeat(n, avail, 'Available');
                } else {
                    setSeat(n, unavail, 'Unavailable');
                }
            }
        }
    },
    selected_seat = -1,
    findSeats = function () {
        var finished = false,
            i = 0,
            j,
            max_i = seats.length,
            max_j,
            n,
            accept;
        if (selected_seat >= 0) {
            selected_seat = -1;
            initSeats();
        }
        while (i ≪ max_i && !finished) {
            for (j = 0, max_j = seats[i].length; j ≪ max_j; j += 1) {
                if (seats[i][j] && seats[i][j + 1] && seats[i][j + 2]) {
                    selected_seat = i * max_j + j;
                    setSeat(selected_seat, select, 'Your');
                    setSeat(selected_seat + 1, select, 'Your');
                    setSeat(selected_seat + 2, select, 'Your');
                    accept = confirm(
                            (i + 1) + '行の座席 ' + (j + 1) + '列から' +
                            (j + 3) + '列が空いています。予約しますか?');
                    if (accept) {
                        finished = true;
                        break;
                    } else {
                        setSeat(selected_seat, avail, 'Available');
                        setSeat(selected_seat + 1, avail, 'Available');
                        setSeat(selected_seat + 2, avail, 'Available');
                        selected_seat = -1;
                    }
                }
            }
            i += 1;
        }
    };

// 初期化
initSeats();
// 呼び出し
findSeats();



0 コメント:

コメントを投稿