練習問題/解答例/Scala
をテンプレートにして作成
[
トップ
] [
新規
|
一覧
|
検索
|
最終更新
|
ヘルプ
|
ログイン
]
開始行:
*Scala解答例 [#p9ba346f]
[[練習問題]]
解答例は次の環境でテストしています
-Scala version 2.11.6
-Java(TM) SE Runtime Environment (build 1.8.0_40-b25) 64-...
-sbt 0.13.8
ほとんどの解答例は[[ideone.com:http://ideone.com/]]でその...
つっこみは[[Top>/]]の避難所まで
#contents
**[[ループ練習>練習問題#eb2c4338]] [#s1c6b422]
***問1 [#ke7969de]
object Main extends App {
for (i <- 1 to 5) {
println("Hello World!")
}
}
別解
object Main extends App {
(1 to 5) foreach { _ =>
println("Hello World!")
}
}
***問2 [#ybb0b896]
object Main extends App {
val j = args(0).toInt
for (i <- 1 to j) {
println("Hello World! " + i)
}
}
別解
object Main extends App {
val j = args(0).toInt
(1 to j) foreach { i =>
println("Hello World! " + i)
}
}
**[[FizzBuzz>練習問題#t52e5a48]] [#ga808233]
object Main extends App {
def fizzBuzz(n: Int) =
if (n % 15 == 0) {
"FizzBuzz"
} else if (n % 5 == 0) {
"Buzz"
} else if (n % 3 == 0) {
"Fizz"
} else {
n.toString
}
(1 to 100).map(fizzBuzz).foreach(println)
}
**[[素数判定>練習問題#o8db2119]] [#ldc71efe]
***判定 [#v8e35b34]
object Main extends App {
def prime(n: Int) =
2 <= n && !(2 until (math.sqrt(n) + 1.0).toInt).exis...
val n = args(0).toInt
println(n.toString + "は" + (if (prime(n)) "素数" else...
}
***列挙 [#j53b2078]
object Main extends App {
def primes(xs: Stream[Int] = Stream.from(2)): Stream[I...
xs.head #:: primes(xs.tail.filter(_ % xs.head != 0))
primes() takeWhile {
_ <= 100
} foreach {
println
}
}
**[[うるう年測定>練習問題#i0d67516]] [#xd158eb1]
import java.util.GregorianCalendar
object Main extends App {
val cal = new GregorianCalendar()
while (true) {
print("西暦を入力してください> ")
val y = readInt()
if (y <= 0) sys.exit()
printf("%dはうるう年%s\n", y,
if (cal.isLeapYear(y)) "です" else "ではありません")
}
}
**[[転置行列>練習問題#q9f27a17]] [#o9735320]
import scala.annotation.tailrec
object Main extends App {
type Mx = List[Array[String]]
@tailrec
def matrix(xs: Mx = Nil): Mx = {
val sep = """\s+""".r
val s = readLine()
if (s.length <= 0) xs else matrix(xs :+ sep.split(s))
}
matrix().transpose.foreach(x => println(x.mkString(" "...
}
**[[カレンダー出力>練習問題#i5e3e061]] [#xde7305e]
-build.sbt
name := "vipcal"
version := "1.0"
scalaVersion := "2.10.2"
libraryDependencies ++= Seq(
"org.scala-lang" % "scala-swing" % "2.10.2",
"org.swinglabs.swingx" % "swingx-core" % "1.6.5-1"
)
-Main.scala
import scala.swing._
import org.jdesktop.swingx.{JXDatePicker, JXMonthView}
import java.awt.event.{ActionEvent, ActionListener}
object Main extends SimpleSwingApplication {
override lazy val top = new MainFrame with ActionListe...
self =>
val monthView = new JXMonthView()
val datePicker = new JXDatePicker(monthView.getToday)
datePicker.addActionListener(self)
contents = new BoxPanel(Orientation.Vertical) {
contents += Component.wrap(datePicker)
contents += Component.wrap(monthView)
}
def actionPerformed(e: ActionEvent) {
val d = datePicker.getDate
monthView.setFirstDisplayedDay(d)
monthView.setFlaggedDates(d)
}
}
}
#ref(http://i.imgur.com/uAqI9dn.png,nolink,カレンダー)
**[[配列いじり>練習問題#w5561ad6]] [#ode26856]
object Main extends App {
def tailZero(xs: Array[Int]) =
xs.head +: Array.fill(xs.tail.size){ 0 }
val a = Array(3, 5, 2, 4, 2)
println(a.mkString(" "))
println(tailZero(a).mkString(" "))
}
**[[Caesar暗号解読>練習問題#h54a0395]] [#g5a75e45]
object Main extends App {
val ciphertext =
"""qdq-gi.q-a ziatmxxitmdqibtqi-ustbi ri.qmoqrcxi.qb...
|-ibtqi-qp-qaai ripmymsqkir -ibtqi-qy dmxi ri.cnxu...
|-ibtqiqzmobyqzbkii-q.qmxi -imyqzpyqzbi rixmeaki -...
|-i-qscxmbu zaimzpir -i btq-iymbbq-a;iz -iatmxximz...
|zinqiuzimzgiemgipuao-uyuzmbqpimsmuzabir -ia. za -...
val chars = """abcdefghijklmnopqrstuvwxyz .,-"""
def rot(s: String, count: Int) =
s.splitAt(s.length - count - 1) match {
case (a, b) => b + a
}
(1 until chars.length) map {
i => chars.zip(rot(chars, i)).toMap
} map {
p => ciphertext.map(c => p.getOrElse(c, c))
} filter(_.contains("person")) foreach {
println
}
}
**[[フィボナッチ数列>練習問題#p59f794f]] [#v6061921]
import scala.annotation.tailrec
object Main extends App {
@tailrec
def fibs(a: Int, b: Int)(n: Int): Int =
n match {
case 0 => a
case _ => fibs(b, a + b)(n - 1)
}
val fib = fibs(0, 1) _
val n = args(0).toInt
printf("%d: %d\n", n, fib(n))
}
**[[ひらがな2文字をランダムで出力するプログラム>練習問題#...
import java.util.Random
object Main extends App {
val first = 'ぁ'.toInt
val last = 'ん'.toInt
val rnd = new Random()
def randomHiragana = Array.fill(2)((first + rnd.nextIn...
for (i <- 0 until 10) {
println(randomHiragana)
}
}
**[[配列から大きい要素とその添字を求めるプログラム>練習問...
object Main extends App {
val array = Array(12, 6, 8, 3, 10, 1, 0, 9)
array.zip(array.indices).sortBy(_._1).reverse.take(3) ...
i => printf("%d -> %d\n",i._2, i._1)
}
}
**[[累乗>練習問題#x6e30de3]] [#t3a731fd]
***課題1 [#k9aa5b74]
object Main extends App {
def pow(a: Int, n: Int): BigInt = {
var x = BigInt(1)
var i = n
while (i > 0) {
x = x * a
i -= 1
}
x
}
println(pow(2, 0))
println(pow(2, 1))
println(pow(2, 2))
println(pow(2, 10))
println(pow(2, 1024))
println(pow(2, 1000007))
}
***課題1(Stream版) [#r285d3c4]
object Main extends App {
def pow(a: Int, n: Int) = {
val x = BigInt(a)
Stream.fill(n)(x).product
}
println(pow(2, 0))
println(pow(2, 1))
println(pow(2, 2))
println(pow(2, 10))
println(pow(2, 1024))
println(pow(2, 1000007))
}
***結果 [#ef174388]
1
2
4
1024
17976931348623159077293051907890247336179769789423065727...
50096313270847732240753602112011387987139335765878976881...
47412437776789342486548527630221960124609411945308295208...
46288147391311054082723716335051068458629823994724593847...
224137216
12672839973498749760893342228866436160939039029488086186...
中略
4810776629789295701471878694639518221425715604831630000128
終了行:
*Scala解答例 [#p9ba346f]
[[練習問題]]
解答例は次の環境でテストしています
-Scala version 2.11.6
-Java(TM) SE Runtime Environment (build 1.8.0_40-b25) 64-...
-sbt 0.13.8
ほとんどの解答例は[[ideone.com:http://ideone.com/]]でその...
つっこみは[[Top>/]]の避難所まで
#contents
**[[ループ練習>練習問題#eb2c4338]] [#s1c6b422]
***問1 [#ke7969de]
object Main extends App {
for (i <- 1 to 5) {
println("Hello World!")
}
}
別解
object Main extends App {
(1 to 5) foreach { _ =>
println("Hello World!")
}
}
***問2 [#ybb0b896]
object Main extends App {
val j = args(0).toInt
for (i <- 1 to j) {
println("Hello World! " + i)
}
}
別解
object Main extends App {
val j = args(0).toInt
(1 to j) foreach { i =>
println("Hello World! " + i)
}
}
**[[FizzBuzz>練習問題#t52e5a48]] [#ga808233]
object Main extends App {
def fizzBuzz(n: Int) =
if (n % 15 == 0) {
"FizzBuzz"
} else if (n % 5 == 0) {
"Buzz"
} else if (n % 3 == 0) {
"Fizz"
} else {
n.toString
}
(1 to 100).map(fizzBuzz).foreach(println)
}
**[[素数判定>練習問題#o8db2119]] [#ldc71efe]
***判定 [#v8e35b34]
object Main extends App {
def prime(n: Int) =
2 <= n && !(2 until (math.sqrt(n) + 1.0).toInt).exis...
val n = args(0).toInt
println(n.toString + "は" + (if (prime(n)) "素数" else...
}
***列挙 [#j53b2078]
object Main extends App {
def primes(xs: Stream[Int] = Stream.from(2)): Stream[I...
xs.head #:: primes(xs.tail.filter(_ % xs.head != 0))
primes() takeWhile {
_ <= 100
} foreach {
println
}
}
**[[うるう年測定>練習問題#i0d67516]] [#xd158eb1]
import java.util.GregorianCalendar
object Main extends App {
val cal = new GregorianCalendar()
while (true) {
print("西暦を入力してください> ")
val y = readInt()
if (y <= 0) sys.exit()
printf("%dはうるう年%s\n", y,
if (cal.isLeapYear(y)) "です" else "ではありません")
}
}
**[[転置行列>練習問題#q9f27a17]] [#o9735320]
import scala.annotation.tailrec
object Main extends App {
type Mx = List[Array[String]]
@tailrec
def matrix(xs: Mx = Nil): Mx = {
val sep = """\s+""".r
val s = readLine()
if (s.length <= 0) xs else matrix(xs :+ sep.split(s))
}
matrix().transpose.foreach(x => println(x.mkString(" "...
}
**[[カレンダー出力>練習問題#i5e3e061]] [#xde7305e]
-build.sbt
name := "vipcal"
version := "1.0"
scalaVersion := "2.10.2"
libraryDependencies ++= Seq(
"org.scala-lang" % "scala-swing" % "2.10.2",
"org.swinglabs.swingx" % "swingx-core" % "1.6.5-1"
)
-Main.scala
import scala.swing._
import org.jdesktop.swingx.{JXDatePicker, JXMonthView}
import java.awt.event.{ActionEvent, ActionListener}
object Main extends SimpleSwingApplication {
override lazy val top = new MainFrame with ActionListe...
self =>
val monthView = new JXMonthView()
val datePicker = new JXDatePicker(monthView.getToday)
datePicker.addActionListener(self)
contents = new BoxPanel(Orientation.Vertical) {
contents += Component.wrap(datePicker)
contents += Component.wrap(monthView)
}
def actionPerformed(e: ActionEvent) {
val d = datePicker.getDate
monthView.setFirstDisplayedDay(d)
monthView.setFlaggedDates(d)
}
}
}
#ref(http://i.imgur.com/uAqI9dn.png,nolink,カレンダー)
**[[配列いじり>練習問題#w5561ad6]] [#ode26856]
object Main extends App {
def tailZero(xs: Array[Int]) =
xs.head +: Array.fill(xs.tail.size){ 0 }
val a = Array(3, 5, 2, 4, 2)
println(a.mkString(" "))
println(tailZero(a).mkString(" "))
}
**[[Caesar暗号解読>練習問題#h54a0395]] [#g5a75e45]
object Main extends App {
val ciphertext =
"""qdq-gi.q-a ziatmxxitmdqibtqi-ustbi ri.qmoqrcxi.qb...
|-ibtqi-qp-qaai ripmymsqkir -ibtqi-qy dmxi ri.cnxu...
|-ibtqiqzmobyqzbkii-q.qmxi -imyqzpyqzbi rixmeaki -...
|-i-qscxmbu zaimzpir -i btq-iymbbq-a;iz -iatmxximz...
|zinqiuzimzgiemgipuao-uyuzmbqpimsmuzabir -ia. za -...
val chars = """abcdefghijklmnopqrstuvwxyz .,-"""
def rot(s: String, count: Int) =
s.splitAt(s.length - count - 1) match {
case (a, b) => b + a
}
(1 until chars.length) map {
i => chars.zip(rot(chars, i)).toMap
} map {
p => ciphertext.map(c => p.getOrElse(c, c))
} filter(_.contains("person")) foreach {
println
}
}
**[[フィボナッチ数列>練習問題#p59f794f]] [#v6061921]
import scala.annotation.tailrec
object Main extends App {
@tailrec
def fibs(a: Int, b: Int)(n: Int): Int =
n match {
case 0 => a
case _ => fibs(b, a + b)(n - 1)
}
val fib = fibs(0, 1) _
val n = args(0).toInt
printf("%d: %d\n", n, fib(n))
}
**[[ひらがな2文字をランダムで出力するプログラム>練習問題#...
import java.util.Random
object Main extends App {
val first = 'ぁ'.toInt
val last = 'ん'.toInt
val rnd = new Random()
def randomHiragana = Array.fill(2)((first + rnd.nextIn...
for (i <- 0 until 10) {
println(randomHiragana)
}
}
**[[配列から大きい要素とその添字を求めるプログラム>練習問...
object Main extends App {
val array = Array(12, 6, 8, 3, 10, 1, 0, 9)
array.zip(array.indices).sortBy(_._1).reverse.take(3) ...
i => printf("%d -> %d\n",i._2, i._1)
}
}
**[[累乗>練習問題#x6e30de3]] [#t3a731fd]
***課題1 [#k9aa5b74]
object Main extends App {
def pow(a: Int, n: Int): BigInt = {
var x = BigInt(1)
var i = n
while (i > 0) {
x = x * a
i -= 1
}
x
}
println(pow(2, 0))
println(pow(2, 1))
println(pow(2, 2))
println(pow(2, 10))
println(pow(2, 1024))
println(pow(2, 1000007))
}
***課題1(Stream版) [#r285d3c4]
object Main extends App {
def pow(a: Int, n: Int) = {
val x = BigInt(a)
Stream.fill(n)(x).product
}
println(pow(2, 0))
println(pow(2, 1))
println(pow(2, 2))
println(pow(2, 10))
println(pow(2, 1024))
println(pow(2, 1000007))
}
***結果 [#ef174388]
1
2
4
1024
17976931348623159077293051907890247336179769789423065727...
50096313270847732240753602112011387987139335765878976881...
47412437776789342486548527630221960124609411945308295208...
46288147391311054082723716335051068458629823994724593847...
224137216
12672839973498749760893342228866436160939039029488086186...
中略
4810776629789295701471878694639518221425715604831630000128
ページ名: