2012年12月8日土曜日

開発環境

『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 6章(メソッドの詳細), 6.2(練習問題)目次 を解いてみる。

その他参考書籍

目次

コード(TextWrangler)

sample.rb

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

width = 40
puts "table of contents".center(width)
puts
puts "chapter 1: start".ljust(width / 2) + "p.1".rjust(width / 2)
puts "chapter 2: number".ljust(width / 2) + "p.11".rjust(width / 2)
puts "chapter 3: string".ljust(width / 2) + "p.15".rjust(width / 2)

入出力結果(Terminal)

$ ./sample.rb
           table of contents            

chapter 1: start                     p.1
chapter 2: number                   p.11
chapter 3: string                   p.15
$

ちなみにJavaScriptの場合。

コード(TextWrangler)

var result = "";
String.prototype.center = function(n){
  var result = "";
  n -= this.length;
  for(var i = 0; i < n / 2; i ++){
    result += " "; 
  }
  result += this;
  return result;
};
String.prototype.ljust = function(n){
  var result = this;
  n -= this.length;
  for(var i = 0; i < n; i++){
    result += " ";
  }
  return result;
};
String.prototype.rjust = function(n){
  var result = "";
  n -= this.length;
  for(var i = 0; i < n; i++){
    result += " ";
  }
  result += this;
  return result;
};
var width = 40;
result += "table of contents".center(width) + "\n\n" +
  "chapter 1: start".ljust(width / 2) + "p.1".rjust(width / 2) + "\n" +
  "chapter 2: number".ljust(width / 2) + "p.11".rjust(width / 2) + "\n" +
  "chapter 3: string".ljust(width / 2) + "p.15".rjust(width / 2) + "\n";
$('#pre0').text(result);


pythonの場合。

sample.py

コード(TextWrangler)

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

width = 40
print("tables of contents".center(width))
print()
print("chapter 1: start".ljust(width // 2) + "p.1".rjust(width // 2))
print("chapter 2: number".ljust(width // 2) + "p.11".rjust(width // 2))
print("chapter 3: string".ljust(width // 2) + "p.15".rjust(width // 2))

入出力結果(Terminal)

$ ./sample.py
           tables of contents           

chapter 1: start                     p.1
chapter 2: number                   p.11
chapter 3: string                   p.15
$

perlの場合。

sample.pl

コード(TextWrangler)

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

my $width = 40;
my $half = $width / 2;

print " " x (($width - length("table of contents")) / 2) . "table of contents\n";
print "\n";
printf "%-${half}s%${half}s\n", "chapter 1: start", "p.1";
printf "%-${half}s%${half}s\n", "chapter 2: number", "p.11";
printf "%-${half}s%${half}s\n", "chapter 3: string", "p.15";

入出力結果(Terminal)

$ ./sample.pl
           table of contents

chapter 1: start                     p.1
chapter 2: number                   p.11
chapter 3: string                   p.15
$

0 コメント:

コメントを投稿