2009-10-10から1日間の記事一覧

mのn乗

再帰の勉強 #Ruby def pow(m,n) if n == 0 then 1 else m * pow(m,n-1) end end puts pow(2,3) #=>8 //scala def pow(m: Int,n: Int):Int= if (n == 0) 1 else m * pow(m,n-1) println(pow(2,3)) //=>8

Listのlengthその2

もういっちょ #ruby def length(arr) def length_loop(arr,count=0) if arr.empty? then count else arr.shift length_loop(arr,count+1) end end length_loop(arr) end puts length [1,2,3,"a"] #=>4 //Scala def length[T](lst: List[T]):Int ={ def lengt…

Listのlength

再帰の勉強 #Ruby #Arrayで代用・・・ def length(arr) if arr.empty? then 0 else arr.shift 1 + length(arr) end end puts length [1,2,3,4] #=>4 ついでにScalaをちょっぴり勉強 //Scala def length(lst: List[Int]):Int = if (lst == Nil) 0 else length…

階乗その3

再帰の勉強 #Ruby def fact(n) def fact_loop(n, i=1, p=1) if i > n then p else fact_loop(n, i+1, p*i) end end fact_loop(n) end puts fact(5) #=>120 //Scala def fact(n: Int):Int={ def factLoop(n: Int, i: Int, p: Int):Int = if (i > n) p else fa…

最大公約数

再帰の勉強 #Ruby def gcd(m,n) if m % n == 0 then n else gcd(n, m % n) end end puts gcd(30,18) #=>6 //Scala def gcd(m: Int,n: Int):Int= if (m % n==0) n else gcd(n, m % n) println(gcd(30,18)) //=>6