-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpleac_scala.data
10943 lines (9517 loc) · 376 KB
/
pleac_scala.data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- Scala -*-
// Some of the examples make use of Scala's Predef.assert
// function so that the script is self-checking
// @@PLEAC@@_NAME
// @@SKIP@@ Scala
// @@PLEAC@@_WEB
// @@SKIP@@ http://www.scala-lang.org
// @@PLEAC@@_1.0
//----------------------------------------------------------------------------------
var string = "\\n" // two characters, \ and an n
assert(string.length == 2)
var string = "\n" // a "newline" character
var string = "Jon 'Maddog' Orwant" // single quotes inside double quotes
var string = "Jon \"Maddog\" Orwant" // escaped double quotes
var string = """
This is a multiline string declaration
using single quotes (you can use double quotes)
"""
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.1
//----------------------------------------------------------------------------------
// accessing substrings
var string = "hippopotamus"
var start = 5; var end = 7; var endplus1 = 8
assert(string.substring(start, endplus1) == "pot")
assert(string.substring(start) == "potamus")
// String is immutable but new strings can be created in various ways
assert(string * 3 == "hippopotamushippopotamushippopotamus")
assert(string.replace("ppopotam","bisc") == "hibiscus")
assert(string.substring(0, 2) + "bisc" + string.substring(string.length-2, string.length) == "hibiscus")
// StringBuffer is mutable
val sb = new StringBuilder(string)
sb.replace(2, sb.length-2, "bisc")
assert(sb.toString() == "hibiscus")
// No pack/unpack equivalents exist in Scala.
// get a 5-character string, skip 8, then grab 2 5-character strings
// TODO
// On a Java 5 or 6 JVM, Groovy can also make use of Scanners:
// TODO
// another scanner example similar to the javadoc example
// TODO
// split at five characters boundaries
// TODO
// chop string into individual characters
var charlist = (for (i <- "abcd") yield i).toList
assert(charlist == List[Char]('a','b','c','d'))
val string = "This is what you have"
assert(string.substring(0,1) == "T")
assert(string.substring(5,7) == "is")
assert(string.substring(13) == "you have")
assert(string.substring(string.length-1) == "e")
assert(string.substring(string.length-4, string.length) == "have")
assert(string.substring(string.length-8, string.length-5) == "you")
val data = new StringBuffer(string)
data.replace(5,7,"wasn't") ; assert(data.toString == "This wasn't what you have")
data.replace(data.length-12, data.length, "ondrous") ; assert(data.toString == "This wasn't wondrous")
data.replace(0, 1, "") ; assert(data.toString == "his wasn't wondrous")
data.replace(data.length-10, data.length, "") ; assert(data.toString == "his wasn'")
val string = "This wasn't wondrous"
// check last ten characters match some pattern
assert(string.substring(string.length-10).matches("^t\\s.*s$") == true)
val string = "This is a test"
assert(string.substring(0,5).replaceAll("is", "at") + string.substring(5, string.length) == "That is a test")
// exchange the first and last letters in a string
val string = "make a hat"
assert(string.substring(string.length-1) + string.substring(1,string.length-1) + string.substring(0,1) == "take a ham")
// extract column with unpack
val string = 'To be or not to be'
// TODO
// skip 6, grab 6
// TODO
// forward 6, grab 2, backward 5, grab 2
// TODO
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.2
//----------------------------------------------------------------------------------
// use b if b is true, else c
var b = false; val c = "cat"
val a = if (b) b else c // Watch out type of a is Any!
assert(a == "cat")
b = true
val a = if (b) b else c // Watch out type of a is Any!
assert (a == true)
// set x to y unless x is already true
var x:Any = false; val y = "dog"
if (!(x.asInstanceOf[Boolean])) x = y // Cast is needed, because Scala is static typed
assert(x == "dog")
// JVM supplies user name
assert(System.getProperty("user.name") != null)
// test for nullity then for emptyness (length == 0)
// Maybe in a later version of Scala it is possible to use structural types
// to expect an object having a length field oder length() method
def setDefaultIfNullOrEmpty(startingPoint: String) = {
if (startingPoint == null || startingPoint.length == 0) "Greenwich" else startingPoint
}
assert(setDefaultIfNullOrEmpty(null) == "Greenwich") // Check null
assert(setDefaultIfNullOrEmpty("") == "Greenwich") // Check empty String
assert(setDefaultIfNullOrEmpty("Something else") == "Something else")
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.3
//----------------------------------------------------------------------------------
// not possible in Scala
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.4
//----------------------------------------------------------------------------------
val ch: Char = 'e'
val num: Int = ch // no problem
val ch = num.asInstanceOf[Char] // needs an explicit cast
val s1 = "Number " + num + " is character " + num.asInstanceOf[Char]
assert(s1 == "Number 101 is character e")
val s2 = "Character " + ch + " is number " + ch.asInstanceOf[Int]
assert(s2 == "Character e is number 101")
// easy conversion between char arrays, char lists and Strings
val ascii = "sample".toCharArray() // {115, 97, 109, 112, 108, 101}
assert(new String(ascii) == "sample")
assert(new String(Array('s', 'a', 'm', 'p', 'l', 'e')) == "sample")
// convert 'HAL' to 'IBM' (in increasing order of Grooviness)
assert(new String("HAL".toCharArray.map(_ + 1).toChar)) == "IBM")
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.5
//----------------------------------------------------------------------------------
// Example to process a string one character at the time
// 3 ways are shown here to get for examle the sum of the character of a string
val string = "abc"
val expectedSum = 'a' + 'b' + 'c' // 294
// Create a function an calculate with pattern matching
def sumChars(chars:List[Char]):Int = {
chars match {
case Nil => 0
case head :: tail => head + sumChars(tail)
}
}
assert(sumChars(string.toList) == expectedSum)
// Call the foreach method with a closure to add the chars
var sum = 0
string.foreach { c => {
sum += c
}}
assert(sum == expectedSum)
// Use the foldLeft method or the alias /:
assert(string.foldLeft(0)((a,b) => a + b) == expectedSum)
assert(string./:(0)((a,b) => a + b) == expectedSum)
val string = "an apple a day"
var s = ""
string.foreach { c => s = s + c }
assert(s == "an apple a day")
assert(string.substring(3,8).split("").subArray(1,6).deepEquals(Array("a", "p", "p", "l", "e")))
//----------------------------------------------------------------------------------
// @@INCLUDE include/scala/ch01/CheckSum.scala
//----------------------------------------------------------------------------------
// @@INCLUDE include/scala/ch01/SlowCat.scala
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.6
//----------------------------------------------------------------------------------
// See http://lampsvn.epfl.ch/trac/scala/ticket/1495
// Will work with Scala 2.8+
assert("gnirts".reverse == "string")
val string = "Yoda said, \"can you see this?\""
assert(string.split(" ").reverse.mkString(" ") == "this?\" see you \"can said, Yoda")
val words = List("bob", "alpha", "rotator", "omega", "reviver")
val longPalindromes = words.filter(w => w == w.reverse.toString && w.length > 5)
assert(longPalindromes == List("rotator", "reviver"))
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.7
//----------------------------------------------------------------------------------
// TODO
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.8
//----------------------------------------------------------------------------------
// Scala does not support variable expansion.
// You have to concatenate.
val debt = 150
assert("You owe " + debt + " to me" == "You owe 150 to me")
val rows = 24
val cols = 80
assert("I am " + rows + " high and " + cols + " wide" == "I am 24 high and 80 wide")
assert("I am 17 years old".replaceAll("""\d+""", "34") == "I am 34 years old")
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.9
//----------------------------------------------------------------------------------
val little = "bo peep"
assert(little.toUpperCase == "BO PEEP")
assert(little.toUpperCase.toLowerCase == "bo peep")
val text = "thIs is a loNG lIne"
assert("This Is A Long Line" == text.split(" ").map(_.toLowerCase.capitalize).mkString(" "))
val rnd = new scala.util.Random
val genesis = """
Book 01 Genesis
001:001 In the Beginning god created the heaven and the earth.
001:002 And the earth was without form, and void; and darkness was
upon the face of the deep. and the spirit of god moved upon
the face of the waters.
001:003 and god said, let there be light: and there was light.
"""
println(genesis.map {
c => {
if (rnd.nextDouble < 0.2) c.toUpperCase
else c.toLowerCase
}
}.mkString)
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.10
//----------------------------------------------------------------------------------
val n = 10
assert("I have " + (n+1) + " guanacos." == "I have 11 guanacos.")
assert("I have %d guanacos.".format(n+1) == "I have 11 guanacos.")
// TODO
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.11
//----------------------------------------------------------------------------------
// TODO
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.12
//----------------------------------------------------------------------------------
// TODO
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.13
//----------------------------------------------------------------------------------
val string = "Mom said, \"Don't do that.\""
// backslash special chars
assert(string.replaceAll("['\"]", "\\\\$0") == "Mom said, \\\"Don\\'t do that.\\\"")
// double special chars
assert(string.replaceAll("['\"]", "$0$0") == "Mom said, \"\"Don''t do that.\"\"")
// backslash quote all non-capital-letters
assert("DIR /?".replaceAll("[^A-Z]", "\\\\$0") == "DIR\\ \\/\\?")
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.14
//----------------------------------------------------------------------------------
assert(" x ".trim == "x")
// print what's typed, but surrounded by >< symbols
// script:
var line = ""
while((line = readLine) != null) {
println(">" + line + "<")
}
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.15
//----------------------------------------------------------------------------------
// TODO
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.16
//----------------------------------------------------------------------------------
// TODO
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.17
//----------------------------------------------------------------------------------
val input = "I have analysed the new part. As long as you aren't worried about the colour, it is a dropin replacement"
val translations = Map(("colour", "color"), ("analysed","analyzed"), ("dropin","drop-in"))
val wordExtractor = """(.*?)(\w+)(.*?)""".r
val output = input.split(" ").map(w => { val wordExtractor(prefix, word, suffix) = w; if (translations.isDefinedAt(word)) prefix + translations(word) + suffix else w} ).mkString(" ")
val expected = "I have analyzed the new part. As long as you aren't worried about the color, it is a drop-in replacement"
assert(output == expected)
//----------------------------------------------------------------------------------
// @@PLEAC@@_1.18
//----------------------------------------------------------------------------------
// TODO
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.1
//----------------------------------------------------------------------------------
// Shown for Int. Float, Double, ... similar
val n = "33".toInt
assert(n == 33)
// Trying to parse not an Int throws a NumberFormatException
var n = 0
try {
n = "33.5".toInt
} catch {
case e:NumberFormatException => assert(e.getMessage.contains("33.5"))
}
assert(n == 0)
// another solution with regular expressions
val intPattern = """^[+-]?\d+$"""
assert("0".matches(intPattern))
assert("36".matches(intPattern))
assert("-36".matches(intPattern))
assert("+36".matches(intPattern))
assert(!"1.5".matches(intPattern))
assert(!"abc".matches(intPattern))
val decimalPattern = """^-?(?:\d+(?:\.\d*)?|\.\d+)$"""
assert("37".matches(decimalPattern))
assert("37.5".matches(decimalPattern))
assert("37.".matches(decimalPattern))
assert(!"37.5.1".matches(decimalPattern))
assert(!"abc".matches(decimalPattern))
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.2
//----------------------------------------------------------------------------------
def compareDoubles(a:Double, b:Double, accuracy:Double) = {
Math.abs(a-b) < accuracy
}
assert(compareDoubles(0.25, 0.255, 0.1) == true)
assert(compareDoubles(0.25, 0.255, 0.01) == true)
assert(compareDoubles(0.25, 0.255, 0.001) == false)
// @@INCLUDE include/scala/ch02/DoubleApproxEqual.scala
val wage = 5.36
val week = 40 * wage
// Assertion possibly fails because of your Locale, see http://lampsvn.epfl.ch/trac/scala/ticket/2004
assert("One week's wage is: $%.2f".format(week) == "One week's wage is: $214.40")
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.3
//----------------------------------------------------------------------------------
def round(d:Double, prec:Int) = {
val p = Math.pow(10, prec)
val v = d * Math.pow(10, prec)
val tmp = Math.round(v)
tmp/p
}
val a = 0.255
val b = round(a, 2);
assert(a.toString() == "0.255")
assert(b.toString() == "0.26")
val a = List(3.3 , 3.5 , 3.7, -3.3)
// warning rint() rounds to nearest integer - slightly different to Perl's int()
val rintExpected = List(3.0, 4.0, 4.0, -3.0)
val floorExpected = List(3.0, 3.0, 3.0, -4.0)
val ceilExpected = List(4.0, 4.0, 4.0, -3.0)
assert(a.map(Math.rint) == rintExpected)
assert(a.map(Math.floor) == floorExpected)
assert(a.map(Math.ceil) == ceilExpected)
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.4
//----------------------------------------------------------------------------------
assert(Integer.parseInt('0110110', 2) == 54)
assert(Integer.toString(54, 2) == "110110")
// also works for other radix values, e.g. hex
assert(Integer.toString(60, 16) == "3c")
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.5
//----------------------------------------------------------------------------------
val x = 3; val y = 20
for (i <- x to y) {
//i is set to every integer from x to y, inclusive
}
(x to y).foreach {
// implicit closure variable _ is set to every integer from x up to y
}
(x until y).foreach {
// implicit closure variable _ is set to every integer from x up to but excluding y
}
List.range(x, y, step).foreach {
// implicit closure variable _ is set to every integer
// from x up to but excluding y with a step size of step
}
assert(List.range(x,y,7) == List(3, 10, 17))
assert("Infancy is: " + (0 to 2).mkString(" ") == "Infancy is: 0 1 2")
assert("Toddling is: " + (3 to 4).mkString(" ") == "Toddling is: 3 4")
assert("Childhood is: " + (5 to 12).mkString(" ") == "Childhood is: 5 6 7 8 9 10 11 12")
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.6
//----------------------------------------------------------------------------------
object IntRoman {
val romanMap = Map((1000,"M"), (900,"CM"), (500,"D"), (400,"CD"), (100,"C"), (90,"XC"),
(50,"L"), (40,"XL"), (10,"X"), (9,"IX"), (5,"V"), (4,"IV"), (1,"I"))
def apply(input:String):Int = {
var ustr = input.toUpperCase()
var sum = 0
romanMap.keySet.toList.sort((a,b)=>a>b).foreach{ key =>
while (ustr.startsWith(romanMap(key))) {
sum += key
ustr = ustr.substring(romanMap(key).length)
}
}
sum
}
}
class IntRoman(i:Int) {
import IntRoman.romanMap
def toRoman = {
var remains = i
val text = new StringBuilder()
romanMap.keySet.toList.sort((a,b) => a>b).foreach{ key => {
while (remains >= key) {
remains = remains - key
text append romanMap(key)
}
}
}
text.toString
}
}
implicit def int2intRoman(i:Int) = new IntRoman(i)
assert(15.toRoman == "XV")
assert(IntRoman("XXVI") == 26)
for (i <- 1 to 3900) {
assert(i == IntRoman(i.toRoman))
}
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.7
//----------------------------------------------------------------------------------
val rnd = new scala.util.Random()
val randomNumber = rnd.nextInt(10) // Random number between 0 (inclusive) and 10 (exclusive)
assert(randomNumber >= 0 && randomNumber < 10)
// Creates a random number between 25 (inclusive) and 75 (inclusive)
val rnd = new scala.util.Random()
val randomNumber = rnd.nextInt(51) + 25
assert (randomNumber >= 25 && randomNumber <= 75)
val rnd = new scala.util.Random()
val fruits = List("apple", "banana", "orange", "strawberry")
val eatme = fruits(rnd.nextInt(fruits.length))
assert(fruits.exists(_ == eatme)) // check that in fruits exists eatme
val rnd = new scala.util.Random()
val chars = ('A' to 'Z').toList ::: ('a' to 'z').toList ::: List('!', '@', '$', '%', '^', '&', '*') ::: Nil
val password = (for (i <- 1 to 8; c = chars(rnd.nextInt(chars.length))) yield c).mkString
assert(password.length == 8) // sorry we can assert the length only ;)
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.8
//----------------------------------------------------------------------------------
// Scala uses Java's java.util.Random
// You can use your own seed, but beware of this!
val seed = System.currentTimeMillis()
val rnd1 = new scala.util.Random(seed)
val rnd2 = new scala.util.Random(seed)
// Same seed same random numbers...
assert(rnd1.nextInt() == rnd2.nextInt())
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.9
//----------------------------------------------------------------------------------
// Use java.security.SecureRandom instead of scala.util.Random or java.util.Random
// SecureRandom is a subclass of java.util.Random so the usage is the same:
val rnd = new java.security.SecureRandom()
val secureRandomNumber = rnd.nextInt(10)
assert(secureRandomNumber >= 0 && secureRandomNumber < 10)
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.10
//----------------------------------------------------------------------------------
// use Java's Random.nextGaussian() method.
// Scala's Random doesn't have it at the moment
// See http://lampsvn.epfl.ch/trac/scala/ticket/2008
val rnd = new java.util.Random()
val randomNumber = rnd.nextGaussian() * sdev + mean
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.11
//----------------------------------------------------------------------------------
assert(Math.toRadians(90) == Math.Pi / 2)
assert(Math.toDegrees(Math.Pi) == 180)
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.12
//----------------------------------------------------------------------------------
// use methods in Math object
//----------------------------------------------------------------------------------
val t = Math.tan(1.5)
assert(t > 14.1 && t < 14.11)
val ac = Math.acos(0.1)
assert(ac > 1.47 && ac < 1.48)
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.13
//----------------------------------------------------------------------------------
assert(Math.log(Math.E) == 1)
// Use java.lang.Math for log to base 10
// logarithm of 10000 to base 10 is 4
assert(java.lang.Math.log10(10000) == 4)
def logn(base:Double, x:Double) = Math.log(x) / Math.log(base)
assert logn(2, 1024) == 10
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.14
//----------------------------------------------------------------------------------
// TODO
// there are several Java Matrix packages available, e.g.
// http://math.nist.gov/javanumerics/jama
import Jama.Matrix
matrix1 = new Matrix([
[3, 2, 3],
[5, 9, 8]
] as double[][])
matrix2 = new Matrix([
[4, 7],
[9, 3],
[8, 1]
] as double[][])
expectedArray = [[54.0, 30.0], [165.0, 70.0]] as double[][]
productArray = matrix1.times(matrix2).array
for (i in 0..<productArray.size()) {
assert productArray[i] == expectedArray[i]
}
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.15
//----------------------------------------------------------------------------------
// @@INCLUDE include/scala/ch02/Complex.scala
// Or use a library e.g. org.apache.commons.math.complex.Complex
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.16
//----------------------------------------------------------------------------------
val twofivefive = Integer.parseInt("ff", 16) // hex to dec
assert(twofivefive.toHexString.toLowerCase == "ff") // reverse it
val five = Integer.parseInt("101", 2) // bin to dec
assert(five.toBinaryString.toLowerCase == "101") // reverse it
val eight = Integer.parseInt("10", 8) // oct to dec
assert(eight.toOctalString.toLowerCase == "10") // reverse it
//----------------------------------------------------------------------------------
// @@INCLUDE include/scala/ch02/Conversion.scala
// @@INCLUDE include/scala/ch02/Permission.scala
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.17
//----------------------------------------------------------------------------------
val nf = java.text.NumberFormat.getInstance(java.util.Locale.US)
assert(nf.format(-1740525205) == "-1,740,525,205")
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.18
//----------------------------------------------------------------------------------
def timeMessage(h:Int) = { "It took " + h + " hour" + (if (h == 1) "" else "s") }
assert("It took 0 hours" == timeMessage(0))
assert("It took 1 hour" == timeMessage(1))
assert("It took 2 hours" == timeMessage(2))
// you can also use Java's ChoiceFormat
// overkill for this example but extensible and compatible with MessageFormat
import java.text.ChoiceFormat
val limits = Array(0.0, 1.0, 2.0)
val names = Array("strawberries", "strawberry", "strawberries")
val choice = new ChoiceFormat(limits, names)
val expect0 = "I have 0 strawberries"
val expect1 = "I have 1 strawberry"
val expect2 = "I have 2 strawberries"
val count = 0
assert("I have " + count + " " + choice.format(count) == expect0)
val count = 1
assert("I have " + count + " " + choice.format(count) == expect1)
val count = 2
assert("I have " + count + " " + choice.format(count) == expect2)
// more complex pluralization can be done with Java libraries, e.g.:
// http://www.elvis.ac.nz/brain?PluralizationMapping
// org.springframework.util.Pluralizer within the Spring Framework (springframework.org)
//----------------------------------------------------------------------------------
// @@PLEAC@@_2.19
//----------------------------------------------------------------------------------
// TODO
// calculating prime factors
def factorize(BigInteger orig) {
factors = [:]
def addFactor = { x -> if (factors[x]) factors[x] += 1 else factors[x] = 1 }
n = orig
i = 2
sqi = 4 // square of i
while (sqi <= n) {
while (n.remainder(i) == 0) {
n /= i
addFactor i
}
// we take advantage of the fact that (i+1)**2 = i**2 + 2*i + 1
sqi += 2 * i + 1
i += 1
}
if ((n != 1) && (n != orig)) addFactor n
return factors
}
def pretty(factors) {
if (!factors) return "PRIME"
sb = new StringBuffer()
factors.keySet().sort().each { key ->
sb << key
if (factors[key] > 1) sb << "**" + factors[key]
sb << " "
}
return sb.toString().trim()
}
assert pretty(factorize(2178)) == '2 3**2 11**2'
assert pretty(factorize(39887)) == 'PRIME'
assert pretty(factorize(239322000000000000000000)) == '2**19 3 5**18 39887'
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.0
//----------------------------------------------------------------------------------
// TODO
// use Date to get the current time
println new Date()
// => Mon Jan 01 07:12:32 EST 2007
// use Calendar to compute year, month, day, hour, minute, and second values
cal = Calendar.instance
println 'Today is day ' + cal.get(Calendar.DAY_OF_YEAR) + ' of the current year.'
// => Today is day 1 of the current year.
// there are other Java Date/Time packages with extended capabilities, e.g.:
// http://joda-time.sourceforge.net/
// there is a special Grails (grails.codehaus.org) time DSL (see below)
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.1
//----------------------------------------------------------------------------------
// TODO
cal = Calendar.instance
Y = cal.get(Calendar.YEAR)
M = cal.get(Calendar.MONTH) + 1
D = cal.get(Calendar.DATE)
println "The current date is $Y $M $D"
// => The current date is 2006 04 28
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.2
//----------------------------------------------------------------------------------
// TODO
// create a calendar with current time and time zone
cal = Calendar.instance
// set time zone using long or short timezone values
cal.timeZone = TimeZone.getTimeZone("America/Los_Angeles")
cal.timeZone = TimeZone.getTimeZone("UTC")
// set date fields one at a time
cal.set(Calendar.MONTH, Calendar.DECEMBER)
// or several together
//calendar.set(year, month - 1, day, hour, minute, second)
// get time in seconds since EPOCH
long time = cal.time.time / 1000
println time
// => 1196522682
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.3
//----------------------------------------------------------------------------------
// TODO
// create a calendar with current time and time zone
cal = Calendar.instance
// set time
cal.time = new Date(time * 1000)
// get date fields
println('Dateline: '
+ cal.get(Calendar.HOUR_OF_DAY) + ':'
+ cal.get(Calendar.MINUTE) + ':'
+ cal.get(Calendar.SECOND) + '-'
+ cal.get(Calendar.YEAR) + '/'
+ (cal.get(Calendar.MONTH) + 1) + '/'
+ cal.get(Calendar.DATE))
// => Dateline: 7:33:16-2007/1/1
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.4
//----------------------------------------------------------------------------------
// TODO
import java.text.SimpleDateFormat
long difference = 100
long after = time + difference
long before = time - difference
// any field of a calendar is incrementable via add() and roll() methods
cal = Calendar.instance
df = new SimpleDateFormat()
printCal = {cal -> df.format(cal.time)}
cal.set(2000, 0, 1, 00, 01, 0)
assert printCal(cal) == '1/01/00 00:01'
// roll minute back by 2 but don't adjust other fields
cal.roll(Calendar.MINUTE, -2)
assert printCal(cal) == '1/01/00 00:59'
// adjust hour back 1 and adjust other fields if needed
cal.add(Calendar.HOUR, -1)
assert printCal(cal) == '31/12/99 23:59'
// larger example
cal.timeZone = TimeZone.getTimeZone("UTC")
cal.set(1973, 0, 18, 3, 45, 50)
cal.add(Calendar.DATE, 55)
cal.add(Calendar.HOUR_OF_DAY, 2)
cal.add(Calendar.MINUTE, 17)
cal.add(Calendar.SECOND, 5)
assert printCal(cal) == '14/03/73 16:02'
// alternatively, work with epoch times
long birthTime = 96176750359 // 18/Jan/1973, 3:45:50 am
long interval = 5 + // 5 second
17 * 60 + // 17 minute
2 * 60 * 60 + // 2 hour
55 * 60 * 60 * 24 // and 55 day
then = new Date(birthTime + interval * 1000)
assert df.format(then) == '14/03/73 16:02'
// Alternatively, the Google Data module has a category with DSL-like time support:
// http://docs.codehaus.org/display/GROOVY/Google+Data+Support
// which supports the following syntax
// def interval = 5.seconds + 17.minutes + 2.hours + 55.days
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.5
//----------------------------------------------------------------------------------
// TODO
bree = 361535725 // 16 Jun 1981, 4:35:25
nat = 96201950 // 18 Jan 1973, 3:45:50
difference = bree - nat
println "There were $difference seconds between Nat and Bree"
// => There were 265333775 seconds between Nat and Bree
seconds = difference % 60
difference = (difference - seconds) / 60
minutes = difference % 60
difference = (difference - minutes) / 60
hours = difference % 24
difference = (difference - hours) / 24
days = difference % 7
weeks = (difference - days) / 7
println "($weeks weeks, $days days, $hours:$minutes:$seconds)"
// => (438 weeks, 4 days, 23:49:35)
//----------------------------------------------------------------------------------
cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
cal.set(1981, 5, 16) // 16 Jun 1981
date1 = cal.time
cal.set(1973, 0, 18) // 18 Jan 1973
date2 = cal.time
difference = Math.abs(date2.time - date1.time)
days = difference / (1000 * 60 * 60 * 24)
assert days == 3071
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.6
//----------------------------------------------------------------------------------
// TODO
// create a calendar with current time and time zone
cal = Calendar.instance
cal.set(1981, 5, 16)
yearDay = cal.get(Calendar.DAY_OF_YEAR);
year = cal.get(Calendar.YEAR);
yearWeek = cal.get(Calendar.WEEK_OF_YEAR);
df1 = new SimpleDateFormat("dd/MMM/yy")
df2 = new SimpleDateFormat("EEEE")
print(df1.format(cal.time) + ' was a ' + df2.format(cal.time))
println " and was day number $yearDay and week number $yearWeek of $year"
// => 16/Jun/81 was a Tuesday and was day number 167 and week number 25 of 1981
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.7
//----------------------------------------------------------------------------------
// TODO
input = "1998-06-03"
df1 = new SimpleDateFormat("yyyy-MM-dd")
date = df1.parse(input)
df2 = new SimpleDateFormat("MMM/dd/yyyy")
println 'Date was ' + df2.format(date)
// => Date was Jun/03/1998
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.8
//----------------------------------------------------------------------------------
// TODO
import java.text.DateFormat
df = new SimpleDateFormat('E M d hh:mm:ss z yyyy')
cal.set(2007, 0, 1)
println 'Customized format gives: ' + df.format(cal.time)
// => Mon 1 1 09:02:29 EST 2007 (differs depending on your timezone)
df = DateFormat.getDateInstance(DateFormat.FULL, Locale.FRANCE)
println 'Customized format gives: ' + df.format(cal.time)
// => lundi 1 janvier 2007
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.9
//----------------------------------------------------------------------------------
// TODO
// script:
println 'Press return when ready'
before = System.currentTimeMillis()
input = new BufferedReader(new InputStreamReader(System.in)).readLine()
after = System.currentTimeMillis()
elapsed = (after - before) / 1000
println "You took $elapsed seconds."
// => You took2.313 seconds.
// take mean sorting time
size = 500; number = 100; total = 0
for (i in 0..<number) {
array = []
size.times{ array << Math.random() }
doubles = array as double[]
// sort it
long t0 = System.currentTimeMillis()
Arrays.sort(doubles)
long t1 = System.currentTimeMillis()
total += (t1 - t0)
}
println "On average, sorting $size random numbers takes ${total / number} milliseconds"
// => On average, sorting 500 random numbers takes 0.32 milliseconds
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.10
//----------------------------------------------------------------------------------
// TODO
delayMillis = 50
Thread.sleep(delayMillis)
//----------------------------------------------------------------------------------
// @@PLEAC@@_3.11
//----------------------------------------------------------------------------------
// TODO
// this could be done more simply using JavaMail's getAllHeaderLines() but is shown
// in long hand for illustrative purposes
sampleMessage = '''Delivered-To: [email protected]
Received: (qmail 27284 invoked from network); 30 Dec 2006 15:16:26 -0000
Received: from unknown (HELO lists-outbound.sourceforge.net) (66.35.250.225)
by bne012m.server-web.com with SMTP; 30 Dec 2006 15:16:25 -0000
Received: from sc8-sf-list2-new.sourceforge.net (sc8-sf-list2-new-b.sourceforge.net [10.3.1.94])
by sc8-sf-spam2.sourceforge.net (Postfix) with ESMTP
id D8CCBFDE3; Sat, 30 Dec 2006 07:16:24 -0800 (PST)
Received: from sc8-sf-mx1-b.sourceforge.net ([10.3.1.91]
helo=mail.sourceforge.net)
by sc8-sf-list2-new.sourceforge.net with esmtp (Exim 4.43)
id 1H0fwX-0003c0-GA
for [email protected]; Sat, 30 Dec 2006 07:16:20 -0800
Received: from omta05ps.mx.bigpond.com ([144.140.83.195])
by mail.sourceforge.net with esmtp (Exim 4.44) id 1H0fwY-0005D4-DD
for [email protected]; Sat, 30 Dec 2006 07:16:19 -0800
Received: from win2K001 ([138.130.127.127]) by omta05ps.mx.bigpond.com
with SMTP
id <20061230151611.XVWL19269.omta05ps.mx.bigpond.com@win2K001>;
Sat, 30 Dec 2006 15:16:11 +0000
From: [email protected]
To: <[email protected]>
Date: Sun, 31 Dec 2006 02:14:57 +1100
Subject: Re: [Pleac-discuss] C/Posix/GNU - @@pleac@@_10x
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
Sender: [email protected]
Errors-To: [email protected]
----- Original Message -----
From: [email protected]
Cc: <[email protected]>
Sent: Wednesday, December 27, 2006 9:18 AM
Subject: Re: [Pleac-discuss] C/Posix/GNU - @@pleac@@_10x
I really like that description of PLEAC.
'''
expected = '''
Sender Recipient Time Delta
<origin> somewhere.com 01:14:57 06/12/31
win2K001 omta05ps.mx.bigpond.com 01:14:57 06/12/31 1m 14s
omta05ps.mx.bigpond.com mail.sourceforge.net 01:16:11 06/12/31 8s
sc8-sf-mx1-b.sourceforge. sc8-sf-list2-new.sourcefo 01:16:19 06/12/31 1s
sc8-sf-list2-new.sourcefo sc8-sf-spam2.sourceforge. 01:16:20 06/12/31 4s
unknown bne012m.server-web.com 01:16:24 06/12/31 1s
'''
class MailHopDelta {
def headers, firstSender, firstDate, out
MailHopDelta(mail) {
extractHeaders(mail)
out = new StringBuffer()
def m = (mail =~ /(?m)^Date:\s+(.*)/)
firstDate = parseDate(m[0][1])
firstSender = (mail =~ /(?m)^From.*\@([^\s>]*)/)[0][1]
out('Sender Recipient Time Delta'.split(' '))
}
def parseDate(date) {
try {
return new SimpleDateFormat('EEE, dd MMM yyyy hh:mm:ss Z').parse(date)
} catch(java.text.ParseException ex) {}
try {
return new SimpleDateFormat('dd MMM yyyy hh:mm:ss Z').parse(date)
} catch(java.text.ParseException ex) {}
try {
return DateFormat.getDateInstance(DateFormat.FULL).parse(date)
} catch(java.text.ParseException ex) {}
DateFormat.getDateInstance(DateFormat.LONG).parse(date)
}
def extractHeaders(mail) {
headers = []
def isHeader = true
def currentHeader = ''
mail.split('\n').each{ line ->
if (!isHeader) return
switch(line) {
case ~/^\s*$/:
isHeader = false
if (currentHeader) headers << currentHeader
break
case ~/^\s+.*/:
currentHeader += line; break
default:
if (currentHeader) headers << currentHeader
currentHeader = line
}
}
}
def out(line) {
out << line[0][0..<[25,line[0].size()].min()].padRight(26)
out << line[1][0..<[25,line[1].size()].min()].padRight(26)
out << line[2].padRight(17) + ' '
out << line[3] + '\n'
}
def prettyDate(date) {
new SimpleDateFormat('hh:mm:ss yy/MM/dd').format(date)
}
def process() {
out(['<origin>', firstSender, prettyDate(firstDate), ''])
def prevDate = firstDate
headers.grep(~/^Received:\sfrom.*/).reverseEach{ hop ->
def from = (hop =~ /from\s+(\S+)|\((.*?)\)/)[0][1]
def by = (hop =~ /by\s+(\S+\.\S+)/)[0][1]
def hopDate = parseDate(hop[hop.lastIndexOf(';')+2..-1])
out([from, by, prettyDate(prevDate), prettyDelta(hopDate.time - prevDate.time)])
prevDate = hopDate
}
return out.toString()
}
def prettyField(secs, sign, ch, multiplier, sb) {
def whole = (int)(secs / multiplier)
if (!whole) return 0
sb << '' + (sign * whole) + ch + ' '
return whole * multiplier
}
def prettyDelta(millis) {
def sign = millis < 0 ? -1 : 1