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