nbonacci sequence (n-bonacci数列)の初項から指定した数の項までを計算するためのScalaのコード例。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// See https://pandanote.info/?p=6259 for details. | |
// | |
package info.pandanote.nbonaccitest | |
import scopt.OParser | |
import org.slf4j.LoggerFactory | |
import scala.collection.mutable.ListBuffer | |
case class Options(a: Int = 2, n: Int = 10) | |
class NBonacci | |
object NBonacci { | |
private lazy val logger = LoggerFactory.getLogger(classOf[NBonacci]) | |
def main(args: Array[String]): Unit = { | |
val builder = OParser.builder[Options] | |
val parser = { | |
import builder._ | |
OParser.sequence( | |
programName("NBonacci"), | |
head("NBonacci","0.1.0-SNAPSHOT"), | |
opt[Int]('a',"term") | |
.action((x,c) => c.copy(a = x)).text("Number of terms in the recurrence relation.") | |
.validate(x => | |
if (x > 0) success | |
else failure("Value <a> must be a positive integer")), | |
opt[Int]('n',"number-of-terms") | |
.action((x,c) => c.copy(n = x)).text("Number of terms to calculate.") | |
.validate(x => | |
if (x > 0) success | |
else failure("Value <n> must be a positive integer")), | |
help("help").text("Calculate n-bonacci sequence.") | |
) | |
} | |
val o: Options = OParser.parse(parser,args,Options()) match { | |
case Some(options) => options | |
case _ => sys.exit(1) | |
} | |
logger.info(o.toString) | |
val buf = ListBuffer.fill(o.a-1)(0) | |
buf += 1 | |
var count = 0 | |
while (count < o.n) { | |
if (count < o.a) { | |
println(buf(count)) | |
} else { | |
val next = buf.result.foldRight(0){(x,y) => x+y} | |
println(next) | |
buf += next | |
buf.remove(0) | |
} | |
count+=1 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment