開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- プログラミング言語: Ruby
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 8章(配列とイテレータ), 8.3(練習問題)配列の構築とソート を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
配列の構築とソート
コード(BBEdit)
sample.rb
#!/usr/bin/env ruby1.9 #-*- coding: utf-8 -*- words = [] while true word = gets.chomp break if word == "" words.push word end sorted_words = words.sort puts "ソート前: #{words.join(" ")}" puts "ソート後: #{sorted_words.join(" ")}"
入出力結果(Terminal)
$ ./sample.rb ruby perl python haskell javascript c# ソート前: ruby perl python haskell javascript c# ソート後: c# haskell javascript perl python ruby $
ちなみにJavaScriptの場合。
コード(BBEdit)
var words = [], word = "", result = "", sorted_words, i, max; while( true ) { word = prompt("単語を入力(空白で終了)", ""); if ( word === "" ) { break; } words.push(word); } sorted_words = words.slice(); sorted_words.sort(); result = "ソート前: " + words.join(" ") + "\n" + "ソート後: " + sorted_words.join(" "); $('#pre0').text(result);
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3 #-*- coding: utf-8 -*- words = [] while True: word = input("単語を入力(空白で終了): ") if word == "": break words.append(word) sorted_words = sorted(words) print(" ".join(words), " ".join(sorted_words), sep="\n")
入出力結果(Terminal)
$ ./sample.py 単語を入力(空白で終了): ruby 単語を入力(空白で終了): perl 単語を入力(空白で終了): python 単語を入力(空白で終了): haskell 単語を入力(空白で終了): javascript 単語を入力(空白で終了): c# 単語を入力(空白で終了): ruby perl python haskell javascript c# c# haskell javascript perl python ruby $
perlの場合。
sample.pl
コード(BBEdit)
#!/usr/bin/env perl use strict; use warnings; use utf8; use 5.016; binmode STDIN, ":utf8"; binmode STDOUT, ":utf8"; my @words = (); while (1) { chomp(my $word = <STDIN>); last if $word =~ /^\s*$/; push @words, $word; } my @sorted_words = sort @words; print "@words\n@sorted_words\n";
入出力結果(Terminal)
$ ./sample.pl ruby perl python haskell javascript c# ruby perl python haskell javascript c# c# haskell javascript perl python ruby $
0 コメント:
コメントを投稿