Last active
August 29, 2015 14:03
-
-
Save odaillyjp/7b190cc71ab7ee1e06d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'minitest' | |
require 'minitest/autorun' | |
require 'pry' | |
MAX_WIDTH = 5 | |
MAX_HEIGHT = 5 | |
SENTINEL_CHER = -1 | |
def solve(str) | |
init_numbers_field(str) | |
init_memo | |
count_depthes = [] | |
MAX_WIDTH.times do |x| | |
MAX_HEIGHT.times do |y| | |
count_depthes << count_depth(x + 1, y + 1) | |
end | |
end | |
count_depthes.max | |
end | |
# 入力値を二次元配列にする | |
def init_numbers_field(str) | |
@numbers_field = str.split('/').map(&:chars).transpose | |
@numbers_field.each { |row| row.map!(&:to_i) } | |
# 番兵 | |
horizontal_sentinels = Array.new(MAX_WIDTH, SENTINEL_CHER) | |
@numbers_field.push horizontal_sentinels | |
@numbers_field.unshift horizontal_sentinels | |
@numbers_field.map do |row| | |
row.push SENTINEL_CHER | |
row.unshift SENTINEL_CHER | |
end | |
end | |
# メモ化用の二次元配列を作る | |
def init_memo | |
@max_depth_memo = [] | |
# 番兵を配慮して、MAX_WIDTH と MAX_HEIGHT に +2 する | |
(MAX_WIDTH + 2).times do | |
@max_depth_memo << Array.new(MAX_HEIGHT + 2, nil) | |
end | |
end | |
def count_depth(x, y) | |
return 0 if @numbers_field[x][y] == SENTINEL_CHER | |
return @max_depth_memo[x][y] if @max_depth_memo[x][y] | |
count_depthes = [1] | |
current_number = @numbers_field[x][y] | |
if @numbers_field[x][y - 1] > current_number | |
count_depthes << (1 + count_depth(x, y - 1)) | |
end | |
if @numbers_field[x + 1][y] > current_number | |
count_depthes << (1 + count_depth(x + 1, y)) | |
end | |
if @numbers_field[x - 1][y] > current_number | |
count_depthes << (1 + count_depth(x - 1, y)) | |
end | |
if @numbers_field[x][y + 1] > current_number | |
count_depthes << (1 + count_depth(x, y + 1)) | |
end | |
# メモ化 | |
@max_depth_memo[x][y] = count_depthes.max | |
@max_depth_memo[x][y] | |
end | |
class TestFoo < MiniTest::Unit::TestCase | |
SAMPLES = [ | |
['01224/82925/69076/32298/21065', 6], | |
['03478/12569/03478/12569/03478', 10], | |
['09900/28127/87036/76545/87650', 10], | |
['77777/77777/77777/77777/77777', 1], | |
['00000/11111/22222/33333/44444', 5], | |
['01234/12345/23456/34567/45678', 9], | |
['10135/21245/43456/55567/77789', 8], | |
['33333/33333/55555/55555/77777', 2], | |
['01234/11234/22234/33334/44444', 5], | |
['98765/88765/77765/66665/55555', 5], | |
['01234/10325/23016/32107/45670', 8], | |
['34343/43434/34343/43434/34343', 2] | |
] | |
SAMPLES.each_with_index do |sample_data, idx| | |
define_method "test_exercise_no#{idx}" do | |
assert_equal(solve(sample_data.first), sample_data.last) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment