Skip to content

Instantly share code, notes, and snippets.

@kachick
Created April 29, 2012 18:25
Show Gist options
  • Select an option

  • Save kachick/2552441 to your computer and use it in GitHub Desktop.

Select an option

Save kachick/2552441 to your computer and use it in GitHub Desktop.
Rubyでアルゴリズムやらデータ構造やらのお勉強(recursive - 1)
# -*- coding: utf-8 -*-
# Cで書かれたアルゴリズムやらデータ構造なりを、自分なりにRubyで表現してみるお勉強PJ。
# 参考書籍(プログラミングの宝箱 アルゴリズムとデータ構造)
# Ruby1.9.3で動作確認済み
# 再帰の例にあったやつを数指定可能に。根っこはひねる余地なさげ
$VERBOSE = true
def looped_number_of(num, digit, base=10)
counter = 0
while num > 0
if num % base == digit
counter += 1
end
num /= base
end
counter
end
def recursive_number_of(num, digit, base=10)
return 0 if num == 0
div, mod = num.divmod base
(mod == digit ? 1 : 0) + recursive_number_of(div, digit)
end
# Overview
p looped_number_of 13167, 1 #=> 2
p looped_number_of 111561171, 1 #=> 6
p looped_number_of 173181, 1 #=> 3
p recursive_number_of 13167, 1 #=> 2
p recursive_number_of 111561171, 1 #=> 6
p recursive_number_of 173181, 1 #=> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment