Skip to content

Instantly share code, notes, and snippets.

@pandanote-info
Last active May 2, 2020 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pandanote-info/4fa7111d4d6df5e7b4f1f9b0bc3c9c05 to your computer and use it in GitHub Desktop.
Save pandanote-info/4fa7111d4d6df5e7b4f1f9b0bc3c9c05 to your computer and use it in GitHub Desktop.
nbonacci sequence (n-bonacci数列)の初項から指定した数の項までを計算するためのScalaのコード例。
//
// 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