データ間の関係を表現する

備忘録目次 - ロバの耳

ハッシュで単方向リンクリストを作って,それを操作する.

# 先祖を探す.リストには自分を含める
def get_ancestor( h, c)
	ret = [c]
	while(true) 
		c = h[c]
		return ret unless c
		ret << c 
	end
end

# 子供を探す.自分は含めない
def get_children( h, c)
	ret = []
	h.each_pair{|k,v| ret << k if v==c}
	'nobody' if ret.empty?
	ret
end

# 子孫を探す.自分は含めない
def get_descendant( h, c)
	ret = []
	h.each_pair{|k,v|
		if v==c
			ret << k
			heir = get_descendant( h, k)
			ret += heir unless heir[0]=='nobody'
		end
	}
	'nobody' if ret.empty?
	ret
end

father = Hash[*%w[Cain Adam Abel Adam Seth Adam Enoch Cain Irad Enoch Mehujael Irad Methusael Mehujael Lamech Methusael Jabal Lamech Jubal Lamech Tubalcain Lamech Enos Seth]]

p get_ancestor( father, 'Enoch')
p get_children( father, 'Enoch')
p get_descendant( father, 'Enoch')


もう少し綺麗にまとめられるような気がする.いやハッシュで逆検索するのが悪いのか?

循環参照していると無限ループで死ぬ.キリスト教に対する他意はない*1

*1:とわざわざ書くのもどうか?