| author | Christian Urban <urbanc@in.tum.de> | 
| Tue, 19 Nov 2019 06:38:10 +0000 | |
| changeset 321 | f6cb539e0ffb | 
| parent 320 | 90aed247c8cf | 
| child 323 | 93b6c16dded8 | 
| permissions | -rw-r--r-- | 
| 67 | 1 | // Scala Lecture 3 | 
| 2 | //================= | |
| 3 | ||
| 320 | 4 | // - last week | 
| 5 | // | |
| 6 | // option type | |
| 7 | // higher-order function | |
| 8 | ||
| 9 | ||
| 10 | ||
| 11 | // Recursion Again ;o) | |
| 12 | //==================== | |
| 13 | ||
| 217 | 14 | |
| 15 | // A Web Crawler / Email Harvester | |
| 16 | //================================= | |
| 17 | // | |
| 18 | // the idea is to look for links using the | |
| 19 | // regular expression "https?://[^"]*" and for | |
| 218 | 20 | // email addresses using yet another regex. | 
| 217 | 21 | |
| 22 | import io.Source | |
| 23 | import scala.util._ | |
| 155 | 24 | |
| 217 | 25 | // gets the first 10K of a web-page | 
| 26 | def get_page(url: String) : String = {
 | |
| 27 |   Try(Source.fromURL(url)("ISO-8859-1").take(10000).mkString).
 | |
| 320 | 28 |     getOrElse { println(s" Problem with: $url"); ""}
 | 
| 217 | 29 | } | 
| 155 | 30 | |
| 217 | 31 | // regex for URLs and emails | 
| 32 | val http_pattern = """"https?://[^"]*"""".r | |
| 33 | val email_pattern = """([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})""".r
 | |
| 34 | ||
| 218 | 35 | // val s = "foo bla christian@kcl.ac.uk 1234567" | 
| 36 | // email_pattern.findAllIn(s).toList | |
| 155 | 37 | |
| 217 | 38 | // drops the first and last character from a string | 
| 39 | def unquote(s: String) = s.drop(1).dropRight(1) | |
| 155 | 40 | |
| 217 | 41 | def get_all_URLs(page: String): Set[String] = | 
| 42 | http_pattern.findAllIn(page).map(unquote).toSet | |
| 155 | 43 | |
| 320 | 44 | // a naive version of crawl - searches until a given depth, | 
| 217 | 45 | // visits pages potentially more than once | 
| 320 | 46 | def crawl(url: String, n: Int) : Unit = {
 | 
| 47 | if (n == 0) () | |
| 217 | 48 |   else {
 | 
| 49 | println(s" Visiting: $n $url") | |
| 321 | 50 | val page = get_page(url) | 
| 51 | for (u <- get_all_URLs(page)) crawl(u, n - 1) | |
| 217 | 52 | } | 
| 155 | 53 | } | 
| 54 | ||
| 217 | 55 | // some starting URLs for the crawler | 
| 56 | val startURL = """https://nms.kcl.ac.uk/christian.urban/""" | |
| 320 | 57 | |
| 217 | 58 | crawl(startURL, 2) | 
| 59 | ||
| 155 | 60 | |
| 318 | 61 | |
| 320 | 62 | // a primitive email harvester | 
| 63 | def emails(url: String, n: Int) : Set[String] = {
 | |
| 64 | if (n == 0) Set() | |
| 65 |   else {
 | |
| 66 | println(s" Visiting: $n $url") | |
| 67 | val page = get_page(url) | |
| 68 | val new_emails = email_pattern.findAllIn(page).toSet | |
| 69 | new_emails ++ (for (u <- get_all_URLs(page)) yield emails(u, n - 1)).flatten | |
| 70 | } | |
| 218 | 71 | } | 
| 72 | ||
| 320 | 73 | emails(startURL, 2) | 
| 218 | 74 | |
| 75 | ||
| 320 | 76 | // if we want to explore the internet "deeper", then we | 
| 77 | // first have to parallelise the request of webpages: | |
| 78 | // | |
| 79 | // scala -cp scala-parallel-collections_2.13-0.2.0.jar | |
| 80 | // import scala.collection.parallel.CollectionConverters._ | |
| 155 | 81 | |
| 82 | ||
| 83 | ||
| 320 | 84 | // another well-known example | 
| 85 | //============================ | |
| 178 | 86 | |
| 320 | 87 | def move(from: Char, to: Char) = | 
| 88 | println(s"Move disc from $from to $to!") | |
| 67 | 89 | |
| 320 | 90 | def hanoi(n: Int, from: Char, via: Char, to: Char) : Unit = {
 | 
| 91 | if (n == 0) () | |
| 92 |   else {
 | |
| 93 | hanoi(n - 1, from, to, via) | |
| 94 | move(from, to) | |
| 95 | hanoi(n - 1, via, from, to) | |
| 96 | } | |
| 97 | } | |
| 67 | 98 | |
| 320 | 99 | hanoi(4, 'A', 'B', 'C') | 
| 67 | 100 | |
| 155 | 101 | |
| 102 | ||
| 217 | 103 | // Jumping Towers | 
| 104 | //================ | |
| 105 | ||
| 106 | ||
| 107 | // the first n prefixes of xs | |
| 108 | // for 1 => include xs | |
| 109 | ||
| 110 | def moves(xs: List[Int], n: Int) : List[List[Int]] = (xs, n) match {
 | |
| 111 | case (Nil, _) => Nil | |
| 112 | case (xs, 0) => Nil | |
| 113 | case (x::xs, n) => (x::xs) :: moves(xs, n - 1) | |
| 114 | } | |
| 115 | ||
| 116 | ||
| 117 | moves(List(5,1,0), 1) | |
| 118 | moves(List(5,1,0), 2) | |
| 119 | moves(List(5,1,0), 5) | |
| 120 | ||
| 121 | // checks whether a jump tour exists at all | |
| 122 | ||
| 123 | def search(xs: List[Int]) : Boolean = xs match {
 | |
| 124 | case Nil => true | |
| 321 | 125 | case x::xs => | 
| 126 | if (xs.length < x) true | |
| 127 | else moves(xs, x).exists(search(_)) | |
| 217 | 128 | } | 
| 129 | ||
| 130 | ||
| 131 | search(List(5,3,2,5,1,1)) | |
| 132 | search(List(3,5,1,0,0,0,1)) | |
| 133 | search(List(3,5,1,0,0,0,0,1)) | |
| 134 | search(List(3,5,1,0,0,0,1,1)) | |
| 135 | search(List(3,5,1)) | |
| 136 | search(List(5,1,1)) | |
| 137 | search(Nil) | |
| 138 | search(List(1)) | |
| 139 | search(List(5,1,1)) | |
| 140 | search(List(3,5,1,0,0,0,0,0,0,0,0,1)) | |
| 141 | ||
| 142 | // generates *all* jump tours | |
| 321 | 143 | // if we are only interested in the shortest one, we could | 
| 217 | 144 | // shortcircut the calculation and only return List(x) in | 
| 145 | // case where xs.length < x, because no tour can be shorter | |
| 146 | // than 1 | |
| 147 | // | |
| 148 | ||
| 149 | def jumps(xs: List[Int]) : List[List[Int]] = xs match {
 | |
| 150 | case Nil => Nil | |
| 321 | 151 |   case x::xs => {
 | 
| 217 | 152 | val children = moves(xs, x) | 
| 320 | 153 | val results = children.map(cs => jumps(cs).map(x :: _)).flatten | 
| 154 | if (xs.length < x) List(x)::results else results | |
| 217 | 155 | } | 
| 156 | } | |
| 157 | ||
| 320 | 158 | jumps(List(5,3,2,5,1,1)).minBy(_.length) | 
| 217 | 159 | jumps(List(3,5,1,2,1,2,1)) | 
| 160 | jumps(List(3,5,1,2,3,4,1)) | |
| 161 | jumps(List(3,5,1,0,0,0,1)) | |
| 162 | jumps(List(3,5,1)) | |
| 163 | jumps(List(5,1,1)) | |
| 164 | jumps(Nil) | |
| 165 | jumps(List(1)) | |
| 166 | jumps(List(5,1,2)) | |
| 167 | moves(List(1,2), 5) | |
| 168 | jumps(List(1,5,1,2)) | |
| 169 | jumps(List(3,5,1,0,0,0,0,0,0,0,0,1)) | |
| 170 | ||
| 171 | jumps(List(5,3,2,5,1,1)).minBy(_.length) | |
| 172 | jumps(List(1,3,5,8,9,2,6,7,6,8,9)).minBy(_.length) | |
| 173 | jumps(List(1,3,6,1,0,9)).minBy(_.length) | |
| 174 | jumps(List(2,3,1,1,2,4,2,0,1,1)).minBy(_.length) | |
| 175 | ||
| 176 | ||
| 177 | ||
| 318 | 178 | |
| 179 | ||
| 180 | ||
| 320 | 181 | // User-defined Datatypes | 
| 182 | //======================== | |
| 183 | ||
| 184 | ||
| 321 | 185 | sealed abstract class Colour | 
| 320 | 186 | case object Red extends Colour | 
| 187 | case object Green extends Colour | |
| 188 | case object Blue extends Colour | |
| 189 | ||
| 190 | ||
| 191 | def fav_colour(c: Colour) : Boolean = c match {
 | |
| 192 | case Red => false | |
| 193 | case Green => true | |
| 194 | case Blue => false | |
| 195 | } | |
| 196 | ||
| 197 | fav_colour(Green) | |
| 198 | ||
| 199 | // ... a tiny bit more useful: Roman Numerals | |
| 200 | ||
| 321 | 201 | sealed abstract class RomanDigit | 
| 320 | 202 | case object I extends RomanDigit | 
| 203 | case object V extends RomanDigit | |
| 204 | case object X extends RomanDigit | |
| 205 | case object L extends RomanDigit | |
| 206 | case object C extends RomanDigit | |
| 207 | case object D extends RomanDigit | |
| 208 | case object M extends RomanDigit | |
| 209 | ||
| 210 | type RomanNumeral = List[RomanDigit] | |
| 211 | ||
| 212 | List(X,I) | |
| 213 | ||
| 214 | /* | |
| 215 | I -> 1 | |
| 216 | II -> 2 | |
| 217 | III -> 3 | |
| 218 | IV -> 4 | |
| 219 | V -> 5 | |
| 220 | VI -> 6 | |
| 221 | VII -> 7 | |
| 222 | VIII -> 8 | |
| 223 | IX -> 9 | |
| 224 | X -> 10 | |
| 225 | */ | |
| 226 | ||
| 227 | def RomanNumeral2Int(rs: RomanNumeral): Int = rs match { 
 | |
| 228 | case Nil => 0 | |
| 229 | case M::r => 1000 + RomanNumeral2Int(r) | |
| 230 | case C::M::r => 900 + RomanNumeral2Int(r) | |
| 231 | case D::r => 500 + RomanNumeral2Int(r) | |
| 232 | case C::D::r => 400 + RomanNumeral2Int(r) | |
| 233 | case C::r => 100 + RomanNumeral2Int(r) | |
| 234 | case X::C::r => 90 + RomanNumeral2Int(r) | |
| 235 | case L::r => 50 + RomanNumeral2Int(r) | |
| 236 | case X::L::r => 40 + RomanNumeral2Int(r) | |
| 237 | case X::r => 10 + RomanNumeral2Int(r) | |
| 238 | case I::X::r => 9 + RomanNumeral2Int(r) | |
| 239 | case V::r => 5 + RomanNumeral2Int(r) | |
| 240 | case I::V::r => 4 + RomanNumeral2Int(r) | |
| 241 | case I::r => 1 + RomanNumeral2Int(r) | |
| 242 | } | |
| 243 | ||
| 244 | RomanNumeral2Int(List(I,V)) // 4 | |
| 245 | RomanNumeral2Int(List(I,I,I,I)) // 4 (invalid Roman number) | |
| 246 | RomanNumeral2Int(List(V,I)) // 6 | |
| 247 | RomanNumeral2Int(List(I,X)) // 9 | |
| 248 | RomanNumeral2Int(List(M,C,M,L,X,X,I,X)) // 1979 | |
| 249 | RomanNumeral2Int(List(M,M,X,V,I,I)) // 2017 | |
| 250 | ||
| 251 | ||
| 252 | // String interpolations as patterns | |
| 253 | ||
| 254 | val date = "2019-11-26" | |
| 255 | val s"$year-$month-$day" = date | |
| 256 | ||
| 257 | def parse_date(date: String) : Option[(Int, Int, Int)]= date match {
 | |
| 258 | case s"$year-$month-$day" => Some((day.toInt, month.toInt, year.toInt)) | |
| 259 | case s"$day/$month/$year" => Some((day.toInt, month.toInt, year.toInt)) | |
| 260 | case s"$day.$month.$year" => Some((day.toInt, month.toInt, year.toInt)) | |
| 261 | case _ => None | |
| 262 | } | |
| 318 | 263 | |
| 320 | 264 | parse_date("2019-11-26")
 | 
| 265 | parse_date("26/11/2019")
 | |
| 266 | parse_date("26.11.2019")
 | |
| 267 | ||
| 268 | ||
| 269 | // User-defined Datatypes and Pattern Matching | |
| 270 | //============================================= | |
| 271 | ||
| 272 | // trees | |
| 273 | ||
| 321 | 274 | sealed abstract class Exp | 
| 320 | 275 | case class N(n: Int) extends Exp // for numbers | 
| 276 | case class Plus(e1: Exp, e2: Exp) extends Exp | |
| 277 | case class Times(e1: Exp, e2: Exp) extends Exp | |
| 278 | ||
| 279 | def string(e: Exp) : String = e match {
 | |
| 280 | case N(n) => s"$n" | |
| 281 |   case Plus(e1, e2) => s"(${string(e1)} + ${string(e2)})" 
 | |
| 282 |   case Times(e1, e2) => s"(${string(e1)} * ${string(e2)})"
 | |
| 283 | } | |
| 284 | ||
| 285 | val e = Plus(N(9), Times(N(3), N(4))) | |
| 286 | println(string(e)) | |
| 287 | ||
| 288 | def eval(e: Exp) : Int = e match {
 | |
| 289 | case N(n) => n | |
| 290 | case Plus(e1, e2) => eval(e1) + eval(e2) | |
| 291 | case Times(e1, e2) => eval(e1) * eval(e2) | |
| 292 | } | |
| 293 | ||
| 294 | println(eval(e)) | |
| 295 | ||
| 296 | def simp(e: Exp) : Exp = e match {
 | |
| 297 | case N(n) => N(n) | |
| 298 |   case Plus(e1, e2) => (simp(e1), simp(e2)) match {
 | |
| 299 | case (N(0), e2s) => e2s | |
| 300 | case (e1s, N(0)) => e1s | |
| 301 | case (e1s, e2s) => Plus(e1s, e2s) | |
| 302 | } | |
| 303 |   case Times(e1, e2) => (simp(e1), simp(e2)) match {
 | |
| 304 | case (N(0), _) => N(0) | |
| 305 | case (_, N(0)) => N(0) | |
| 306 | case (N(1), e2s) => e2s | |
| 307 | case (e1s, N(1)) => e1s | |
| 308 | case (e1s, e2s) => Times(e1s, e2s) | |
| 309 | } | |
| 310 | } | |
| 311 | ||
| 312 | ||
| 313 | val e2 = Times(Plus(N(0), N(1)), Plus(N(0), N(9))) | |
| 314 | println(string(e2)) | |
| 315 | println(string(simp(e2))) | |
| 316 | ||
| 317 | ||
| 318 | // Tokens and Reverse Polish Notation | |
| 321 | 319 | sealed abstract class Token | 
| 320 | 320 | case class T(n: Int) extends Token | 
| 321 | case object PL extends Token | |
| 322 | case object TI extends Token | |
| 323 | ||
| 324 | def rp(e: Exp) : List[Token] = e match {
 | |
| 325 | case N(n) => List(T(n)) | |
| 326 | case Plus(e1, e2) => rp(e1) ::: rp(e2) ::: List(PL) | |
| 327 | case Times(e1, e2) => rp(e1) ::: rp(e2) ::: List(TI) | |
| 328 | } | |
| 329 | println(string(e2)) | |
| 330 | println(rp(e2)) | |
| 331 | ||
| 332 | def comp(ls: List[Token], st: List[Int]) : Int = (ls, st) match {
 | |
| 333 | case (Nil, st) => st.head | |
| 334 | case (T(n)::rest, st) => comp(rest, n::st) | |
| 335 | case (PL::rest, n1::n2::st) => comp(rest, n1 + n2::st) | |
| 336 | case (TI::rest, n1::n2::st) => comp(rest, n1 * n2::st) | |
| 337 | } | |
| 338 | ||
| 339 | comp(rp(e), Nil) | |
| 340 | ||
| 341 | def proc(s: String) : Token = s match {
 | |
| 342 | case "+" => PL | |
| 343 | case "*" => TI | |
| 344 | case _ => T(s.toInt) | |
| 345 | } | |
| 346 | ||
| 347 | comp("1 2 + 4 * 5 + 3 +".split(" ").toList.map(proc), Nil)
 | |
