0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

自然数の分割を辞書式順序ですべて書き出す関数を書いてみた

Posted at

初めての投稿です.Markdown記法も初めて使います.Rubyの上達のためにQiitaを始めました.よろしくお願いします.

$7=3+2+1+1$という7の分割を[3,2,1,1]という配列で表現することにする.
このとき,自然数$n$の分割を(配列の配列として)辞書式順序ですべて書き出す関数を書いてみた.

split.rb
def split(n)
	result=[[n]]
	return result if n==1
	(1..n-1).each do |i|
		y=[]
		z=split(i).delete_if{|x| x.max>n-i}
		z.each do |x|
			y.push(x.insert(0,n-i))
		end
		y.each do |j|
			result.push(j)
		end
	end
	return result
end

p split(6)
 #=>[[6], [5, 1], [4, 2], [4, 1, 1], [3, 3], [3, 2, 1], [3, 1, 1, 1], [2, 2, 2], [2, 2, 1, 1], [2, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]

配列として出力したので,split(n).lengthとすることで$n$の分割数がわかる.ただし,分割をすべて求めるという経路をたどっているため,分割数を求めるプログラムとしては遅いと思われる.

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?