2012年12月10日月曜日

開発環境

『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 7章(フロー制御), 7.5(練習問題)耳の遠いおばあちゃん を解いてみる。

その他参考書籍

耳の遠いおばあちゃん

コード(TextWrangler)

sample.rb

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

n = 5
while true
  puts "#{n} bottles of beer on the wall, #{n} bottles of beer!"
  n -= 1
  break if n == 1
  puts "Take one down, pass it around, #{n} bottles of beer on the wall!"
end
puts "Take one down, pass it around, #{n} bottle of beer on the wall!"
puts "#{n} bottle of beer on the wall, #{n} bottle of beer!"
puts "Take one down, pass it around, no more bottles of beer on the wall"

入出力結果(Terminal)

$ ./sample.rb
hi
HUH?! SPEAK UP, SONNY!
Hi
HUH?! SPEAK UP, SONNY!
HI
NO, NOT SINCE 1933!
HI 
NO, NOT SINCE 1930!
HI
NO, NOT SINCE 1947!
HI
NO, NOT SINCE 1938!
HI
NO, NOT SINCE 1944!
bye
HUH?! SPEAK UP, SONNY!
Bye
HUH?! SPEAK UP, SONNY!
BYE
BYE
$

ちなみにJavaScriptの場合。

コード(TextWrangler)

<pre id='pre0' ></pre>

<label id="l0"><input id="t0" type="text" value="Hi" onkeydown="f()" /></label>
<input id="btn0" type="button" value="say" onclick="say()"/><br />
<script>
function say(){
  var said = $('#t0').val();
  $('#pre0').append(said + "\n");
  if(said == "BYE"){
    $('#pre0').append("BYE\n");
    $('#l0').remove();
    $('#btn0').remove();
    return;
  }
  if(said == said.toUpperCase()){
    var year = 1930 + parseInt(Math.random() * 21);
    $('#pre0').append("NO, NOT SINCE " + year + "!\n");
  } else {
    $('#pre0').append("HUH?! SPEAK UP, SONNY!\n");
  }
}
function f(e){
  var e = e ? e : window.event;
  if(e.keyCode == 13) say();
}
</script>




pythonの場合。

sample.py

コード(TextWrangler)

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

import random

while 1:
    said = input()
    if said == "BYE":
        print("BYE")
        break
    if said == said.upper():
        print("NO, NOT SINCE {0}!".format(random.randint(1930, 1950)))
    else:
        print("HUH?! SPEAK UP, SONNY!")

入出力結果(Terminal)

$ ./sample.py
hi
HUH?! SPEAK UP, SONNY!
Hi
HUH?! SPEAK UP, SONNY!
HI
NO, NOT SINCE 1947!
HI
NO, NOT SINCE 1940!
HI
NO, NOT SINCE 1937!
HI
NO, NOT SINCE 1937!
HI
NO, NOT SINCE 1943!
bye
HUH?! SPEAK UP, SONNY!
Bye
HUH?! SPEAK UP, SONNY!
BYE
BYE
$

perlの場合。

sample.pl

コード(TextWrangler)

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

while(1){
  chomp(my $said = <STDIN>);
  if($said eq "BYE"){
    print "BYE\n";
    last;
  }
  if($said eq uc $said){
    print "NO, NOT SINCE " . int(1930 + rand(21)) . "!\n";
  } else {
    print "HUH?! SPEAK UP, SONNY!\n";
  }
}

入出力結果(Terminal)

$ ./sample.pl
hi
HUH?! SPEAK UP, SONNY!
HI
NO, NOT SINCE 1943!
HI
NO, NOT SINCE 1936!
HI
NO, NOT SINCE 1949!
HI
NO, NOT SINCE 1942!
HI
NO, NOT SINCE 1930!
bye
HUH?! SPEAK UP, SONNY!
Bye
HUH?! SPEAK UP, SONNY!
BYE
BYE
$

0 コメント:

コメントを投稿