| 217 | 348 | |
| 349 | ||
| 350 | ||
| 351 | ||
| 352 | // Sudoku | |
| 353 | //======== | |
| 354 | ||
| 355 | // THE POINT OF THIS CODE IS NOT TO BE SUPER | |
| 356 | // EFFICIENT AND FAST, just explaining exhaustive | |
| 357 | // depth-first search | |
| 358 | ||
| 155 | 359 | |
| 360 | val game0 = """.14.6.3.. | |
| 361 | |62...4..9 | |
| 362 | |.8..5.6.. | |
| 363 | |.6.2....3 | |
| 364 | |.7..1..5. | |
| 365 | |5....9.6. | |
| 366 | |..6.2..3. | |
| 367 | |1..5...92 | |
| 368 |               |..7.9.41.""".stripMargin.replaceAll("\\n", "")
 | |
| 53 | 369 | |
| 155 | 370 | type Pos = (Int, Int) | 
| 371 | val EmptyValue = '.' | |
| 372 | val MaxValue = 9 | |
| 373 | ||
| 374 | val allValues = "123456789".toList | |
| 375 | val indexes = (0 to 8).toList | |
| 376 | ||
| 377 | ||
| 378 | def empty(game: String) = game.indexOf(EmptyValue) | |
| 379 | def isDone(game: String) = empty(game) == -1 | |
| 380 | def emptyPosition(game: String) = | |
| 381 | (empty(game) % MaxValue, empty(game) / MaxValue) | |
| 382 | ||
| 67 | 383 | |
| 155 | 384 | def get_row(game: String, y: Int) = | 
| 385 | indexes.map(col => game(y * MaxValue + col)) | |
| 386 | def get_col(game: String, x: Int) = | |
| 387 | indexes.map(row => game(x + row * MaxValue)) | |
| 388 | ||
| 389 | def get_box(game: String, pos: Pos): List[Char] = {
 | |
| 390 | def base(p: Int): Int = (p / 3) * 3 | |
| 391 | val x0 = base(pos._1) | |
| 392 | val y0 = base(pos._2) | |
| 393 | val ys = (y0 until y0 + 3).toList | |
| 394 | (x0 until x0 + 3).toList.flatMap(x => ys.map(y => game(x + y * MaxValue))) | |
| 395 | } | |
| 396 | ||
| 217 | 397 | //get_row(game0, 0) | 
| 398 | //get_row(game0, 1) | |
| 218 | 399 | //get_col(game0, 0) | 
| 400 | //get_box(game0, (3, 1)) | |
| 217 | 401 | |
| 402 | ||
| 155 | 403 | // this is not mutable!! | 
| 404 | def update(game: String, pos: Int, value: Char): String = | |
| 405 | game.updated(pos, value) | |
| 406 | ||
| 407 | def toAvoid(game: String, pos: Pos): List[Char] = | |
| 408 | (get_col(game, pos._1) ++ get_row(game, pos._2) ++ get_box(game, pos)) | |
| 409 | ||
| 410 | def candidates(game: String, pos: Pos): List[Char] = | |
| 218 | 411 | allValues.diff(toAvoid(game, pos)) | 
| 155 | 412 | |
| 413 | //candidates(game0, (0,0)) | |
| 414 | ||
| 415 | def pretty(game: String): String = | |
| 218 | 416 |   "\n" + (game.sliding(MaxValue, MaxValue).mkString("\n"))
 | 
