今回もやってみたhttp://itpro.nikkeibp.co.jp/article/MAG/20070521/271681/
文字列の判定は正規表現を利用しました。
今回もrubyで書いてみました。
ソース
class Snake def search( value ) # A = ">'"のあとに1つ以上の"="が並んだ後、"#"さらに前と同じ個数の"="が続き"~"で終わる。 # B = ">^"のあとに1つ以上の"Q="が並んだ後、"~~"で終わる。 # 上記以外は、NA if ( /^>'(=*)#\1~$/ =~ value) then #部分正規表現(n)に対する後方参照\nを利用 return "A" elsif ( /^>\^(Q=)+~~$/ =~ value ) then return "B" end return "NA" end end
テストクラス
require 'test/unit' require 'kousien/src/snake' class SnakeTest < Test::Unit::TestCase def setup @obj = Snake.new() end # def teardown # end def test_normal_a assert_equal( "A" , @obj.search(">'======#======~") ) assert_equal( "A" , @obj.search(">'=====#=====~") ) assert_equal( "A" , @obj.search(">'=#=~") ) assert_equal( "NA" , @obj.search(">'======#=====~") ) assert_equal( "NA" , @obj.search(">'=====#======~") ) assert_equal( "NA" , @obj.search(">'======#======") ) assert_equal( "NA" , @obj.search("'======#======~") ) assert_equal( "NA" , @obj.search(">'===#====~") ) assert_equal( "NA" , @obj.search(">'=====-=====~") ) end def test_normal_b assert_equal( "B" , @obj.search(">^Q=Q=Q=Q=Q=Q=Q=Q=Q=~~") ) assert_equal( "B" , @obj.search(">^Q=~~") ) assert_equal( "NA" , @obj.search(">^~~") ) assert_equal( "NA" , @obj.search(">^Q=Q=Q=Q=Q=Q=Q=Q=Q=~") ) assert_equal( "NA" , @obj.search(">Q=Q=Q=Q=Q=Q=Q=Q=Q=~~") ) end end
実行結果
Loaded suite test/snake_test Started .. Finished in 0.0 seconds. 2 tests, 14 assertions, 0 failures, 0 errors