Groovyでトランポリン遊び
お題
1から10まで足す。
これぐらいだと trampolineにする意味はないけどね。
ソース
def fact1 = { n, total -> n == 0 ? total : trampoline(n - 1, n + total) } def factorial1 = { n -> fact1.trampoline().call(n, 0) } assert factorial1(10) == 55 def fact2 = { list, total -> list == [] ? total : trampoline(list.tail(), list.head() + total) } def factorial2 = { list -> fact2.trampoline().call(list, 0) } assert factorial2(1..10) == 55 def fact3 = { list, total -> if(!list) { total } else { trampoline(list.tail(), list.head() + total) } } def factorial3 = { list -> fact3.trampoline().call(list, 0) } assert factorial3(1..10) == 55 def fact4 = { list, total -> if(!list) { total } else { trampoline(list.tail(), list.head() + total) } } def factorial4 = { list -> fact4.trampoline().call(list, 0) } assert factorial4([1,2,3,4,5,6,7,8,9,10]) == 55
[D:\workspace\groovy_SandBox]groovy 0001その前にトランポリンで遊ぶ.groovy [D:\workspace\groovy_SandBox]
動きの確認
1番目
n=10, total=0 n=9, total=10 n=8, total=19 n=7, total=27 n=6, total=34 n=5, total=40 n=4, total=45 n=3, total=49 n=2, total=52 n=1, total=54 n=0, total=55
2番目
list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], total=0 list=[2, 3, 4, 5, 6, 7, 8, 9, 10], total=1 list=[3, 4, 5, 6, 7, 8, 9, 10], total=3 list=[4, 5, 6, 7, 8, 9, 10], total=6 list=[5, 6, 7, 8, 9, 10], total=10 list=[6, 7, 8, 9, 10], total=15 list=[7, 8, 9, 10], total=21 list=[8, 9, 10], total=28 list=[9, 10], total=36 list=[10], total=45 list=[], total=55
3番目
list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], total=0 list=[2, 3, 4, 5, 6, 7, 8, 9, 10], total=1 list=[3, 4, 5, 6, 7, 8, 9, 10], total=3 list=[4, 5, 6, 7, 8, 9, 10], total=6 list=[5, 6, 7, 8, 9, 10], total=10 list=[6, 7, 8, 9, 10], total=15 list=[7, 8, 9, 10], total=21 list=[8, 9, 10], total=28 list=[9, 10], total=36 list=[10], total=45 list=[], total=55
4番目
list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], total=0 list=[2, 3, 4, 5, 6, 7, 8, 9, 10], total=1 list=[3, 4, 5, 6, 7, 8, 9, 10], total=3 list=[4, 5, 6, 7, 8, 9, 10], total=6 list=[5, 6, 7, 8, 9, 10], total=10 list=[6, 7, 8, 9, 10], total=15 list=[7, 8, 9, 10], total=21 list=[8, 9, 10], total=28 list=[9, 10], total=36 list=[10], total=45 list=[], total=55
効果があるのはこのぐらいの値かな。
printlnfactorial1(1000) println factorial1(10000) println factorial1(100000)
500500 50005000 705082704
おや?
こうか。
println factorial1(1000G) println factorial1(10000G) println factorial1(100000G)
500500 50005000 5000050000
添削歓迎
間違ってるよ、こうした方がGroovyらしくないか?
などなど
方法は、コメント、トラックバック、はてブ、Twitter @orange_clover宛 で、お願いしまます。