51
|
1 |
// Scala Lecture 2
|
|
2 |
//=================
|
363
|
3 |
|
471
|
4 |
// - Options
|
|
5 |
// - Higher-Order Functions (short-hand notation)
|
|
6 |
// - maps (behind for-comprehensions)
|
|
7 |
// - Pattern-Matching
|
|
8 |
// - Recursion
|
361
|
9 |
|
316
|
10 |
// The Option Type
|
|
11 |
//=================
|
|
12 |
|
361
|
13 |
// in Java, if something unusually happens, you return null
|
|
14 |
// or raise an exception
|
316
|
15 |
//
|
|
16 |
//in Scala you use Options instead
|
|
17 |
// - if the value is present, you use Some(value)
|
|
18 |
// - if no value is present, you use None
|
204
|
19 |
|
|
20 |
|
316
|
21 |
List(7,2,3,4,5,6).find(_ < 4)
|
|
22 |
List(5,6,7,8,9).find(_ < 4)
|
212
|
23 |
|
361
|
24 |
// Int: ..., 0, 1, 2,...
|
|
25 |
// Boolean: true false
|
|
26 |
//
|
|
27 |
// List[Int]: Nil, List(_)
|
|
28 |
//
|
|
29 |
// Option[Int]: None, Some(0), Some(1), ...
|
447
|
30 |
// Option[Boolean]: None, Some(true), Some(false)
|
361
|
31 |
// Option[...]: None, Some(_)
|
|
32 |
|
|
33 |
def safe_div(x: Int, y: Int) : Option[Int] =
|
|
34 |
if (y == 0) None else Some(x / y)
|
|
35 |
|
447
|
36 |
safe_div(10 + 5, 4 - 1)
|
361
|
37 |
|
447
|
38 |
List(1,2,3,4,5,6).indexOf(7)
|
471
|
39 |
List[Int]().min
|
447
|
40 |
List[Int]().minOption
|
|
41 |
|
|
42 |
def my_min(ls: List[Int]) : Option[Int] =
|
|
43 |
ls.minOption
|
361
|
44 |
|
|
45 |
my_min(List(1,2,3,4))
|
|
46 |
|
310
|
47 |
|
316
|
48 |
// better error handling with Options (no exceptions)
|
|
49 |
//
|
|
50 |
// Try(something).getOrElse(what_to_do_in_case_of_an_exception)
|
204
|
51 |
//
|
316
|
52 |
|
471
|
53 |
import scala.util._ // Try,...
|
|
54 |
import io.Source // fromURL
|
316
|
55 |
|
447
|
56 |
val my_url = "https://nms.kcl.ac.uk/christian.urban/"
|
316
|
57 |
|
361
|
58 |
Source.fromURL(my_url)("ISO-8859-1").mkString
|
447
|
59 |
Source.fromURL(my_url)("ISO-8859-1").getLines().toList
|
316
|
60 |
|
361
|
61 |
Try(Source.fromURL(my_url)("ISO-8859-1").mkString).getOrElse("")
|
316
|
62 |
|
361
|
63 |
Try(Some(Source.fromURL(my_url)("ISO-8859-1").mkString)).getOrElse(None)
|
204
|
64 |
|
|
65 |
|
316
|
66 |
// the same for files
|
447
|
67 |
|
361
|
68 |
Try(Some(Source.fromFile("test.txt")("ISO-8859-1").mkString)).getOrElse(None)
|
316
|
69 |
|
447
|
70 |
Try(Source.fromFile("test.txt")("ISO-8859-1").mkString).toOption
|
|
71 |
|
|
72 |
Using(Source.fromFile("test.txt")("ISO-8859-1"))(_.mkString).toOption
|
204
|
73 |
|
319
|
74 |
// how to implement a function for reading
|
447
|
75 |
// (lines) from files...
|
319
|
76 |
//
|
316
|
77 |
def get_contents(name: String) : List[String] =
|
447
|
78 |
Source.fromFile(name)("ISO-8859-1").getLines().toList
|
204
|
79 |
|
319
|
80 |
get_contents("text.txt")
|
316
|
81 |
get_contents("test.txt")
|
204
|
82 |
|
316
|
83 |
// slightly better - return Nil
|
|
84 |
def get_contents(name: String) : List[String] =
|
361
|
85 |
Try(Source.fromFile(name)("ISO-8859-1").getLines.toList).getOrElse(List())
|
204
|
86 |
|
316
|
87 |
get_contents("text.txt")
|
204
|
88 |
|
316
|
89 |
// much better - you record in the type that things can go wrong
|
|
90 |
def get_contents(name: String) : Option[List[String]] =
|
447
|
91 |
Try(Some(Source.fromFile(name)("ISO-8859-1").getLines().toList)).getOrElse(None)
|
204
|
92 |
|
316
|
93 |
get_contents("text.txt")
|
|
94 |
get_contents("test.txt")
|
204
|
95 |
|
|
96 |
|
317
|
97 |
// operations on options
|
204
|
98 |
|
317
|
99 |
val lst = List(None, Some(1), Some(2), None, Some(3))
|
204
|
100 |
|
317
|
101 |
lst.flatten
|
204
|
102 |
|
317
|
103 |
Some(1).get
|
|
104 |
None.get
|
310
|
105 |
|
317
|
106 |
Some(1).isDefined
|
|
107 |
None.isDefined
|
310
|
108 |
|
361
|
109 |
for (x <- lst) yield x.getOrElse(0)
|
310
|
110 |
|
361
|
111 |
|
|
112 |
|
|
113 |
val ps = List((3, 0), (4, 2), (6, 2),
|
|
114 |
(2, 0), (1, 0), (1, 1))
|
317
|
115 |
|
|
116 |
// division where possible
|
|
117 |
|
|
118 |
for ((x, y) <- ps) yield {
|
|
119 |
if (y == 0) None else Some(x / y)
|
|
120 |
}
|
|
121 |
|
361
|
122 |
|
|
123 |
|
317
|
124 |
// getOrElse is for setting a default value
|
|
125 |
|
|
126 |
val lst = List(None, Some(1), Some(2), None, Some(3))
|
|
127 |
|
361
|
128 |
|
|
129 |
// a function that turns strings into numbers
|
|
130 |
// (similar to .toInt)
|
|
131 |
Integer.parseInt("1234")
|
318
|
132 |
|
|
133 |
|
|
134 |
def get_me_an_int(s: String) : Option[Int] =
|
|
135 |
Try(Some(Integer.parseInt(s))).getOrElse(None)
|
310
|
136 |
|
|
137 |
|
317
|
138 |
// This may not look any better than working with null in Java, but to
|
|
139 |
// see the value, you have to put yourself in the shoes of the
|
|
140 |
// consumer of the get_me_an_int function, and imagine you didn't
|
|
141 |
// write that function.
|
|
142 |
//
|
|
143 |
// In Java, if you didn't write this function, you'd have to depend on
|
|
144 |
// the Javadoc of the get_me_an_int. If you didn't look at the Javadoc,
|
318
|
145 |
// you might not know that get_me_an_int could return null, and your
|
317
|
146 |
// code could potentially throw a NullPointerException.
|
310
|
147 |
|
|
148 |
|
317
|
149 |
// even Scala is not immune to problems like this:
|
310
|
150 |
|
317
|
151 |
List(5,6,7,8,9).indexOf(7)
|
|
152 |
List(5,6,7,8,9).indexOf(10)
|
|
153 |
List(5,6,7,8,9)(-1)
|
310
|
154 |
|
|
155 |
|
320
|
156 |
Try({
|
|
157 |
val x = 3
|
|
158 |
val y = 0
|
|
159 |
Some(x / y)
|
|
160 |
}).getOrElse(None)
|
204
|
161 |
|
323
|
162 |
|
|
163 |
// minOption
|
|
164 |
// maxOption
|
|
165 |
// minByOption
|
|
166 |
// maxByOption
|
|
167 |
|
204
|
168 |
// Higher-Order Functions
|
|
169 |
//========================
|
|
170 |
|
|
171 |
// functions can take functions as arguments
|
319
|
172 |
// and produce functions as result
|
204
|
173 |
|
|
174 |
def even(x: Int) : Boolean = x % 2 == 0
|
|
175 |
def odd(x: Int) : Boolean = x % 2 == 1
|
|
176 |
|
|
177 |
val lst = (1 to 10).toList
|
|
178 |
|
|
179 |
lst.filter(even)
|
320
|
180 |
lst.count(odd)
|
212
|
181 |
lst.find(even)
|
320
|
182 |
lst.exists(even)
|
212
|
183 |
|
362
|
184 |
lst.find(_ < 4)
|
320
|
185 |
lst.filter(_ < 4)
|
362
|
186 |
|
|
187 |
def less4(x: Int) : Boolean = x < 4
|
|
188 |
lst.find(less4)
|
|
189 |
lst.find(_ < 4)
|
|
190 |
|
|
191 |
lst.filter(x => x % 2 == 0)
|
318
|
192 |
lst.filter(_ % 2 == 0)
|
204
|
193 |
|
320
|
194 |
|
362
|
195 |
lst.sortWith((x, y) => x < y)
|
|
196 |
lst.sortWith(_ > _)
|
204
|
197 |
|
318
|
198 |
// but this only works when the arguments are clear, but
|
|
199 |
// not with multiple occurences
|
|
200 |
lst.find(n => odd(n) && n > 2)
|
|
201 |
|
|
202 |
|
447
|
203 |
// lexicographic ordering
|
362
|
204 |
val ps = List((3, 0), (3, 2), (4, 2), (2, 2),
|
|
205 |
(2, 0), (1, 1), (1, 0))
|
318
|
206 |
|
212
|
207 |
def lex(x: (Int, Int), y: (Int, Int)) : Boolean =
|
|
208 |
if (x._1 == y._1) x._2 < y._2 else x._1 < y._1
|
|
209 |
|
|
210 |
ps.sortWith(lex)
|
204
|
211 |
|
320
|
212 |
ps.sortBy(x => x._1)
|
204
|
213 |
ps.sortBy(_._2)
|
|
214 |
|
|
215 |
ps.maxBy(_._1)
|
|
216 |
ps.maxBy(_._2)
|
|
217 |
|
|
218 |
|
212
|
219 |
// maps (lower-case)
|
|
220 |
//===================
|
204
|
221 |
|
212
|
222 |
def double(x: Int): Int = x + x
|
204
|
223 |
def square(x: Int): Int = x * x
|
|
224 |
|
|
225 |
val lst = (1 to 10).toList
|
|
226 |
|
362
|
227 |
lst.map(square)
|
212
|
228 |
lst.map(x => (double(x), square(x)))
|
|
229 |
|
362
|
230 |
// works also for strings
|
|
231 |
def tweet(c: Char) = c.toUpper
|
|
232 |
|
|
233 |
"Hello World".map(tweet)
|
|
234 |
|
|
235 |
|
|
236 |
// this can be iterated
|
|
237 |
|
|
238 |
lst.map(square).filter(_ > 4)
|
|
239 |
|
363
|
240 |
lst.map(square).find(_ > 4)
|
|
241 |
lst.map(square).find(_ > 4).map(double)
|
|
242 |
|
|
243 |
lst.map(square)
|
362
|
244 |
.find(_ > 4)
|
363
|
245 |
.map(double)
|
|
246 |
|
|
247 |
|
|
248 |
// Option Type and maps
|
|
249 |
//======================
|
|
250 |
|
|
251 |
// a function that turns strings into numbers (similar to .toInt)
|
|
252 |
Integer.parseInt("12u34")
|
|
253 |
|
|
254 |
// maps on Options
|
|
255 |
|
|
256 |
import scala.util._
|
362
|
257 |
|
363
|
258 |
def get_me_an_int(s: String) : Option[Int] =
|
|
259 |
Try(Some(Integer.parseInt(s))).getOrElse(None)
|
|
260 |
|
|
261 |
get_me_an_int("12345").map(_ % 2 == 0)
|
|
262 |
get_me_an_int("12u34").map(_ % 2 == 0)
|
|
263 |
|
|
264 |
|
|
265 |
|
|
266 |
val lst = List("12345", "foo", "5432", "bar", "x21", "456")
|
|
267 |
for (x <- lst) yield get_me_an_int(x)
|
|
268 |
|
|
269 |
// summing up all the numbers
|
|
270 |
|
|
271 |
lst.map(get_me_an_int).flatten.sum
|
|
272 |
|
|
273 |
|
|
274 |
|
204
|
275 |
|
319
|
276 |
// this is actually how for-comprehensions are
|
|
277 |
// defined in Scala
|
204
|
278 |
|
|
279 |
lst.map(n => square(n))
|
|
280 |
for (n <- lst) yield square(n)
|
|
281 |
|
318
|
282 |
// lets define our own higher-order functions
|
|
283 |
// type of functions is for example Int => Int
|
204
|
284 |
|
212
|
285 |
|
363
|
286 |
def my_map_int(lst: List[Int], f: Int => Int) : List[Int] =
|
|
287 |
{
|
204
|
288 |
if (lst == Nil) Nil
|
|
289 |
else f(lst.head) :: my_map_int(lst.tail, f)
|
|
290 |
}
|
|
291 |
|
|
292 |
my_map_int(lst, square)
|
|
293 |
|
|
294 |
// same function using pattern matching: a kind
|
|
295 |
// of switch statement on steroids (see more later on)
|
|
296 |
|
319
|
297 |
def my_map_int(lst: List[Int], f: Int => Int) : List[Int] =
|
362
|
298 |
lst match {
|
|
299 |
case Nil => Nil
|
|
300 |
case x::xs => f(x)::my_map_int(xs, f)
|
|
301 |
}
|
204
|
302 |
|
|
303 |
|
363
|
304 |
|
|
305 |
val biglst = (1 to 10000).toList
|
|
306 |
my_map_int(biglst, double)
|
|
307 |
|
|
308 |
(1 to 10000000).toList.map(double)
|
|
309 |
|
204
|
310 |
// other function types
|
|
311 |
//
|
|
312 |
// f1: (Int, Int) => Int
|
|
313 |
// f2: List[String] => Option[Int]
|
|
314 |
// ...
|
|
315 |
|
|
316 |
|
320
|
317 |
|
204
|
318 |
|
|
319 |
|
212
|
320 |
// Map type (upper-case)
|
|
321 |
//=======================
|
204
|
322 |
|
|
323 |
// Note the difference between map and Map
|
|
324 |
|
364
|
325 |
val m = Map(1 -> "one", 2 -> "two", 10 -> "many")
|
320
|
326 |
|
364
|
327 |
List((1, "one"), (2, "two"), (10, "many")).toMap
|
320
|
328 |
|
364
|
329 |
m.get(1)
|
|
330 |
m.get(4)
|
204
|
331 |
|
364
|
332 |
m.getOrElse(1, "")
|
|
333 |
m.getOrElse(4, "")
|
204
|
334 |
|
364
|
335 |
val new_m = m + (10 -> "ten")
|
204
|
336 |
|
364
|
337 |
new_m.get(10)
|
|
338 |
|
|
339 |
val m2 = for ((k, v) <- m) yield (k, v.toUpperCase)
|
204
|
340 |
|
|
341 |
|
318
|
342 |
|
319
|
343 |
// groupBy function on Maps
|
364
|
344 |
val lst = List("one", "two", "three", "four", "five")
|
|
345 |
lst.groupBy(_.head)
|
204
|
346 |
|
364
|
347 |
lst.groupBy(_.length)
|
204
|
348 |
|
364
|
349 |
lst.groupBy(_.length).get(3)
|
|
350 |
|
|
351 |
val grps = lst.groupBy(_.length)
|
|
352 |
grps.keySet
|
204
|
353 |
|
|
354 |
|
51
|
355 |
|
192
|
356 |
|
|
357 |
// Pattern Matching
|
|
358 |
//==================
|
|
359 |
|
471
|
360 |
// A powerful tool which has even landed in Java during
|
|
361 |
// the last few years (https://inside.java/2021/06/13/podcast-017/).
|
|
362 |
// ...Scala already has it for many years and the concept is
|
|
363 |
// older than your friendly lecturer, that is stone old ;o)
|
192
|
364 |
|
|
365 |
// The general schema:
|
|
366 |
//
|
|
367 |
// expression match {
|
|
368 |
// case pattern1 => expression1
|
|
369 |
// case pattern2 => expression2
|
|
370 |
// ...
|
|
371 |
// case patternN => expressionN
|
|
372 |
// }
|
|
373 |
|
|
374 |
|
319
|
375 |
// recall
|
365
|
376 |
def my_map_int(lst: List[Int], f: Int => Int) : List[Int] =
|
|
377 |
lst match {
|
|
378 |
case Nil => Nil
|
|
379 |
case x::xs => f(x)::my_map_int(xs, f)
|
|
380 |
}
|
58
|
381 |
|
471
|
382 |
def my_map_option(opt: Option[Int], f: Int => Int) : Option[Int] =
|
|
383 |
opt match {
|
365
|
384 |
case None => None
|
|
385 |
case Some(x) => Some(f(x))
|
|
386 |
}
|
58
|
387 |
|
365
|
388 |
my_map_option(None, x => x * x)
|
|
389 |
my_map_option(Some(8), x => x * x)
|
192
|
390 |
|
212
|
391 |
|
192
|
392 |
// you can also have cases combined
|
266
|
393 |
def season(month: String) : String = month match {
|
192
|
394 |
case "March" | "April" | "May" => "It's spring"
|
|
395 |
case "June" | "July" | "August" => "It's summer"
|
|
396 |
case "September" | "October" | "November" => "It's autumn"
|
204
|
397 |
case "December" => "It's winter"
|
|
398 |
case "January" | "February" => "It's unfortunately winter"
|
365
|
399 |
case _ => "Wrong month"
|
266
|
400 |
}
|
|
401 |
|
365
|
402 |
// pattern-match on integers
|
|
403 |
|
|
404 |
def fib(n: Int) : Int = n match {
|
|
405 |
case 0 | 1 => 1
|
|
406 |
case n => fib(n - 1) + fib(n - 2)
|
|
407 |
}
|
|
408 |
|
|
409 |
fib(10)
|
266
|
410 |
|
204
|
411 |
// Silly: fizz buzz
|
192
|
412 |
def fizz_buzz(n: Int) : String = (n % 3, n % 5) match {
|
|
413 |
case (0, 0) => "fizz buzz"
|
|
414 |
case (0, _) => "fizz"
|
|
415 |
case (_, 0) => "buzz"
|
|
416 |
case _ => n.toString
|
|
417 |
}
|
|
418 |
|
365
|
419 |
for (n <- 1 to 20)
|
192
|
420 |
println(fizz_buzz(n))
|
|
421 |
|
|
422 |
|
365
|
423 |
val lst = List(None, Some(1), Some(2), None, Some(3)).flatten
|
|
424 |
|
|
425 |
def my_flatten(xs: List[Option[Int]]): List[Int] =
|
|
426 |
xs match {
|
|
427 |
case Nil => Nil
|
|
428 |
case None::rest => my_flatten(rest)
|
|
429 |
case Some(v)::rest => v :: my_flatten(rest)
|
|
430 |
}
|
|
431 |
|
|
432 |
my_flatten(List(None, Some(1), Some(2), None, Some(3)))
|
|
433 |
|
|
434 |
|
|
435 |
|
|
436 |
|
|
437 |
|
|
438 |
|
278
|
439 |
|
|
440 |
|
309
|
441 |
// Recursion
|
|
442 |
//===========
|
|
443 |
|
|
444 |
|
318
|
445 |
/* Say you have characters a, b, c.
|
|
446 |
What are all the combinations of a certain length?
|
309
|
447 |
|
318
|
448 |
All combinations of length 2:
|
|
449 |
|
|
450 |
aa, ab, ac, ba, bb, bc, ca, cb, cc
|
|
451 |
|
|
452 |
Combinations of length 3:
|
|
453 |
|
|
454 |
aaa, baa, caa, and so on......
|
309
|
455 |
*/
|
|
456 |
|
320
|
457 |
def combs(cs: List[Char], n: Int) : List[String] = {
|
|
458 |
if (n == 0) List("")
|
|
459 |
else for (c <- cs; s <- combs(cs, n - 1)) yield s"$c$s"
|
|
460 |
}
|
|
461 |
|
|
462 |
combs(List('a', 'b', 'c'), 3)
|
|
463 |
|
|
464 |
|
|
465 |
|
318
|
466 |
def combs(cs: List[Char], l: Int) : List[String] = {
|
309
|
467 |
if (l == 0) List("")
|
318
|
468 |
else for (c <- cs; s <- combs(cs, l - 1)) yield s"$c$s"
|
309
|
469 |
}
|
|
470 |
|
318
|
471 |
combs("abc".toList, 2)
|
|
472 |
|
|
473 |
|
329
|
474 |
// When writing recursive functions you have to
|
|
475 |
// think about three points
|
|
476 |
//
|
|
477 |
// - How to start with a recursive function
|
|
478 |
// - How to communicate between recursive calls
|
|
479 |
// - Exit conditions
|
|
480 |
|
|
481 |
|
147
|
482 |
|
318
|
483 |
// A Recursive Web Crawler / Email Harvester
|
|
484 |
//===========================================
|
204
|
485 |
//
|
212
|
486 |
// the idea is to look for links using the
|
|
487 |
// regular expression "https?://[^"]*" and for
|
|
488 |
// email addresses using another regex.
|
204
|
489 |
|
|
490 |
import io.Source
|
|
491 |
import scala.util._
|
|
492 |
|
|
493 |
// gets the first 10K of a web-page
|
|
494 |
def get_page(url: String) : String = {
|
|
495 |
Try(Source.fromURL(url)("ISO-8859-1").take(10000).mkString).
|
|
496 |
getOrElse { println(s" Problem with: $url"); ""}
|
147
|
497 |
}
|
|
498 |
|
204
|
499 |
// regex for URLs and emails
|
|
500 |
val http_pattern = """"https?://[^"]*"""".r
|
|
501 |
val email_pattern = """([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})""".r
|
|
502 |
|
268
|
503 |
//test case:
|
212
|
504 |
//email_pattern.findAllIn
|
|
505 |
// ("foo bla christian@kcl.ac.uk 1234567").toList
|
|
506 |
|
204
|
507 |
|
|
508 |
// drops the first and last character from a string
|
|
509 |
def unquote(s: String) = s.drop(1).dropRight(1)
|
|
510 |
|
|
511 |
def get_all_URLs(page: String): Set[String] =
|
|
512 |
http_pattern.findAllIn(page).map(unquote).toSet
|
|
513 |
|
|
514 |
// naive version of crawl - searches until a given depth,
|
|
515 |
// visits pages potentially more than once
|
318
|
516 |
def crawl(url: String, n: Int) : Unit = {
|
|
517 |
if (n == 0) ()
|
204
|
518 |
else {
|
|
519 |
println(s" Visiting: $n $url")
|
318
|
520 |
for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1)
|
204
|
521 |
}
|
147
|
522 |
}
|
|
523 |
|
204
|
524 |
// some starting URLs for the crawler
|
|
525 |
val startURL = """https://nms.kcl.ac.uk/christian.urban/"""
|
147
|
526 |
|
204
|
527 |
crawl(startURL, 2)
|
|
528 |
|
|
529 |
|
318
|
530 |
// a primitive email harvester
|
|
531 |
def emails(url: String, n: Int) : Set[String] = {
|
|
532 |
if (n == 0) Set()
|
|
533 |
else {
|
|
534 |
println(s" Visiting: $n $url")
|
|
535 |
val page = get_page(url)
|
|
536 |
val new_emails = email_pattern.findAllIn(page).toSet
|
|
537 |
new_emails ++ (for (u <- get_all_URLs(page)) yield emails(u, n - 1)).flatten
|
|
538 |
}
|
|
539 |
}
|
55
|
540 |
|
318
|
541 |
emails(startURL, 3)
|
55
|
542 |
|
|
543 |
|
318
|
544 |
// if we want to explore the internet "deeper", then we
|
|
545 |
// first have to parallelise the request of webpages:
|
|
546 |
//
|
|
547 |
// scala -cp scala-parallel-collections_2.13-0.2.0.jar
|
|
548 |
// import scala.collection.parallel.CollectionConverters._
|
55
|
549 |
|
53
|
550 |
|
|
551 |
|
|
552 |
|
192
|
553 |
|
319
|
554 |
// Jumping Towers
|
|
555 |
//================
|
278
|
556 |
|
319
|
557 |
|
364
|
558 |
def moves(xs: List[Int], n: Int) : List[List[Int]] =
|
|
559 |
(xs, n) match {
|
|
560 |
case (Nil, _) => Nil
|
366
|
561 |
case (_, 0) => Nil
|
364
|
562 |
case (x::xs, n) => (x::xs) :: moves(xs, n - 1)
|
|
563 |
}
|
319
|
564 |
|
366
|
565 |
// List(5,5,1,0) -> moves(List(5,1,0), 5)
|
319
|
566 |
moves(List(5,1,0), 1)
|
|
567 |
moves(List(5,1,0), 2)
|
|
568 |
moves(List(5,1,0), 5)
|
|
569 |
|
|
570 |
// checks whether a jump tour exists at all
|
|
571 |
|
|
572 |
def search(xs: List[Int]) : Boolean = xs match {
|
|
573 |
case Nil => true
|
366
|
574 |
case x::xs =>
|
|
575 |
if (xs.length < x) true
|
|
576 |
else moves(xs, x).exists(search(_))
|
319
|
577 |
}
|
|
578 |
|
|
579 |
|
|
580 |
search(List(5,3,2,5,1,1))
|
|
581 |
search(List(3,5,1,0,0,0,1))
|
|
582 |
search(List(3,5,1,0,0,0,0,1))
|
|
583 |
search(List(3,5,1,0,0,0,1,1))
|
|
584 |
search(List(3,5,1))
|
|
585 |
search(List(5,1,1))
|
|
586 |
search(Nil)
|
|
587 |
search(List(1))
|
|
588 |
search(List(5,1,1))
|
|
589 |
search(List(3,5,1,0,0,0,0,0,0,0,0,1))
|
|
590 |
|
366
|
591 |
|
|
592 |
import scala.util._
|
|
593 |
List.fill(100)(Random.nextInt(2))
|
|
594 |
search(List.fill(100)(Random.nextInt(10)))
|
|
595 |
|
319
|
596 |
// generate *all* jump tours
|
|
597 |
// if we are only interested in the shortes one, we could
|
|
598 |
// shortcircut the calculation and only return List(x) in
|
|
599 |
// case where xs.length < x, because no tour can be shorter
|
|
600 |
// than 1
|
|
601 |
//
|
|
602 |
|
|
603 |
def jumps(xs: List[Int]) : List[List[Int]] = xs match {
|
|
604 |
case Nil => Nil
|
366
|
605 |
case x::xs => {
|
319
|
606 |
val children = moves(xs, x)
|
366
|
607 |
val results =
|
|
608 |
children.map(cs => jumps(cs).map(x :: _)).flatten
|
319
|
609 |
if (xs.length < x) List(x) :: results else results
|
|
610 |
}
|
|
611 |
}
|
|
612 |
|
|
613 |
jumps(List(3,5,1,2,1,2,1))
|
|
614 |
jumps(List(3,5,1,2,3,4,1))
|
|
615 |
jumps(List(3,5,1,0,0,0,1))
|
|
616 |
jumps(List(3,5,1))
|
|
617 |
jumps(List(5,1,1))
|
|
618 |
jumps(Nil)
|
|
619 |
jumps(List(1))
|
|
620 |
jumps(List(5,1,2))
|
|
621 |
moves(List(1,2), 5)
|
|
622 |
jumps(List(1,5,1,2))
|
|
623 |
jumps(List(3,5,1,0,0,0,0,0,0,0,0,1))
|
|
624 |
|
|
625 |
jumps(List(5,3,2,5,1,1)).minBy(_.length)
|
|
626 |
jumps(List(1,3,5,8,9,2,6,7,6,8,9)).minBy(_.length)
|
|
627 |
jumps(List(1,3,6,1,0,9)).minBy(_.length)
|
|
628 |
jumps(List(2,3,1,1,2,4,2,0,1,1)).minBy(_.length)
|
|
629 |
|
|
630 |
|