2013年1月9日水曜日

開発環境

『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 2章(数値), 2.5(練習問題)この本の著者の年齢 を解いてみる。

その他参考書籍

この本の著者の年齢

コード(BBEdit)

sample.rb

#!/usr/bin/env ruby1.9
#-*- coding: utf-8 -*-

td = Time.new
birth = td - 10.25 * (10**8)
age = 0
while Time.new(birth.year + age, birth.mon, birth.day) <= td
  age += 1
end
age -= 1
puts "#{age}歳"

入出力結果(Terminal)

$ ./sample.rb
32歳
$

ちなみにJavaScriptの場合。

コード(BBEdit)

var td = new Date();
var birth = new Date(td - 10.25 * Math.pow(10, 8) * 1000);
var age = -1;
do{
  age++;
  birth.setFullYear(birth.getFullYear() + 1);
} while (birth <= td);
$('#pre0').text(age + "歳");



pythonの場合。

sample.py

コード(BBEdit)

#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-

import datetime

td = datetime.datetime.now()
td_timestamp = td.timestamp()
birth_timestamp = td_timestamp - 10.25 * (10**8)
birth = datetime.datetime.fromtimestamp(birth_timestamp)
age = 0
while birth.replace(year=birth.year + age) <= td:
    age += 1
else:
    age -= 1

print("{0}歳".format(age))

入出力結果(Terminal)

$ ./sample.py
32歳
$

perlの場合。

sample.pl

コード(BBEdit)

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.016;
binmode STDIN, ":utf8";
binmode STDOUT, ":utf8";
use Time::Local;

my $td_timestamp = timelocal((localtime)[0, 1, 2, 3, 4, 5]);
my $birth_timestamp = $td_timestamp - 10.25 * (10**8);
my @birth = localtime($birth_timestamp);
my $timestamp = $birth_timestamp;

my $age = 1;
while( timelocal(@birth[0, 1, 2, 3, 4], $birth[5] + $age) <= $td_timestamp){
  $age++;
}
$age--;
print $age . "歳\n";

入出力結果(Terminal)

$ ./sample.pl
32歳
$

0 コメント:

コメントを投稿