| 155 | 417 | |
| 218 | 418 | |
| 155 | 419 | def search(game: String): List[String] = {
 | 
| 420 | if (isDone(game)) List(game) | |
| 421 |   else {
 | |
| 422 | val cs = candidates(game, emptyPosition(game)) | |
| 320 | 423 | cs.map(c => search(update(game, empty(game), c))).toList.flatten | 
| 67 | 424 | } | 
| 425 | } | |
| 426 | ||
| 217 | 427 | search(game0).map(pretty) | 
| 428 | ||
| 429 | val game1 = """23.915... | |
| 430 | |...2..54. | |
| 431 | |6.7...... | |
| 432 | |..1.....9 | |
| 433 | |89.5.3.17 | |
| 434 | |5.....6.. | |
| 435 | |......9.5 | |
| 436 | |.16..7... | |
| 437 |               |...329..1""".stripMargin.replaceAll("\\n", "")
 | |
| 438 | ||
| 439 | ||
| 440 | // game that is in the hard category | |
| 441 | val game2 = """8........ | |
| 442 | |..36..... | |
| 443 | |.7..9.2.. | |
| 444 | |.5...7... | |
| 445 | |....457.. | |
| 446 | |...1...3. | |
| 447 | |..1....68 | |
| 448 | |..85...1. | |
| 449 |               |.9....4..""".stripMargin.replaceAll("\\n", "")
 | |
