This gist will contain all the exercises from the book
Last active
September 28, 2021 15:51
-
-
Save hhimanshu/55564b70dac97d0aa4eb to your computer and use it in GitHub Desktop.
Scala for the Impatient Exercises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 2. In the Scala REPL, compute the square root of 3, and then square that value. By how much does the result differ from 3? (Hint: The res variables are your friend.) | |
*/ | |
scala> math.sqrt(3) | |
res1: Double = 1.7320508075688772 | |
scala> res1*res1 | |
res2: Double = 2.9999999999999996 | |
scala> 3 - res2 | |
res3: Double = 4.440892098500626E-16 | |
// 3. Are the res variables val or var? | |
scala> res1 = 3 | |
<console>:11: error: reassignment to val | |
res1 = 3 | |
^ | |
/** | |
* 4. Scala lets you multiply a string with a number—try out "crazy" * 3 in the REPL. | |
* What does this operation do? Where can you find it in Scaladoc? | |
*/ | |
// StringOps.* : Return the current string concatenated n times. | |
scala> "crazy "*3 | |
res6: String = "crazy crazy crazy " | |
/** | |
* 5. What does 10 max 2 mean? In which class is the max method defined? | |
*/ | |
// Int.max: Returns this if this > that or that otherwise. | |
scala> 10 max 2 | |
res7: Int = 10 | |
scala> 10.max(2) | |
res8: Int = 10 | |
/** | |
* 6. Using BigInt, compute 21024. | |
*/ | |
scala> BigInt(2) pow 1024 | |
res13: scala.math.BigInt = 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216 | |
/** | |
* 7. What do you need to import so that you can get a random prime as probablePrime(100, Random), | |
* without any qualifiers before probablePrime and Random? | |
*/ | |
scala> import scala.util.Random | |
import scala.util.Random | |
scala> import scala.math.BigInt | |
import scala.math.BigInt | |
scala> import scala.math.BigInt.probablePrime | |
import scala.math.BigInt.probablePrime | |
scala> probablePrime(100, Random) | |
res14: scala.math.BigInt = 931669304734992063893063804797 | |
/** | |
* 8. One way to create random file or directory names is to produce a random BigInt | |
* and convert it to base 36, yielding a string such as "qsnvbevtomcj38o06kul". | |
* Poke around Scaladoc to find a way of doing this in Scala. | |
*/ | |
scala> probablePrime(100, Random) toString 36 | |
res15: String = 2mojnrl2508jtnu26t01 | |
/** | |
* 9. How do you get the first character of a string in Scala? The last character? | |
*/ | |
scala> "Hello".head | |
res20: Char = H | |
scala> "Hello".last | |
res21: Char = o | |
/** | |
* 10. What do the take, drop, takeRight, and dropRight string functions do? | |
* What advantage or disadvantage do they have over using substring? | |
*/ | |
// StringOps.drop: Selects all elements except first n ones. | |
// StringOps.dropRight: Selects all elements except last n ones. | |
// StringOps.take: Selects first n elements. | |
// StringOps.takeRight: Selects last n elements. | |
scala> "Hello World!" take 6 | |
res22: String = "Hello " | |
scala> "Hello World!" drop 6 | |
res23: String = World! | |
scala> "Hello World!" takeRight 6 | |
res24: String = World! | |
scala> "Hello World!" dropRight 6 | |
res25: String = "Hello " |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 1. The signum of a number is 1 if the number is positive, –1 if it is negative, and 0 if it is zero. | |
* Write a function that computes this value. | |
*/ | |
scala> def signum(num:Int) = if (num > 0) 1 else if (num < 0) -1 else 0 | |
signum: (num: Int)Int | |
scala> signum(10) | |
res4: Int = 1 | |
scala> signum(0) | |
res5: Int = 0 | |
scala> signum(-123) | |
res6: Int = -1 | |
/** | |
* 2. What is the value of an empty block expression {}? What is its type? | |
*/ | |
// Value is 'no value' and type is Unit | |
scala> val empty = {} | |
empty: Unit = () | |
scala> empty | |
/** | |
* 3. Come up with one situation where the assignment x = y = 1 is valid in Scala. | |
* (Hint: Pick a suitable type for x.) | |
*/ | |
scala> var x: Any = _ | |
x: Any = null | |
scala> var y: Int = _ | |
y: Int = 0 | |
scala> x = y = 1 | |
x: Any = () | |
scala> x | |
res0: Any = () | |
scala> y | |
res1: Int = 1 | |
/** | |
* 4. Write a Scala equivalent for the Java loop | |
* for (int i = 10; i >= 0; i--) System.out.println(i); | |
*/ | |
// Range.by: Create a new range with the start and end values of this range and a new step. | |
scala> for(i<- 10 to 0 by -1) println(i) | |
10 | |
9 | |
8 | |
7 | |
6 | |
5 | |
4 | |
3 | |
2 | |
1 | |
0 | |
/** | |
* 5. Write a procedure countdown(n: Int) that prints the numbers from n to 0. | |
*/ | |
scala> def countdown(n:Int) = for(i <- n to 0 by -1) println(i) | |
countdown: (n: Int)Unit | |
scala> countdown(10) | |
10 | |
9 | |
8 | |
7 | |
6 | |
5 | |
4 | |
3 | |
2 | |
1 | |
0 | |
/** | |
* 6. Write a for loop for computing the product of the Unicode codes of all letters in a string. | |
* For example, the product of the characters in "Hello" is 9415087488L. | |
*/ | |
// IndexedSeq.product: Multiplies up the elements of this collection. | |
// returns | |
// the product of all elements in this sequence of numbers of type Int. | |
// Instead of Int, any other type T with an implicit Numeric[T] implementation can be used as element type of the sequence and as result type of product. | |
// Examples of such types are: Long, Float, Double, BigInt. | |
scala> (for(i <- "Hello") yield i.toLong).product | |
res19: Long = 9415087488 | |
/** | |
* 7. Solve the preceding exercise without writing a loop. (Hint: Look at the StringOps Scaladoc.) | |
*/ | |
scala> "Hello".map(c => c.toLong).product | |
res22: Long = 9415087488 | |
/** | |
* 8. Write a function product(s : String) that computes the product, as described in the preceding exercises. | |
*/ | |
scala> def product(s:String) = s.map(c => c.toLong).product | |
product: (s: String)Long | |
scala> product("Hello") | |
res23: Long = 9415087488 | |
/** | |
* 9. Make the function of the preceding exercise a recursive function. | |
*/ | |
scala> def product(s:String, p:Long):Long = s.isEmpty match { | |
| case false => product(s.tail, p * s.head.toLong) | |
| case true => p | |
| } | |
scala> def prod(s:String):Long = s.isEmpty match { | |
| case false => product(s, 1) | |
| case true => 0 | |
| } | |
prod: (s: String)Long | |
scala> prod("") | |
res5: Long = 0 | |
scala> prod("Hello") | |
res6: Long = 9415087488 | |
/** | |
* 10. Write a function that computes xn, where n is an integer. Use the following recursive definition: | |
* • xn = y2 if n is even and positive, where y = xn / 2. | |
* • xn = x·xn – 1 if n is odd and positive. | |
* • x0 = 1. | |
* • xn = 1 / x–n if n is negative. | |
* Don’t use a return statement. | |
*/ | |
scala> def pow(x:Int, n:Int) = n match { | |
| case n if n > 0 && (n%2 == 0) => scala.math.pow(x, n/2) | |
| case n if n > 0 && (n%2 == 1) => x * scala.math.pow(x, n-1) | |
| case 0 => 1 | |
| case n if n < 0 => 1/scala.math.pow(x, -n) | |
| } | |
pow: (x: Int, n: Int)Double | |
scala> pow(2, 4) | |
res0: Double = 4.0 | |
scala> pow(2, 5) | |
res1: Double = 32.0 | |
scala> pow(2, 0) | |
res2: Double = 1.0 | |
scala> pow(2, -1) | |
res3: Double = 0.5 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 1. Write a code snippet that sets a to an array of n random integers between 0 (inclusive) and n (exclusive) | |
*/ | |
scala> def randomInRange(n:Int) = for(i <- 0 to n) yield Random.nextInt(n) | |
randomInRange: (n: Int)scala.collection.immutable.IndexedSeq[Int] | |
scala> randomInRange(100) | |
res7: scala.collection.immutable.IndexedSeq[Int] = Vector(68, 47, 1, 20, 35, 93, 53, 24, 75, 46, 23, 61, 98, 62, 60, 38, 82, 69, 10, 82, 96, 30, 14, 50, 20, 42, 44, 11, 31, 18, 70, 13, 25, 77, 85, 89, 55, 45, 16, 44, 13, 50, 71, 58, 86, 16, 7, 79, 60, 31, 79, 52, 56, 86, 31, 85, 32, 84, 14, 54, 79, 56, 7, 68, 62, 87, 77, 4, 47, 28, 36, 23, 88, 19, 28, 41, 47, 3, 92, 88, 29, 22, 52, 8, 14, 76, 83, 45, 42, 45, 36, 77, 50, 12, 89, 28, 70, 97, 35, 70, 32) | |
/** | |
* 2. Write a loop that swaps adjacent elements of an array of integers. For example, Array(1, 2, 3, 4, 5) becomes Array(2, 1, 4, 3, 5). | |
*/ | |
// http://stackoverflow.com/a/10160082/379235 | |
scala> val a = Array(1, 2, 3, 4, 5) | |
a: Array[Int] = Array(1, 2, 3, 4, 5) | |
scala> a.grouped(2).flatMap(_.reverse).toArray | |
res17: Array[Int] = Array(2, 1, 4, 3, 5) | |
/** | |
* 3. Repeat the preceding assignment, but produce a new array with the swapped values. Use for/yield. | |
*/ | |
scala> (for {b <- a.grouped(2); c <- b.reverse} yield c).toArray | |
res16: Array[Int] = Array(2, 1, 4, 3, 5) | |
/** | |
* 4. Given an array of integers, produce a new array that contains all positive values | |
* of the original array, in their original order, followed by all values that are zero or negative, | |
* in their original order | |
*/ | |
scala> val b = Array(-1, 2,3,4, -10, 0, -12) | |
b: Array[Int] = Array(-1, 2, 3, 4, -10, 0, -12) | |
scala> val(positive, negative) = b partition(_ > 0) | |
positive: Array[Int] = Array(2, 3, 4) | |
negative: Array[Int] = Array(-1, -10, 0, -12) | |
scala> positive ++ negative | |
res11: Array[Int] = Array(2, 3, 4, -1, -10, 0, -12) | |
// better approach - https://stackoverflow.com/questions/32109281/produce-new-array-where-all-positive-comes-first-then-negative-or-zero-but-in-s | |
/** | |
* 5. How do you compute the average of an Array[Double]? | |
*/ | |
scala> val doubleArray = Array(12.3, 12.3) | |
doubleArray: Array[Double] = Array(12.3, 12.3) | |
scala> doubleArray.sum/doubleArray.length | |
res15: Double = 12.3 | |
/** | |
* 6. How do you rearrange the elements of an Array[Int] so that they appear in reverse sorted order? | |
* How do you do the same with an ArrayBuffer[Int]? | |
*/ | |
scala> val arrayInt = Array(1,2,3,4,5,6,7,8,9) | |
arrayInt: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9) | |
scala> arrayInt sortWith(_>_) | |
res32: Array[Int] = Array(9, 8, 7, 6, 5, 4, 3, 2, 1) | |
scala> import scala.collection.mutable.ArrayBuffer | |
import scala.collection.mutable.ArrayBuffer | |
scala> val arrayBufferInt = ArrayBuffer(1,3,2,4,5,6,7,9,8) | |
arrayBufferInt: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 3, 2, 4, 5, 6, 7, 9, 8) | |
scala> arrayBufferInt sortWith(_>_) | |
res33: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(9, 8, 7, 6, 5, 4, 3, 2, 1) | |
/** | |
* 7. Write a code snippet that produces all values from an array with duplicates removed. (Hint: Look at Scaladoc.) | |
*/ | |
scala> val arrayWithDups = Array(2,2,4,5,6,6,3,3,1,1,1,1,0) | |
arrayWithDups: Array[Int] = Array(2, 2, 4, 5, 6, 6, 3, 3, 1, 1, 1, 1, 0) | |
scala> arrayWithDups.distinct | |
res35: Array[Int] = Array(2, 4, 5, 6, 3, 1, 0) | |
/* Not Attempting 08 */ | |
/** | |
* 9. Make a collection of all time zones returned by java.util.TimeZone.getAvailableIDs that are in America. | |
* Strip off the "America/" prefix and sort the result. | |
*/ | |
scala> java.util.TimeZone.getAvailableIDs filter(t => t.contains("America/")) map (t => t.split('/') last) sortWith(_ < _) | |
warning: there was one feature warning; re-run with -feature for details | |
res45: Array[String] = Array(Adak, Anchorage, Anguilla, Antigua, Araguaina, Aruba, Asuncion, Atikokan, Atka, Bahia, Bahia_Banderas, | |
Barbados, Belem, Belize, Beulah, Blanc-Sablon, Boa_Vista, Bogota, Boise, Buenos_Aires, Buenos_Aires, Cambridge_Bay, Campo_Grande, | |
Cancun, Caracas, Catamarca, Catamarca, Cayenne, Cayman, Center, Chicago, Chihuahua, ComodRivadavia, Coral_Harbour, Cordoba, Cordoba, | |
Costa_Rica, Creston, Cuiaba, Curacao, Danmarkshavn, Dawson, Dawson_Creek, Denver, Detroit, Dominica, Edmonton, Eirunepe, El_Salvador, | |
Ensenada, Fort_Wayne, Fortaleza, Glace_Bay, Godthab, Goose_Bay, Grand_Turk, Grenada, Guadeloupe, Guatemala, Guayaquil, Guyana, Halifax, | |
Havana, Hermosillo, Indianapolis, Indianapolis, Inuvik, Iqaluit, Jamaica, Jujuy, Jujuy, Juneau, Knox, Knox_IN, Kralendijk, La_Paz, L... | |
scala> | |
/** Not attempting 10 */ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 1. Set up a map of prices for a number of gizmos that you covet. | |
* Then produce a second map with the same keys and the prices at a 10 percent discount. | |
*/ | |
scala> val items = Map("Tesla" -> 80000, "iWatch" -> 700) | |
items: scala.collection.immutable.Map[String,Int] = Map(Tesla -> 80000, iWatch -> 700) | |
scala> for ((item, value) <- items) yield(item, value - (value * 0.1)) | |
res2: scala.collection.immutable.Map[String,Double] = Map(Tesla -> 72000.0, iWatch -> 630.0) | |
/** | |
* 2. Write a program that reads words from a file. Use a mutable map to count how often each word appears. | |
*/ | |
// source file: https://www.gutenberg.org/cache/epub/35709/pg35709.txt | |
scala> val words = scala.io.Source.fromFile("pg35709.txt").mkString.split("\\s+") | |
words: Array[String] = Array(The, Project, Gutenberg, EBook, of, Making, Your, Camera, Pay,, by, Frederick, C., Davis, | |
This, eBook, is, for, the, use, of, anyone, anywhere, at, no, cost, and, with, almost, no, restrictions, whatsoever., | |
You, may, copy, it,, give, it, away, or, re-use, it, under, the, terms, of, the, Project, Gutenberg, License, included, | |
with, this, eBook, or, online, at, www.gutenberg.net, Title:, Making, Your, Camera, Pay, Author:, Frederick, C., Davis, | |
Release, Date:, March, 29,, 2011, [EBook, #35709], Language:, English, ***, START, OF, THIS, PROJECT, GUTENBERG, EBOOK, | |
MAKING, YOUR, CAMERA, PAY, ***, Produced, by, The, Online, Distributed, Proofreading, Team, at, http://www.pgdp.net, | |
(This, file, was, produced, from, images, generously, made, available, by, The, In... | |
scala> val wordCount = scala.collection.mutable.HashMap[String, Int]() | |
wordCount: scala.collection.mutable.HashMap[String,Int] = Map() | |
scala> for (word <- words) { | |
| val count = wordCount.getOrElse(word, 0) | |
| wordCount(word) = count + 1 | |
| } | |
scala> word | |
wordCount words | |
scala> wordCount | |
res1: scala.collection.mutable.HashMap[String,Int] = Map(arts -> 1, follow -> 3, request, -> 1, Lines. -> 1, | |
demand -> 7, 1.E.4. -> 1, PRODUCT -> 2, 470 -> 1, Chicago, -> 3, scenic -> 1, J2 -> 1, untrimmed -> 1, | |
photographs--not -> 1, basis. -> 1, "prints -> 1, instances. -> 1, Onion-Planter -> 1, trick -> 1, | |
illustrating -> 3, prefer. -> 1, detected -> 1, non-exclusive. -> 1, famous -> 1, Competition -> 2, | |
expense -> 1, created -> 2, renamed. -> 1, maggot -> 1, calendar-photographs, -> 1, widely-read -> 1, | |
Publisher, -> 1, producers -> 1, Shapes -> 1, ARTICLES -> 2, yearly -> 2, retoucher -> 1, satisfy -> 2, | |
agrees: -> 1, Gentleman_, -> 1, intellectual -> 2, hard -> 2, Porch. -> 1, sold.) -> 1, START -> 1, House -> 2, | |
welcome -> 1, Dealers' -> 1, ... -> 2, pasted -> 1, _Cosmopolitan_ -... | |
/** | |
* 3. Repeat the preceding exercise with an immutable map. | |
*/ | |
scala> val words = scala.io.Source.fromURL("https://www.gutenberg.org/cache/epub/35709/pg35709.txt").mkString.split("\\s+") | |
words: Array[String] = Array(The, Project, Gutenberg, EBook, of, Making, Your, Camera, Pay,, by, Frederick, C., | |
Davis, This, eBook, is, for, the, use, of, anyone, anywhere, at, no, cost, and, with, almost, no, restrictions, | |
whatsoever., You, may, copy, it,, give, it, away, or, re-use, it, under, the, terms, of, the, Project, Gutenberg, | |
License, included, with, this, eBook, or, online, at, www.gutenberg.net, Title:, Making, Your, Camera, Pay, Author:, | |
Frederick, C., Davis, Release, Date:, March, 29,, 2011, [EBook, #35709], Language:, English, ***, START, OF, THIS, PROJECT, | |
GUTENBERG, EBOOK, MAKING, YOUR, CAMERA, PAY, ***, Produced, by, The, Online, Distributed, Proofreading, Team, at, | |
http://www.pgdp.net, (This, file, was, produced, from, images, generously, made, available, by, The, In... | |
scala> var wordCount = Map[String, Int]() | |
wordCount: scala.collection.immutable.Map[String,Int] = Map() | |
scala> for (word <- words) { | |
| val count = wordCount.getOrElse(word, 0) | |
| wordCount = wordCount + (word -> (count + 1)) | |
| } | |
scala> wordCount | |
res2: scala.collection.immutable.Map[String,Int] = Map("Should -> 1, serious -> 1, | |
Farm-buildings -> 1, container, -> 1, comply -> 6, forgotten -> 1, stop, -> 2, Spell -> 1, Washington, -> 6, | |
Advertises -> 1, rate -> 2, lights -> 1, submitted -> 1, engraver -> 3, generalize -> 2, Produced -> 2, Furniture: -> 1, | |
Redistributing -> 1, non-fictionist, -> 1, Archive/American -> 2, wiser -> 1, "snap-shooters" -> 1, action. -> 3, 6, -> 1, | |
supplementary -> 2, botany, -> 1, glean -> 1, locations -> 1, tenth, -> 1, Features -> 1, Advertising -> 1, Lens. -> 1, | |
trade, -> 1, SHAPE -> 2, particularly -> 1, bird-dogs, -> 1, used -> 24, Mo., -> 1, eye -> 1, PUNITIVE -> 1, striking -> 2, | |
gloss." -> 1, job--as -> 1, picture. -> 1, instance, -> 1, READ -> 1, Sets -> 1, Medical: -> 1, advertising-medium. -... | |
scala> | |
/** | |
* 4. Repeat the preceding exercise with a sorted map, so that the words are printed in sorted order. | |
*/ | |
scala> val words = scala.io.Source.fromURL("https://www.gutenberg.org/cache/epub/35709/pg35709.txt").mkString.split("\\s+") | |
words: Array[String] = Array(The, Project, Gutenberg, EBook, of, Making, Your, Camera, Pay,, by, Frederick, C., Davis, This, eBook, is, for, the, use, of, anyone, anywhere, at, no, cost, and, with, almost, no, restrictions, whatsoever., You, may, copy, it,, give, it, away, or, re-use, it, under, the, terms, of, the, Project, Gutenberg, License, included, with, this, eBook, or, online, at, www.gutenberg.net, Title:, Making, Your, Camera, Pay, Author:, Frederick, C., Davis, Release, Date:, March, 29,, 2011, [EBook, #35709], Language:, English, ***, START, OF, THIS, PROJECT, GUTENBERG, EBOOK, MAKING, YOUR, CAMERA, PAY, ***, Produced, by, The, Online, Distributed, Proofreading, Team, at, http://www.pgdp.net, (This, file, was, produced, from, images, generously, made, available, by, The, In... | |
scala> var wordCountSorted = scala.collection.immutable.SortedMap[String, Int]() | |
wordCountSorted: scala.collection.immutable.SortedMap[String,Int] = Map() | |
scala> for(word <- words) { | |
| val count = wordCountSorted.getOrElse(word, 0) | |
| wordCountSorted = wordCountSorted + (word -> (count + 1)) | |
| } | |
scala> wordCountSorted | |
res2: scala.collection.immutable.SortedMap[String,Int] = Map("'Second -> 1, "1001 -> 1, "A -> 3, "All -> 2, "And -> 1, "Any -> 1, "But -> 1, "Defects," -> 1, "Do -> 1, "Draw -> 1, "Either -> 1, "First -> 5, "For -> 2, "From -> 1, "Here -> 1, "How -> 1, "In -> 2, "Information -> 1, "No -> 1, "Non-Exclusive" -> 1, "Not -> 1, "Open -> 1, "Pardon -> 1, "Pay-As-You-Leave" -> 1, "Plain -> 2, "Project -> 5, "Right -> 1, "Second -> 3, "Sell" -> 1, "Shoot -> 1, "Should -> 1, "Sky." -> 1, "Sneezing -> 1, "Speed-Pictures," -> 1, "Study -> 1, "The -> 10, "There -> 1, "There's -> 1, "Transference -> 1, "We -> 1, "Well, -> 1, "What -> 2, "Where -> 1, "Winter-Sports," -> 1, "Work -> 1, "_'How -> 1, "a -> 1, "arrow-points-to-the-scene-of-the-crime" -> 1, "author" -> 1, "barrels -> 1, "before -> 2, "by ... | |
/** | |
* 5. Repeat the preceding exercise with a java.util.TreeMap that you adapt to the Scala API. | |
*/ | |
scala> import java.util.TreeMap | |
import java.util.TreeMap | |
scala> var wordCountTreeMap = new TreeMap[String, Int]() | |
wordCountTreeMap: java.util.TreeMap[String,Int] = {} | |
scala> for(word <- words) { | |
| val count = wordCountTreeMap.getOrDefault(word, 0) | |
| wordCountTreeMap.put(word, count+1) | |
| } | |
scala> wordCount | |
wordCountSorted wordCountTreeMap | |
scala> wordCountTreeMap | |
res7: java.util.TreeMap[String,Int] = {"'Second=1, "1001=1, "A=3, "All=2, "And=1, "Any=1, "But=1, "Defects,"=1, "Do=1, "Draw=1, "Either=1, "First=5, "For=2, "From=1, "Here=1, "How=1, "In=2, "Information=1, "No=1, "Non-Exclusive"=1, "Not=1, "Open=1, "Pardon=1, "Pay-As-You-Leave"=1, "Plain=2, "Project=5, "Right=1, "Second=3, "Sell"=1, "Shoot=1, "Should=1, "Sky."=1, "Sneezing=1, "Speed-Pictures,"=1, "Study=1, "The=10, "There=1, "There's=1, "Transference=1, "We=1, "Well,=1, "What=2, "Where=1, "Winter-Sports,"=1, "Work=1, "_'How=1, "a=1, "arrow-points-to-the-scene-of-the-crime"=1, "author"=1, "barrels=1, "before=2, "by=1, "cashed=1, "dead"=1, "deliver=1, "delivers=2, "eaten=1, "either=1, "film-eater."=1, "flivver"=1, "for=1, "fuzzy."=1, "get=1, "he=1, "heart-trouble."=1, "hot=1, "it's=1, "my... | |
/** | |
* 6. Define a linked hash map that maps "Monday" to java.util.Calendar.MONDAY, and similarly for the other weekdays. Demonstrate that the elements are visited in insertion order. | |
*/ | |
scala> import scala.collection.mutable.LinkedHashMap | |
import scala.collection.mutable.LinkedHashMap | |
scala> import java.util.Calendar._ | |
import java.util.Calendar._ | |
scala> val weekdays = LinkedHashMap[String, Int]("Monday" -> MONDAY, "Tuesday" -> TUESDAY, "Sunday" -> SUNDAY, "Friday" -> FRIDAY) | |
weekdays: scala.collection.mutable.LinkedHashMap[String,Int] = Map(Monday -> 2, Tuesday -> 3, Sunday -> 1, Friday -> 6) | |
scala> weekdays | |
res0: scala.collection.mutable.LinkedHashMap[String,Int] = Map(Monday -> 2, Tuesday -> 3, Sunday -> 1, Friday -> 6) | |
/** | |
* 7. Print a table of all Java properties, like this: | |
java.runtime.name | Java(TM) SE Runtime Environment | |
sun.boot.library.path | /home/apps/jdk1.6.0_21/jre/lib/i386 | |
java.vm.version | 17.0-b16 | |
java.vm.vendor | Sun Microsystems Inc. | |
java.vendor.url | http://java.sun.com/ | |
path.separator | : | |
java.vm.name | Java HotSpot(TM) Server VM | |
You need to find the length of the longest key before you can print the table. | |
*/ | |
// https://stackoverflow.com/questions/32217170/how-to-have-width-between-values | |
scala> import scala.collection.JavaConversions.propertiesAsScalaMap | |
import scala.collection.JavaConversions.propertiesAsScalaMap | |
scala> val props: scala.collection.Map[String, String] = System.getProperties() | |
props: scala.collection.Map[String,String] = | |
Map(env.emacs -> "", java.runtime.name -> Java(TM) SE Runtime Environment, sun.boot.library.path -> /Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib, java.vm.version -> 25.51-b03, gopherProxySet -> false, java.vm.vendor -> Oracle Corporation, java.vendor.url -> http://java.oracle.com/, path.separator -> :, java.vm.name -> Java HotSpot(TM) 64-Bit Server VM, file.encoding.pkg -> sun.io, user.country -> US, sun.java.launcher -> SUN_STANDARD, sun.os.patch.level -> unknown, java.vm.specification.name -> Java Virtual Machine Specification, user.dir -> /Users/harit, java.runtime.version -> 1.8.0_51-b16, java.awt.graphicsenv -> sun.awt.CGraphicsEnvironment, java.endorsed.dirs -> /Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk... | |
scala> props.keys.map(_.length).max | |
res24: Int = 29 | |
scala> for ((k,v) <- props) yield println(k.padTo(29, " ").mkString + "|" + v) | |
env.emacs | | |
java.runtime.name |Java(TM) SE Runtime Environment | |
sun.boot.library.path |/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib | |
java.vm.version |25.51-b03 | |
gopherProxySet |false | |
java.vm.vendor |Oracle Corporation | |
java.vendor.url |http://java.oracle.com/ | |
path.separator |: | |
java.vm.name |Java HotSpot(TM) 64-Bit Server VM | |
file.encoding.pkg |sun.io | |
user.country |US | |
sun.java.launcher |SUN_STANDARD | |
sun.os.patch.level |unknown | |
java.vm.specification.name |Java Virtual Machine Specification | |
user.dir |/Users/harit | |
java.runtime.version |1.8.0_51-b16 | |
java.awt.graphicsenv |sun.awt.CGraphicsEnvironment | |
java.endorsed.dirs |/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib/endorsed | |
os.arch |x86_64 | |
java.io.tmpdir |/var/folders/39/rrqhhzfn42bf7qcwqg2kywtr0000gn/T/ | |
line.separator | | |
java.vm.specification.vendor |Oracle Corporation | |
os.name |Mac OS X | |
sun.jnu.encoding |UTF-8 | |
java.library.path |/Users/harit/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:. | |
java.specification.name |Java Platform API Specification | |
java.class.version |52.0 | |
sun.management.compiler |HotSpot 64-Bit Tiered Compilers | |
os.version |10.10.4 | |
http.nonProxyHosts |local|*.local|169.254/16|*.169.254/16 | |
user.home |/Users/harit | |
user.timezone |America/Los_Angeles | |
scala.home |/usr/local/Cellar/scala/2.11.7/libexec | |
java.awt.printerjob |sun.lwawt.macosx.CPrinterJob | |
file.encoding |UTF-8 | |
java.specification.version |1.8 | |
scala.usejavacp |true | |
java.class.path |"" | |
user.name |harit | |
java.vm.specification.version|1.8 | |
sun.java.command |scala.tools.nsc.MainGenericRunner | |
java.home |/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre | |
sun.arch.data.model |64 | |
user.language |en | |
java.specification.vendor |Oracle Corporation | |
awt.toolkit |sun.lwawt.macosx.LWCToolkit | |
java.vm.info |mixed mode | |
java.version |1.8.0_51 | |
java.ext.dirs |/Users/harit/Library/Java/Extensions:/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib/ext:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java | |
sun.boot.class.path |/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib/sunrsasign.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/jre/classes:/usr/local/Cellar/scala/2.11.7/libexec/lib/akka-actor_2.11-2.3.10.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/config-1.2.1.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/jline-2.12.1.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/scala-actors-2.11.0.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/scala-actors-migration_2.11-1.1.0.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/scala-compiler.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/scala-continuations-library_2.11-1.0.2.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/scala-continuations-plugin_2.11.7-1.0.2.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/scala-library.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/scala-parser-combinators_2.11-1.0.4.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/scala-reflect.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/scala-swing_2.11-1.0.2.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/scala-xml_2.11-1.0.4.jar:/usr/local/Cellar/scala/2.11.7/libexec/lib/scalap-2.11.7.jar | |
java.vendor |Oracle Corporation | |
file.separator |/ | |
java.vendor.url.bug |http://bugreport.sun.com/bugreport/ | |
sun.io.unicode.encoding |UnicodeBig | |
sun.cpu.endian |little | |
socksNonProxyHosts |local|*.local|169.254/16|*.169.254/16 | |
ftp.nonProxyHosts |local|*.local|169.254/16|*.169.254/16 | |
sun.cpu.isalist | | |
res42: Iterable[Unit] = ArrayBuffer((), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), (), ()) | |
/** | |
* 8. Write a function minmax(values: Array[Int]) that returns a pair containing the smallest and largest values in the array. | |
*/ | |
scala> def minmax(values: Array[Int]):(Int, Int) = (values.min, values.max) | |
minmax: (values: Array[Int])(Int, Int) | |
scala> minmax(Array(1, 100, -1, 20)) | |
res45: (Int, Int) = (-1,100) | |
/** | |
* 9. Write a function lteqgt(values: Array[Int], v: Int) that returns a triple | |
* containing the counts of values less than v, equal to v, and greater than v. | |
*/ | |
scala> def lteqgt(values: Array[Int], v: Int): (Int, Int, Int) = (values.count(_ < v), values.count(_ == v), values.count(_ > v)) | |
lteqgt: (values: Array[Int], v: Int)(Int, Int, Int) | |
scala> lteqgt(Array(0,0,1,1,1,2,2), 1) | |
res47: (Int, Int, Int) = (2,3,2) | |
/** | |
* 10. What happens when you zip together two strings, such as "Hello".zip("World")? Come up with a plausible use case. | |
*/ | |
scala> "Hello".zip("World") | |
res52: scala.collection.immutable.IndexedSeq[(Char, Char)] = Vector((H,W), (e,o), (l,r), (l,l), (o,d)) | |
// use-case? May be sum 2 arrays |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 1. Write an object Conversions with methods inchesToCentimeters, gallonsToLiters, and milesToKilometers. | |
*/ | |
scala> object Conversions { | |
| def inchesToCentimeters(inches: Double): Double = 2.54 * inches | |
| def gallonsToLiters(gallons: Double): Double = 3.78541 * gallons | |
| def milesToKilometers(miles: Double): Double = 1.61 * miles | |
| } | |
defined object Conversions | |
scala> Conversions.inchesToCentimeters(10) | |
res56: Double = 25.4 | |
scala> Conversions.gallonsToLiters(1) | |
res57: Double = 3.78541 | |
scala> Conversions.milesToKilometers(7) | |
res58: Double = 11.270000000000001 | |
/** | |
* 2. The preceding problem wasn’t very object-oriented. Provide a general superclass UnitConversion and define objects InchesToCentimeters, | |
* GallonsToLiters, and MilesToKilometers that extend it. | |
*/ | |
scala> abstract class UnitConversion { | |
| def convert(input: Double): Double | |
| } | |
defined class UnitConversion | |
scala> object InchesToCentimeters extends UnitConversion { | |
| def convert(input: Double) = 2.54 * input | |
| def apply(input: Double) = convert(input) | |
| } | |
defined object InchesToCentimeters | |
scala> InchesToCentimeters(1) | |
res59: Double = 2.54 | |
scala> InchesToCentimeters(10) | |
res60: Double = 25.4 | |
/** | |
* 3. Define an Origin object that extends java.awt.Point. | |
* Why is this not actually a good idea? (Have a close look at the methods of the Point class.) | |
*/ | |
// Not a good idea since it has setXXX methods and in singleton since everybody shares, anyone can | |
// change value causing trouble | |
/** | |
* 4. Define a Point class with a companion object so that you can construct | |
* Point instances as Point(3, 4), without using new. | |
*/ | |
scala> :paste | |
// Entering paste mode (ctrl-D to finish) | |
object Point { | |
def apply(x: Int, y: Int) = new Point(x,y) | |
} | |
class Point private(x:Int, y: Int) { | |
override def toString = s"New Point Created (${x}, ${y}))" | |
} | |
// Exiting paste mode, now interpreting. | |
defined object Point | |
defined class Point | |
scala> Point(3,4) | |
res0: Point = New Point Created (3, 4)) | |
/** | |
* 5. Write a Scala application, using the App trait, that prints the command-line arguments | |
* in reverse order, separated by spaces. For example, scala Reverse Hello World should print World Hello.” | |
*/ | |
// Open a new file called MyApp.scala and paste the following contents | |
object MyApp extends App { | |
if(args.length < 1) println("Provide enough arguments to print") | |
println(args.reverse.mkString(" ")) | |
} | |
$ scalac MyApp.scala | |
$ scala MyApp Hello World Scala | |
Scala World Hello | |
$ scala MyApp | |
Provide enough arguments to print | |
// Not attempting 6,7,8 (Enumeration) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 1. Write a Scala code snippet that reverses the lines in a file (making the last line the first one, and so on). | |
*/ | |
scala> import scala.io.Source | |
import scala.io.Source | |
scala> val source = Source.fromURL("http://www.gutenberg.org/cache/epub/4809/pg4809.txt", "UTF-8") | |
source: scala.io.BufferedSource = non-empty iterator | |
scala> source.getLines.toArray.reverse | |
res10: Array[String] = Array(*END THE SMALL PRINT! FOR PUBLIC DOMAIN EBOOKS*Ver.02/11/02*END*, "", express permission.], they hardware or software or any other related product without, used in any sales of Project Gutenberg eBooks or other materials be, Michael S. Hart. Project Gutenberg is a TradeMark and may not be, when distributed free of all fees. Copyright (C) 2001, 2002 by, [Portions of this eBook's header and trailer may be reprinted only, "", [email protected], software or other items, please contact Michael Hart at:, If you are interested in contributing scanning equipment or, "", "Project Gutenberg Literary Archive Foundation.", Money should be paid to the:, public domain materials, or royalty free copyright licenses., The Project gratefully accepts contributions of money, tim... | |
scala> | |
/** | |
* 2. Write a Scala program that reads a file with tabs, replaces each tab with spaces so that tab stops are at n-column boundaries, and writes the result to the same file. | |
*/ | |
// File (with tabs) | |
/** | |
* $ cat ~/Downloads/fileWithTabs.txt | |
a b c | |
d e f | |
*/ | |
scala> val tabPattern = """\t""".r | |
tabPattern: scala.util.matching.Regex = \t | |
scala> val source = Source.fromFile("/Users/harit/Downloads/fileWithTabs.txt") | |
source: scala.io.BufferedSource = non-empty iterator | |
scala> val lines = source.getLines.toArray | |
lines: Array[String] = Array(a b c, d e f) | |
scala> lines(0) | |
res13: String = a b c | |
scala> import java.io.PrintWriter | |
import java.io.PrintWriter | |
scala> val out = new PrintWriter("/Users/harit/Downloads/fileWithTabs.txt") | |
out: java.io.PrintWriter = java.io.PrintWriter@106e6dfe | |
scala> for(line <- replacedLines) {out.println(line)} | |
scala> out.flush | |
scala> out.close | |
/** | |
*“3. Write a Scala code snippet that reads a file and prints all words with more than 12 characters to the console. Extra credit if you can do this in a single line. | |
*/ | |
scala> import scala.io.Source | |
import scala.io.Source | |
scala> Source.fromURL("http://www.gutenberg.org/cache/epub/4809/pg4809.txt", "UTF-8").mkString.split("\\s").filter(_.length > 12) | |
res7: Array[String] = Array(redistributing, Volunteers*****, council--Policy, Orange--Corrupt, government--Efforts, reform--Influence, Armenteros--Painful, retire--Secret, Philip--Ominous, persecution--Execution, Antwerp--Horrible, Protestants--Remonstrance, Titelmann--Obduracy, Philip--Council, Trent--Quarrel, envoys--Order, Netherlands--Opposition, measure--Reluctance, Spain--Violent, instructions--Remarkable, Orange--Apoplexy, Viglius--Temporary, Hopper--Departure, Cambray--Character, Archbishop--Egmont, Spain--Flattery, bribery--Council, Doctors--Vehement, --Proceedings, principality--Egmont's, persecution--Indignation, Egmont--Habitual, dissimulation, King--Reproof, Orange--Assembly, Brussels--Result, deliberations, Philip--Universal, Netherlands--New, heretics--Interview, subject-... | |
scala> | |
/** | |
* 4. Write a Scala program that reads a text file containing only floating-point numbers. Print the sum, average, maximum, and minimum of the numbers in the file. | |
*/ | |
scala> import scala.io.Source | |
import scala.io.Source | |
scala> val numbers = Source.fromFile("/Users/harit/Downloads/floating.txt", "UTF-8").getLines.map(_.toDouble).toArray | |
numbers: Array[Double] = Array(3.14, 2.34, 1.54, 8.34) | |
scala> numbers.min | |
res9: Double = 1.54 | |
scala> numbers.max | |
res10: Double = 8.34 | |
scala> numbers.sum | |
res11: Double = 15.36 | |
scala> numbers.sum/numbers.size | |
res12: Double = 3.84 | |
/** | |
* 5. Write a Scala program that writes the powers of 2 and their reciprocals to a file, with the exponent ranging from 0 to 20. Line up the columns: | |
1 1 | |
2 0.5 | |
4 0.25 | |
... ... | |
*/ | |
scala> val out = new java.io.PrintWriter("out.txt") | |
out: java.io.PrintWriter = java.io.PrintWriter@259aec72 | |
scala> for (i <- 0 to 20) { | |
| val pow = scala.math.pow(2, i) | |
| out.println(pow + "\t" + 1/pow) | |
| } | |
scala> out.close | |
scala> | |
/** | |
* $ cat out.txt | |
1.0 1.0 | |
2.0 0.5 | |
4.0 0.25 | |
8.0 0.125 | |
16.0 0.0625 | |
32.0 0.03125 | |
64.0 0.015625 | |
128.0 0.0078125 | |
256.0 0.00390625 | |
512.0 0.001953125 | |
1024.0 9.765625E-4 | |
2048.0 4.8828125E-4 | |
4096.0 2.44140625E-4 | |
8192.0 1.220703125E-4 | |
16384.0 6.103515625E-5 | |
32768.0 3.0517578125E-5 | |
65536.0 1.52587890625E-5 | |
131072.0 7.62939453125E-6 | |
262144.0 3.814697265625E-6 | |
524288.0 1.9073486328125E-6 | |
1048576.0 9.5367431640625E-7 | |
*/ | |
// skipping 6-10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Пишу на питоне, ничо не понятно