Catalan numbers: Difference between revisions

Kotlin: strategy pattern
(Kotlin version enhanced)
(Kotlin: strategy pattern)
Line 1,891:
 
=={{header|Kotlin}}==
{{trans|Java}}
{{works with|Java|1.7.0}}
{{works with|Kotlin|1.0.0}}
Line 1,897 ⟶ 1,896:
<lang scala>import net.openhft.koloboke.collect.map.hash.HashIntDoubleMaps.*
 
objectabstract class Catalan {
abstract operator fun catIinvoke(n: Int) : Double {
if (n !in catsI)
catsI[n] = Math.round(fact(2 * n) / (fact(n + 1) * fact(n))).toDouble()
 
privateprotected val catsIm = newUpdatableMapOf(0 , 1.0)
return catsI[n]
}
}
 
object CatalanI : Catalan() {
fun catR1(n: Int): Double {
override fun if invoke(n: inInt): catsR1)Double {
if (n !in return catsR1[n]m)
catsIm[n] = Math.round(fact(2 * n) / (fact(n + 1) * fact(n))).toDouble()
 
varreturn sum = 0.0m[n]
for (i in 0..n - 1)
sum += catR1(i) * catR1(n - 1 - i)
sum = Math.round(sum).toDouble()
 
catsR1[n] = sum
return sum
}
 
fun catR2(n: Int): Double {
if (n !in catsR2)
catsR2[n] = Math.round(2.0 * (2 * (n - 1) + 1) / (n + 1) * catR2(n - 1)).toDouble()
 
return catsR2[n]
}
 
Line 1,928 ⟶ 1,912:
if (n in facts)
return facts[n]
var f = 2.0n * fact(n -1)
 
var f = 2.0
for (i in 3..n)
f *= i
 
facts[n] = f
return f
Line 1,938 ⟶ 1,918:
 
private val facts = newUpdatableMapOf(0 , 1.0, 1 , 1.0, 2 , 2.0)
}
private val catsI = newUpdatableMapOf(0 , 1.0)
 
private val catsR1 = newUpdatableMapOf(0 , 1.0)
object CatalanR1 : Catalan() {
private val catsR2 = newUpdatableMapOf(0 , 1.0)
override fun catR1invoke(n: Int): Double {
if (n !in catsR2m)
return catsR2m[n]
 
var sum f *= i0.0
for (i in 0..n - 1)
sum += catR1invoke(i) * catR1invoke(n - 1 - i)
sum = Math.round(sum).toDouble()
catsR1m[n] = sum
return sum
}
}
 
object CatalanR2 : Catalan() {
override fun catR2invoke(n: Int): Double {
if (n !in catsIm)
catsR2m[n] = Math.round(2.0 * (2 * (n - 1) + 1) / (n + 1) * catR2invoke(n - 1)).toDouble()
return catsIm[n]
}
}
 
fun main(args: Array<String>) {
val c = arrayOf(CatalanI, CatalanR1, CatalanR2)
for(i in 0..15)
for (i in 30..n15) {
println( "[%9d %9d %9d]".format(Catalan.catI(i).toLong(), Catalan.catR1(i).toLong(), Catalan.catR2(i).toLong()))
c.forEach { print("%9d".format(it(i).toLong())) }
println()
}
}</lang>
{{out}}
<pre>[ 1 1 1]
[ 1 1 1]
[ 2 2 2]
[ 5 5 5]
[ 14 14 14]
[ 42 42 42]
[ 132 132 132]
[ 429 429 429]
[ 1430 1430 1430]
[ 4862 4862 4862]
[ 16796 16796 16796]
[ 58786 58786 58786]
[ 208012 208012 208012]
[ 742900 742900 742900]
[ 2674440 2674440 2674440]
[ 9694845 9694845 9694845]</pre>
 
=={{header|Liberty BASIC}}==
Anonymous user