| 450 | ||
| 451 | // game with multiple solutions | |
| 452 | val game3 = """.8...9743 | |
| 453 | |.5...8.1. | |
| 454 | |.1....... | |
| 455 | |8....5... | |
| 456 | |...8.4... | |
| 457 | |...3....6 | |
| 458 | |.......7. | |
| 459 | |.3.5...8. | |
| 460 |               |9724...5.""".stripMargin.replaceAll("\\n", "")
 | |
| 461 | ||
| 462 | ||
| 463 | search(game1).map(pretty) | |
| 464 | search(game3).map(pretty) | |
| 465 | search(game2).map(pretty) | |
| 466 | ||
| 467 | // for measuring time | |
| 468 | def time_needed[T](i: Int, code: => T) = {
 | |
| 469 | val start = System.nanoTime() | |
| 470 | for (j <- 1 to i) code | |
| 471 | val end = System.nanoTime() | |
| 472 | ((end - start) / 1.0e9) + " secs" | |
| 473 | } | |
| 474 | ||
| 475 | time_needed(1, search(game2)) | |
| 476 | ||
| 320 | 477 | |
| 478 | ||
| 479 | ||
| 480 | // Tail recursion | |
| 481 | //================ | |
| 482 | ||
| 483 | ||
| 484 | def fact(n: Long): Long = | |
| 485 | if (n == 0) 1 else n * fact(n - 1) | |
| 486 | ||
| 487 | def factB(n: BigInt): BigInt = | |
| 488 | if (n == 0) 1 else n * factB(n - 1) | |
| 489 | ||
| 490 | factB(100000) | |
| 491 | ||
| 492 | fact(10) //ok | |
| 493 | fact(10000) // produces a stackoverflow | |
| 494 | ||
| 495 | def factT(n: BigInt, acc: BigInt): BigInt = | |
| 496 | if (n == 0) acc else factT(n - 1, n * acc) | |
| 497 | ||
| 498 | factT(10, 1) | |
| 499 | println(factT(100000, 1)) | |
| 500 | ||
| 501 | // there is a flag for ensuring a function is tail recursive | |
| 502 | import scala.annotation.tailrec | |
| 503 | ||
| 504 | @tailrec | |
| 505 | def factT(n: BigInt, acc: BigInt): BigInt = | |
| 506 | if (n == 0) acc else factT(n - 1, n * acc) | |
| 507 | ||
| 508 | ||
| 509 | ||
| 510 | // for tail-recursive functions the Scala compiler | |
| 511 | // generates loop-like code, which does not need | |
| 512 | // to allocate stack-space in each recursive | |
| 513 | // call; Scala can do this only for tail-recursive | |
| 514 | // functions | |
| 515 | ||
| 155 | 516 | // tail recursive version that searches | 
| 158 | 517 | // for all solutions | 
| 518 | ||
| 155 | 519 | def searchT(games: List[String], sols: List[String]): List[String] = games match {
 | 
| 520 | case Nil => sols | |
| 521 |   case game::rest => {
 | |
| 522 | if (isDone(game)) searchT(rest, game::sols) | |
| 523 |     else {
 | |
| 524 | val cs = candidates(game, emptyPosition(game)) | |
| 525 | searchT(cs.map(c => update(game, empty(game), c)) ::: rest, sols) | |
| 526 | } | |
| 527 | } | |
| 67 | 528 | } | 
| 529 | ||
| 158 | 530 | searchT(List(game3), List()).map(pretty) | 
| 531 | ||
| 532 | ||
| 155 | 533 | // tail recursive version that searches | 
| 534 | // for a single solution | |
| 158 | 535 | |
| 155 | 536 | def search1T(games: List[String]): Option[String] = games match {
 | 
| 67 | 537 | case Nil => None | 
| 155 | 538 |   case game::rest => {
 | 
| 539 | if (isDone(game)) Some(game) | |
| 540 |     else {
 | |
| 541 | val cs = candidates(game, emptyPosition(game)) | |
| 542 | search1T(cs.map(c => update(game, empty(game), c)) ::: rest) | |
| 543 | } | |
| 544 | } | |
| 67 | 545 | } | 
| 546 | ||
| 158 | 547 | search1T(List(game3)).map(pretty) | 
| 217 | 548 | time_needed(10, search1T(List(game3))) | 
| 549 | ||
| 158 | 550 | |
| 155 | 551 | // game with multiple solutions | 
| 552 | val game3 = """.8...9743 | |
| 553 | |.5...8.1. | |
| 554 | |.1....... | |
| 555 | |8....5... | |
| 556 | |...8.4... | |
| 557 | |...3....6 | |
| 558 | |.......7. | |
| 559 | |.3.5...8. | |
| 560 |               |9724...5.""".stripMargin.replaceAll("\\n", "")
 | |
| 561 | ||
| 158 | 562 | searchT(List(game3), Nil).map(pretty) | 
| 155 | 563 | search1T(List(game3)).map(pretty) | 
| 67 | 564 | |
| 77 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 565 | // Moral: Whenever a recursive function is resource-critical | 
| 158 | 566 | // (i.e. works with large recursion depth), then you need to | 
| 77 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 567 | // write it in tail-recursive fashion. | 
| 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 568 | // | 
| 155 | 569 | // Unfortuantely, Scala because of current limitations in | 
| 570 | // the JVM is not as clever as other functional languages. It can | |
| 77 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 571 | // only optimise "self-tail calls". This excludes the cases of | 
| 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 572 | // multiple functions making tail calls to each other. Well, | 
| 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 573 | // nothing is perfect. | 
| 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 574 | |
| 
3cbe3d90b77f
updated
 Christian Urban <christian dot urban at kcl dot ac dot uk> parents: 
73diff
changeset | 575 | |
| 67 | 576 | |
| 577 | ||
| 71 | 578 | |
| 67 | 579 |