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