Solved Problems
Output a string to the console
Write the string
"Hello World!" to STDOUT
scala
println("Hello World!")
printf("Hello World!\n")
Retrieve a string containing ampersands from the variables in a url
My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as
The script variable for first name $_REQUEST
I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like
Of course this fails for the same reasons. What is a better approach?
"Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as
"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".
The script variable for first name $_REQUEST
['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.
I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like
"http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)
Of course this fails for the same reasons. What is a better approach?
scala
import java.net.URLEncoder
val params = Map("mode"->"view", "fname"->"Ron & Jean", "lname"->"Smith")
var url = ""
for ((k, v) <- params) { url += URLEncoder.encode(k) + "=" + URLEncoder.encode(v) }
println(url)
val params = Map("mode"->"view", "fname"->"Ron & Jean", "lname"->"Smith")
var url = ""
for ((k, v) <- params) { url += URLEncoder.encode(k) + "=" + URLEncoder.encode(v) }
println(url)
import java.net.URLEncoder
val params = Map("mode"->"view", "fname"->"Ron & Jean", "lname"->"Smith")
(for ((k, v) <- params) yield URLEncoder.encode(k) + "=" + URLEncoder.encode(v) ).mkString("&")
val params = Map("mode"->"view", "fname"->"Ron & Jean", "lname"->"Smith")
(for ((k, v) <- params) yield URLEncoder.encode(k) + "=" + URLEncoder.encode(v) ).mkString("&")
string-wrap
Wrap the string
Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
"The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "
Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
scala
object Wrap {
def wordWrap(str: String, width: Int, lineStart: String, reps: Int) = {
var strRepeated = ""
for(i <- 0 until reps) strRepeated += str
while(strRepeated.length > width) {
println(lineStart + strRepeated.substring(0, (width-1)))
strRepeated = strRepeated.substring(width)
}
println(lineStart + strRepeated)
}
def main(args: Array[String]) = {
wordWrap("The quick brown fox jumps over the lazy dog. ", 78, "> ", 10)
}
}
def wordWrap(str: String, width: Int, lineStart: String, reps: Int) = {
var strRepeated = ""
for(i <- 0 until reps) strRepeated += str
while(strRepeated.length > width) {
println(lineStart + strRepeated.substring(0, (width-1)))
strRepeated = strRepeated.substring(width)
}
println(lineStart + strRepeated)
}
def main(args: Array[String]) = {
wordWrap("The quick brown fox jumps over the lazy dog. ", 78, "> ", 10)
}
}
def stringWrap(s: String): List[String] =
if (s.length == 0) Nil else s.take(78) :: stringWrap(s.drop(78))
stringWrap("The quick brown fox jumps over the lazy dog. " * 10).foreach(line => println("> " + line))
if (s.length == 0) Nil else s.take(78) :: stringWrap(s.drop(78))
stringWrap("The quick brown fox jumps over the lazy dog. " * 10).foreach(line => println("> " + line))
("The quick brown fox jumps over the lazy dog. " * 10) grouped(78) foreach { line => println("> " + line) }
Define a string containing special characters
Define the literal string
"\#{'}${"}/"
scala
val special = "\\#{'}${\"}/"
val special2 = """\#{'}${"}/"""
val special2 = """\#{'}${"}/"""
Define a multiline string
Define the string:
"This
Is
A
Multiline
String"
scala
val text = """This
Is
A
Multiline
String"""
Is
A
Multiline
String"""
val text = "This\nIs\nA\nMultiline\nString"
Define a string containing variables and expressions
Given variables a=3 and b=4 output
"3+4=7"
scala
printf("%d+%d=%d\n", a, b, a + b)
"%d+%d=%d".format(a, b, a + b)
Reverse the characters in a string
Given the string
"reverse me", produce the string "em esrever"
scala
val reversed = "reverse me".reverse
Reverse the words in a string
Given the string
"This is a end, my only friend!", produce the string "friend! only my end, the is This"
scala
"This is the end, my only friend!".split(" ").reverse.reduceLeft( (x,y) => x+' '+y )
val reversed = revwords("This is the end, my only friend!")
(("This is the end, my only friend!" split " ") reverse) mkString " "
val reversedText = text.split(" ").reverse.mkString(" ")
Text wrapping
Wrap the string
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
"The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
scala
val prefix = "> " ; val input = "The quick brown fox jumps over the lazy dog."
WordUtils.wrap(input * 10, 72 - prefix.length).split("\n") foreach {(x) => printf("%s%s\n", prefix, x)}
WordUtils.wrap(input * 10, 72 - prefix.length).split("\n") foreach {(x) => printf("%s%s\n", prefix, x)}
def wrap(words: List[String]): List[List[String]] = words match {
case Nil => Nil
case _ =>
val output = (words.inits.dropWhile { _.mkString(" ").length > 78 }) next;
output :: wrap(words.drop(output.length))
}
wrap(("The quick brown fox jumps over the lazy dog. " * 10) split(" ") toList) foreach {
words => println("> " + words.mkString(" "))
}
case Nil => Nil
case _ =>
val output = (words.inits.dropWhile { _.mkString(" ").length > 78 }) next;
output :: wrap(words.drop(output.length))
}
wrap(("The quick brown fox jumps over the lazy dog. " * 10) split(" ") toList) foreach {
words => println("> " + words.mkString(" "))
}
Remove leading and trailing whitespace from a string
Given the string
" hello " return the string "hello".
scala
val s = " hello ".trim
Simple substitution cipher
Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
scala
val uppers = 'A' to 'Z'
val lowers = 'a' to 'z'
val alpha13 = (uppers ++ lowers).mkString
val beta13 = ((uppers drop 13) ++ (uppers take 13) ++ (lowers drop 13) ++ (lowers take 13)).mkString
val alpha47 = """!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
val beta47 = """PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO"""
// generic translation function
def rot (alpha: String, beta: String)(c: Char) = if (alpha contains c) beta(alpha indexOf c) else c
// specific translation functions curried with the respective alphabets
val rot13 = rot(alpha13, beta13) _
val rot47 = rot(alpha47, beta47) _
assert(("Hello World #123" map rot13).toString == "Uryyb Jbeyq #123")
assert(("Hello World #123" map rot47).toString == "w6==@ (@C=5 R`ab")
val lowers = 'a' to 'z'
val alpha13 = (uppers ++ lowers).mkString
val beta13 = ((uppers drop 13) ++ (uppers take 13) ++ (lowers drop 13) ++ (lowers take 13)).mkString
val alpha47 = """!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
val beta47 = """PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO"""
// generic translation function
def rot (alpha: String, beta: String)(c: Char) = if (alpha contains c) beta(alpha indexOf c) else c
// specific translation functions curried with the respective alphabets
val rot13 = rot(alpha13, beta13) _
val rot47 = rot(alpha47, beta47) _
assert(("Hello World #123" map rot13).toString == "Uryyb Jbeyq #123")
assert(("Hello World #123" map rot47).toString == "w6==@ (@C=5 R`ab")
Make a string uppercase
Transform
"Space Monkey" into "SPACE MONKEY"
scala
println("Space Monkey".toUpperCase)
Make a string lowercase
Transform
"Caps ARE overRated" into "caps are overrated"
scala
"Caps ARE overRated".toLowerCase
Capitalise the first letter of each word
Transform
"man OF stEEL" into "Man Of Steel"
scala
def capitalize(s: String) = { s(0).toUpperCase + s.substring(1, s.length).toLowerCase }
"man OF stEEL".split("\\s") foreach {(x) => text.append(capitalize(x)).append(" ")}
"man OF stEEL".split("\\s") foreach {(x) => text.append(capitalize(x)).append(" ")}
val text = WordUtils.capitalizeFully("man OF stEEL")
val text = StringUtils.join("man OF stEEL".split("\\s") map {(x) => StringUtils.capitalize(x.toLowerCase) + " "})
// can be solved without external libraries
(("man OF stEEL" toLowerCase) split " " map (_ capitalize)).mkString(" ")
(("man OF stEEL" toLowerCase) split " " map (_ capitalize)).mkString(" ")
// This is just a slightly more compact form of the previous solution (my fav).
// It would be nice if split defaulted to whitespace (precompiled reg ex).
"man OF stEEL".toLowerCase.split(" ").map(_.capitalize) mkString " "
// It would be nice if split defaulted to whitespace (precompiled reg ex).
"man OF stEEL".toLowerCase.split(" ").map(_.capitalize) mkString " "
Find the distance between two points
scala
val distance$ = distance((34, 78), (67, -45))
println(distance$)
println(distance$)
val distance$ = distance(new Point(34, 78), new Point(67, -45))
println(distance$)
println(distance$)
def distance (p1: (Int, Int), p2: (Int, Int)) = {
val (p1x, p1y) = p1
val (p2x, p2y) = p2
val dx = p1x - p2x
val dy = p1y - p2y
Math.sqrt(dx*dx + dy*dy)
}
println(distance((34, 78), (67, -45)))
val (p1x, p1y) = p1
val (p2x, p2y) = p2
val dx = p1x - p2x
val dy = p1y - p2y
Math.sqrt(dx*dx + dy*dy)
}
println(distance((34, 78), (67, -45)))
Zero pad a number
Given the number 42, pad it to 8 characters like 00000042
scala
val formatted = String.format("%08d", int2Integer(42))
printf("%08d\n", 42)
println("%08d".format(42))
Right Space pad a number
Given the number 1024 right pad it to 6 characters
"1024 "
scala
val formatted = String.format("%-6d", int2Integer(1024))
printf("%-6d\n", 1024)
println("%-6d".format(1024))
Format a decimal number
Format the number 7/8 as a decimal with 2 places: 0.88
scala
val formatted = String.format("%3.2f", double2Double(7./8.))
printf("%3.2f\n", 7./8.)
Left Space pad a number
Given the number 73 left pad it to 10 characters
" 73"
scala
val formatted = String.format("%10d", int2Integer(73))
printf("%10d\n", 73)
Generate a random integer in a given range
Produce a random integer between 100 and 200 inclusive
scala
val rnd = new GenRandInt(100, 200)
val randomInt = rnd.next
val randomInt = rnd.next
val rnd = new scala.util.Random
val range = 100 to 200
println(range(rnd.nextInt(range length)))
val range = 100 to 200
println(range(rnd.nextInt(range length)))
Generate a repeatable random number sequence
Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
scala
val rnd = new scala.util.Random(12345)
(1 until 6) foreach { (_) => printf("%d ", 100 + rnd.nextInt(200)) } ; println()
rnd.setSeed(12345)
(1 until 6) foreach { (_) => printf("%d ", 100 + rnd.nextInt(200)) } ; println()
(1 until 6) foreach { (_) => printf("%d ", 100 + rnd.nextInt(200)) } ; println()
rnd.setSeed(12345)
(1 until 6) foreach { (_) => printf("%d ", 100 + rnd.nextInt(200)) } ; println()
Check if a string matches a regular expression
Display
"ok" if "Hello" matches /[A-Z][a-z]+/
scala
if ("Hello".matches("[A-Z][a-z]+")) println("ok")
Check if a string matches with groups
Display
"two" if "one two three" matches /one (.*) three/
scala
val m = Pattern.compile("one (.*) three").matcher("one two three")
if (m.matches) println(m.group(1))
if (m.matches) println(m.group(1))
Check if a string contains a match to a regular expression
Display
"ok" if "abc 123 @#$" matches /\d+/
scala
if (Pattern.compile("\\d+").matcher("abc 123 @#$").find) println("ok")
Loop through a string matching a regex and performing an action for each match
Create a list
[fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
scala
val m = Pattern.compile("\\((\\w+)\\):(\\d+)").matcher("(fish):1 sausage (cow):3 tree (boat):4")
var list : List[String] = Nil
while (m.find) list = (m.group(1) + m.group(2)) :: list ; list = list.reverse
var list : List[String] = Nil
while (m.find) list = (m.group(1) + m.group(2)) :: list ; list = list.reverse
Replace the first regex match in a string with a static string
Transform
"Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
scala
val replaced = "Red Green Blue".replaceFirst("e", "*")
Replace all regex matches in a string with a static string
Transform
"She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
scala
val replaced = "She sells sea shells".replaceAll("se\\w+", "X")
Replace all regex matches in a string with a dynamic string
Transform
"The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
scala
val m = Pattern.compile("\\{(\\w+)\\}").matcher("The {Quick} Brown {Fox}")
val sb = new StringBuffer(32) ; val rsb = new StringBuffer(8)
while (m.find) { rsb.replace(0, rsb.length, m.group(1)) ; m.appendReplacement(sb, rsb.reverse.toString) }
m.appendTail(sb)
val sb = new StringBuffer(32) ; val rsb = new StringBuffer(8)
while (m.find) { rsb.replace(0, rsb.length, m.group(1)) ; m.appendReplacement(sb, rsb.reverse.toString) }
m.appendTail(sb)
Define an empty list
Assign the variable
"list" to a list with no elements
scala
val list = Nil
val list = List()
val list : List[String] = List()
Define a static list
Define the list
[One, Two, Three, Four, Five]
scala
val list = "One" :: "Two" :: "Three" :: "Four" :: "Five" :: Nil
val list = List("One", "Two", "Three", "Four", "Five")
val list: List[String] = List("One", "Two", "Three", "Four", "Five")
Join the elements of a list, separated by commas
Given the list
[Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
scala
val result =
((fruit.tail foldLeft (new StringBuilder(fruit.head))) {(acc, e) => acc.append(", ").append(e)}).toString
((fruit.tail foldLeft (new StringBuilder(fruit.head))) {(acc, e) => acc.append(", ").append(e)}).toString
val result = fruit.mkString(",")
val fruit = List[String]("Apple", "Banana", "Carrot")
println(fruit.mkString(", "))
println(fruit.mkString(", "))
Join the elements of a list, in correct english
Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join(
join(
join(
join(
join(
[Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join(
[One, Two]) = "One and Two"
join(
[Lonely]) = "Lonely"
join(
[]) = ""
scala
def join(list : List[String]) : String = list match {
case List() => ""
case List(x) => x
case List(x,y) => x + " and " + y
case List(x,y,z) => x + ", " + y + ", and " + z
case _ => list(0) + ", " + join(list.tail)
}
case List() => ""
case List(x) => x
case List(x,y) => x + " and " + y
case List(x,y,z) => x + ", " + y + ", and " + z
case _ => list(0) + ", " + join(list.tail)
}
def join(list : List[String]) : String = list match {
case List() => ""
case List(x) => x
case List(x,y) => x + " and " + y
case List(x,y,z) => x + ", " + y + ", and " + z
case x::xs => x + ", " + join(xs)
}
case List() => ""
case List(x) => x
case List(x,y) => x + " and " + y
case List(x,y,z) => x + ", " + y + ", and " + z
case x::xs => x + ", " + join(xs)
}
def join[T](list : List[T]) = list match {
case xs if xs.size < 3 => xs.mkString(" and ")
case xs => xs.init.mkString(", ") + ", and " + xs.last
}
case xs if xs.size < 3 => xs.mkString(" and ")
case xs => xs.init.mkString(", ") + ", and " + xs.last
}
Produce the combinations from two lists
Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters
["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
scala
val combinations =
(numbers foldLeft List[Pair[String, Int]]()) { (acc : List[Pair[String, Int]], number : Int) =>
acc ::: (letters map { (letter : String) => Pair(letter : String, number : Int) }) }
(numbers foldLeft List[Pair[String, Int]]()) { (acc : List[Pair[String, Int]], number : Int) =>
acc ::: (letters map { (letter : String) => Pair(letter : String, number : Int) }) }
def product(set1 : List[_], set2 : List[_]) : List[Pair[_, _]] =
{
val p = new mutable.ArrayBuffer[Pair[_, _]]()
for (e1 <- set1) for (e2 <- set2) p += Pair(e1, e2)
p.toList
}
// ------
val combinations =
product(numbers, letters) map { (c) => c match { case Pair(number, letter) => Pair(letter, number) } }
{
val p = new mutable.ArrayBuffer[Pair[_, _]]()
for (e1 <- set1) for (e2 <- set2) p += Pair(e1, e2)
p.toList
}
// ------
val combinations =
product(numbers, letters) map { (c) => c match { case Pair(number, letter) => Pair(letter, number) } }
val letters = List('a', 'b', 'c')
val numbers = List(4, 5)
for { l <- letters; n <- numbers } yield (l,n)
val numbers = List(4, 5)
for { l <- letters; n <- numbers } yield (l,n)
From a List Produce a List of Duplicate Entries
Taking a list:
Write the code to produce a list of duplicates in the list:
["andrew", "bob", "chris", "bob"]
Write the code to produce a list of duplicates in the list:
["bob"]
scala
List("andrew", "bob", "chris", "bob")
.groupBy(identity)
.filter( person => person._2.size > 1)
.map(_._1)
.groupBy(identity)
.filter( person => person._2.size > 1)
.map(_._1)
val l = List("andrew", "bob", "chris", "bob")
l.diff(l.distinct)
l.diff(l.distinct)
Fetch an element of a list by index
Given the list
[One, Two, Three, Four, Five], fetch the third element ('Three')
scala
val result = list(2)
Fetch the last element of a list
Given the list
[Red, Green, Blue], access the last element ('Blue')
scala
val result = list.last
val result = (list.drop(list.length - 1)).head
Find the common items in two lists
Given two lists, find the common items. E.g. given beans =
['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
scala
val beans = "broad" :: "mung" :: "black" :: "red" :: "white" :: Nil
val colors = "black" :: "red" :: "blue" :: "green" :: Nil
val common = beans intersect colors
val colors = "black" :: "red" :: "blue" :: "green" :: Nil
val common = beans intersect colors
Display the unique items in a list
Display the unique items in a list, e.g. given ages =
[18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
scala
val ages = (18 :: 16 :: 17 :: 18 :: 16 :: 19 :: 14 :: 17 :: 19 :: 18 :: Nil) removeDuplicates
Remove an element from a list by index
Given the list
[Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
scala
val (fl, fr) = fruit.splitAt(0) ; fruit = fl ::: fr.tail
fruit = fruit.tail
fruit = fruit.drop(1)
fruits = fruits.remove(fruits.indexOf(_) == 0)
Remove the last element of a list
scala
fruit = fruit.init
fruit = fruit.take(fruit.length - 1)
Rotate a list
Given a list
["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
scala
items = items.tail ::: List(items.head)
items = (items.head :: ((items.tail).reverse)).reverse
Gather together corresponding elements from multiple lists
Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first =
['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
scala
def zip3(l1 : List[_], l2 : List[_],l3 : List[_]) : List[Tuple3[_, _, _]] =
{
def zip3$ (l1$ : List[_], l2$ : List[_], l3$ : List[_], acc : List[Tuple3[_, _, _]]) : List[Tuple3[_, _, _]] = l1$ match
{
case Nil => acc reverse
case l1$head :: l1$tail => zip3$(l1$tail, l2$.tail, l3$.tail, Tuple3(l1$head, l2$.head, l3$.head) :: acc)
}
zip3$(l1, l2, l3, List[Tuple3[_,_,_]]())
}
// ------
val result = zip3(first, last, years)
{
def zip3$ (l1$ : List[_], l2$ : List[_], l3$ : List[_], acc : List[Tuple3[_, _, _]]) : List[Tuple3[_, _, _]] = l1$ match
{
case Nil => acc reverse
case l1$head :: l1$tail => zip3$(l1$tail, l2$.tail, l3$.tail, Tuple3(l1$head, l2$.head, l3$.head) :: acc)
}
zip3$(l1, l2, l3, List[Tuple3[_,_,_]]())
}
// ------
val result = zip3(first, last, years)
val first = List("Bruce", "Tommy Lee", "Bruce")
val last = List("Willis", "Jones", "Lee")
val years = List(1955, 1946, 1940)
val results = (first, last, years).zipped.toList
println(results)
val last = List("Willis", "Jones", "Lee")
val years = List(1955, 1946, 1940)
val results = (first, last, years).zipped.toList
println(results)
List Combinations
Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites =
['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
scala
def product(set1 : List[_], set2 : List[_]) : List[Pair[_, _]] =
{
val p = new mutable.ArrayBuffer[Pair[_, _]]()
for (e1 <- set1) for (e2 <- set2) p += Pair(e1, e2)
p.toList
}
// ------
val cards = product(suites, faces)
printf("Deck has %d cards\n", cards.length)
if (cards.contains(Pair("h", "A"))) println("Deck contains 'Ace of Hearts'")
else println("'Ace of Hearts' not in this deck")
{
val p = new mutable.ArrayBuffer[Pair[_, _]]()
for (e1 <- set1) for (e2 <- set2) p += Pair(e1, e2)
p.toList
}
// ------
val cards = product(suites, faces)
printf("Deck has %d cards\n", cards.length)
if (cards.contains(Pair("h", "A"))) println("Deck contains 'Ace of Hearts'")
else println("'Ace of Hearts' not in this deck")
Perform an operation on every item of a list
Perform an operation on every item of a list, e.g.
for the list
the list of sizes of the strings, e.g.
for the list
["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g.
[2, 3, 4, 5]
scala
val sizes = List("ox", "cat", "deer", "whale") map {_ size}
assert(sizes == List(2, 3, 4, 5))
val sizes = List("ox", "cat", "deer", "whale") map {_ size}
assert(sizes == List(2, 3, 4, 5))
Split a list of things into numbers and non-numbers
Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
split the list into numbers and non-numbers.
scala
val now = new java.util.Date()
val result = List("hello", 25, 3.14, now) partition { _.isInstanceOf[Number] }
assert(result == (List(25, 3.14), List("hello", now)))
val result = List("hello", 25, 3.14, now) partition { _.isInstanceOf[Number] }
assert(result == (List(25, 3.14), List("hello", now)))
Test if a condition holds for all items of a list
Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.
scala
List(2, 3, 4).forall { _ > 1 }
List(2, 3, 4).forall { x => x > 1 }
Test if a condition holds for any items of a list
Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list.
scala
List(2, 3, 4).exists { _ > 3 }
List(2, 3, 4).exists { x => x > 3 }
Define an empty map
scala
val map = mutable.Map.empty
val map = mutable.HashMap.empty[String, Int]
Define an unmodifiable empty map
scala
val map = immutable.Map.empty
val map = immutable.TreeMap.empty[String, Int]
Define an initial map
Define the map
{circle:1, triangle:3, square:4}
scala
val shapes = immutable.TreeMap("circle" -> 1, "triangle" -> 3, "square" -> 4)
val shapes = mutable.Map.empty[String, Int]
shapes += "circle" -> 1
shapes += "triangle" -> 3
shapes += "square" -> 4
shapes += "circle" -> 1
shapes += "triangle" -> 3
shapes += "square" -> 4
var shapes = immutable.Map.empty[String, Int]
shapes = shapes + ("circle" -> 1)
shapes = shapes + ("triangle" -> 3)
shapes = shapes + ("square" -> 4)
shapes = shapes + ("circle" -> 1)
shapes = shapes + ("triangle" -> 3)
shapes = shapes + ("square" -> 4)
Check if a key exists in a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
scala
if (pets.contains("mary")) println("ok")
Retrieve a value from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
scala
if (pets.contains("joe")) println(pets("joe"))
println(pets.getOrElse("joe", "*** no pet owned ***"))
Add an entry to a map
Given an empty pets map, add the mapping from
"rob" to "dog"
scala
pets += "rob" -> "dog"
Remove an entry from a map
Given a map pets
{joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
scala
val pet = pets("bill") ; pets -= "bill" ; println(pet)
println(pets.removeKey("bill") match { case Some(pet) => pet ; case None => "***" })
Create a histogram map from a list
Given the list
[a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
scala
list foreach { (x) => histogram += x -> (histogram.getOrElse(x, 0) + 1) }
val data = List("a", "b", "a", "c", "b", "b")
val keys = data removeDuplicates
val hist = Map.empty[String, Int] ++ keys.map{ k => (k, (data count (_==k)))}
assert(hist == Map("a"->2, "b"->3, "c"->1))
val keys = data removeDuplicates
val hist = Map.empty[String, Int] ++ keys.map{ k => (k, (data count (_==k)))}
assert(hist == Map("a"->2, "b"->3, "c"->1))
val histEntries = for {
key <- data.removeDuplicates
count = data.count(_ == key)
} yield (key -> count)
val hist = Map(histEntries: _*)
key <- data.removeDuplicates
count = data.count(_ == key)
} yield (key -> count)
val hist = Map(histEntries: _*)
value.foldLeft(Map[T, Int]()){
(m, c) => m.updated(c, m.getOrElse(c, 0) + 1)
}
(m, c) => m.updated(c, m.getOrElse(c, 0) + 1)
}
Categorise a list
Given the list
[one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
scala
list foreach { (x) => map += x.length -> (x :: map.getOrElse(x.length, Nil)) }
list foreach { (x) => map += x.length -> (map.getOrElse(x.length, Nil) ::: List(x)) }
List("one", "two", "three", "four", "five") groupBy (_ size)
Perform an action if a condition is true (IF .. THEN)
Given a variable name, if the value is
"Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
scala
val name = "Bob"
if (name.equals("Bob")) printf("Hello, %s!\n", name)
if (name.equals("Bob")) printf("Hello, %s!\n", name)
val name = "Bob"
// Scala supports operator overloading, so the following works correctly
if (name == "Bob") printf("Hello, %s!\n", name)
// Scala supports operator overloading, so the following works correctly
if (name == "Bob") printf("Hello, %s!\n", name)
Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)
Given a variable age, if the value is greater than 42 display
"You are old", otherwise display "You are young"
scala
val age = 42
if (age > 42) println("You are old") else println("You are young")
if (age > 42) println("You are old") else println("You are young")
println( "You are " + ( if ( age > 42 ) "old" else "young" ) )
Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)
scala
val age = 65
if (age > 84) println("You are really ancient")
else if (age > 30) println("You are middle-aged")
else println("You are young")
if (age > 84) println("You are really ancient")
else if (age > 30) println("You are middle-aged")
else println("You are young")
Replacing a conditional with many branches with a switch/case statement
Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
scala
object FourToTwenties {
def unapply (n: Int) = (4 to 20).contains(n % 100)
}
def suffix (n: Int) = {
n match {
case FourToTwenties() => "th"
case n if n % 10 == 1 => "st"
case n if n % 10 == 2 => "nd"
case n if n % 10 == 3 => "rd"
case _ => "th"
}
}
for (n <- 1 to 40) {
println(n.toString + suffix(n))
}
def unapply (n: Int) = (4 to 20).contains(n % 100)
}
def suffix (n: Int) = {
n match {
case FourToTwenties() => "th"
case n if n % 10 == 1 => "st"
case n if n % 10 == 2 => "nd"
case n if n % 10 == 3 => "rd"
case _ => "th"
}
}
for (n <- 1 to 40) {
println(n.toString + suffix(n))
}
Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)
Starting with a variable x=1, Print the sequence
"1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
scala
var x = 1 ; while (x < 150) { printf("%d,", x) ; x *= 2 }
Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)
Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be
"4,2,1,2,6"
scala
val dice = new GenRandInt(1, 6) ; var rnd = 0 ; var fmt = ""
do { rnd = dice.next ; fmt = if (rnd != 6) "%d," else "%d" ; printf(fmt, rnd) } while (rnd != 6)
do { rnd = dice.next ; fmt = if (rnd != 6) "%d," else "%d" ; printf(fmt, rnd) } while (rnd != 6)
Perform an action a fixed number of times (FOR)
Display the string
"Hello" five times like "HelloHelloHelloHelloHello"
scala
// Using overloaded '*' operator (String-specific)
print("Hello" * 5)
print("Hello" * 5)
List.range(0, 5) foreach { (_) => print("Hello") }
for (_ <- List.range(0, 5)) print("Hello")
// Lazy version
for (_ <- Stream.range(0, 5)) print("Hello")
for (_ <- Stream.range(0, 5)) print("Hello")
dotimes(5, _ => print("Hello"))
(0 until 5) foreach { (_) => print("Hello") }
5 times { print("Hello") }
Perform an action a fixed number of times with a counter
Display the string
"10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
scala
for (i <- List.range(1, 11).reverse) printf("%d .. ", i) ; println("Liftoff!")
for (i <- List.range(-10, 0)) printf("%d .. ", (-i)) ; println("Liftoff!")
var i = 10 ; while (i > 0) { printf("%d .. ", i) ; i -= 1 } ; println("Liftoff!")
for (i <- -10 to -1) printf("%d .. ", (-i)) ; println("Liftoff!")
Read the contents of a file into a string
scala
val text = FileUtils.readFileToString(new File("Solution467.scala"))
val text = Source.fromFile("Solution1256.scala").mkString("")
Process a file one line at a time
Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
1> First line of file
2> Second line of file
3> Third line of file
scala
val source = Source.fromFile(new File("Solution468.scala")).getLines
var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 }
var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 }
val source = Source.fromFile(new File("Solution469.scala")).getLines
for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), line) }
for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), line) }
Write a string to a file
scala
FileUtils.writeStringToFile(new File("test.txt"), "This line overwites file contents!")
val fw = new FileWriter("test.txt") ; fw.write("This line overwites file contents!") ; fw.close()
Append to a file
scala
val fw = new FileWriter("test.txt", true) ; fw.write("This line appended to file!") ; fw.close()
Process each file in a directory
scala
for (file <- new File("c:\\").listFiles) { processFile(file) }
Process each file in a directory recursively
scala
processDirectory(new File("c:\\"))
Parse a date and time from a string
Given the string
"2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
scala
val date = new SimpleDateFormat("yyy-MM-dd HH:mm").parse("2008-05-06 13:29")
Display information about a date
Display the day of month, day of year, month name and day name of the day 8 days from now.
scala
import java.util.Calendar
import java.text.SimpleDateFormat
val formatString = "d, D, MMMM, EEEE"
val cal = Calendar.getInstance
cal.add(Calendar.DAY_OF_YEAR, 8)
println(new SimpleDateFormat(formatString) format cal.getTime)
import java.text.SimpleDateFormat
val formatString = "d, D, MMMM, EEEE"
val cal = Calendar.getInstance
cal.add(Calendar.DAY_OF_YEAR, 8)
println(new SimpleDateFormat(formatString) format cal.getTime)
Display a date in different locales
Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like:
Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009
(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009
(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
scala
val date = new GregorianCalendar(2009, JANUARY, 1).getTime
val locales = List(ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale("nl"))
println(locales.map{getDateInstance(FULL, _).format(date)}.mkString("\n"))
val locales = List(ENGLISH, FRENCH, ITALIAN, GERMAN, new Locale("nl"))
println(locales.map{getDateInstance(FULL, _).format(date)}.mkString("\n"))
Display the current date and time
Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
If you can also do this without creating a Date object you can show that too.
scala
println(new java.util.Date)
Define a class
Declare a class named Greeter that takes a string on creation and greets using this string if you call the
"greet" method.
scala
class Greeter(whom : String) { def greet() = { printf("Hello %s\n", whom) } }
(new Greeter("world!")).greet()
(new Greeter("world!")).greet()
Instantiate object with mutable state
Reimplement the Greeter class so that the
For example, if the greetee is changed to
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".
For example, if the greetee is changed to
'Tommy' using the setter, the 'greet' method would display:
Hello, Tommy!
The getter would then be used to display the line:
I have just greeted Tommy.
scala
class Greeter(var whom: String) {
def greet() = println("Hello " + whom + "!")
}
// Is this really a private value with getter and setter methods,
// or just a public mutable value?
val greeter = new Greeter("World")
greeter.greet()
greeter.whom = "Tommy"
greeter.greet()
printf("I have just greeted %s.\n", greeter.whom)
def greet() = println("Hello " + whom + "!")
}
// Is this really a private value with getter and setter methods,
// or just a public mutable value?
val greeter = new Greeter("World")
greeter.greet()
greeter.whom = "Tommy"
greeter.greet()
printf("I have just greeted %s.\n", greeter.whom)
Implement Inheritance Heirarchy
Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:
* A non-mutable
* A
* A
* A non-mutable
'name' property or data member set by derived or descendant classes at construction time
* A
'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A
'print' method (also for overriding) will display the shape's name, area, and all shape-specific values
Two derived or descendant classes will be created:
* Circle -> Constructor requires a 'radius' argument, and a 'circumference' method to be implemented
* Rectangle -> Constructor requires 'length' and 'breadth' arguments, and a 'perimeter' method to be implemented
Instantiate an object of each class, and invoke each objects 'print' method to show relevant details.
scala
abstract class Shape (val name: String) {
def area : Double
def print()
}
class Circle (val radius: Double) extends Shape("Circle") {
def area = Math.Pi * radius * radius
def circumference = 2 * Math.Pi * radius
def print() {
println("I'm a " + name + " with")
printf(" * radius = %.2f\n", radius)
printf(" * area = %.2f\n", area)
printf(" * circumference = %.2f\n\n", circumference)
}
}
class Rectangle (val length: Double, val breadth: Double) extends Shape("Rectangle") {
def area = length * breadth
def perimeter = 2 * (length + breadth)
def print() {
println("I'm a " + name + " with")
printf(" * length = %.2f\n", length)
printf(" * breadth = %.2f\n", breadth)
printf(" * area = %.2f\n", area)
printf(" * perimeter = %.2f\n\n", perimeter)
}
}
val shapes = List(new Circle(5.4), new Rectangle(7.8, 6.5))
shapes foreach (_.print)
def area : Double
def print()
}
class Circle (val radius: Double) extends Shape("Circle") {
def area = Math.Pi * radius * radius
def circumference = 2 * Math.Pi * radius
def print() {
println("I'm a " + name + " with")
printf(" * radius = %.2f\n", radius)
printf(" * area = %.2f\n", area)
printf(" * circumference = %.2f\n\n", circumference)
}
}
class Rectangle (val length: Double, val breadth: Double) extends Shape("Rectangle") {
def area = length * breadth
def perimeter = 2 * (length + breadth)
def print() {
println("I'm a " + name + " with")
printf(" * length = %.2f\n", length)
printf(" * breadth = %.2f\n", breadth)
printf(" * area = %.2f\n", area)
printf(" * perimeter = %.2f\n\n", perimeter)
}
}
val shapes = List(new Circle(5.4), new Rectangle(7.8, 6.5))
shapes foreach (_.print)
Implement and use an Interface
Create a Serializable interface consisting of
* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types
Next, create a Person class which has
'save' and 'restore' methods, each of which:
* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types
'int' and 'string')
Next, create a Person class which has
'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
scala
class Person (var name: String, var age: Int) extends Serializable
val p1 = new Person("John", 21)
val output = new ByteArrayOutputStream()
val oos = new ObjectOutputStream(output)
oos.writeObject(p1)
oos.flush
oos.close
val input = new ByteArrayInputStream(output.toByteArray())
val ois = new ObjectInputStream(input)
val p2 = ois.readObject().asInstanceOf[Person]
assert(p2.name == "John")
assert(p2.age == 21)
val p1 = new Person("John", 21)
val output = new ByteArrayOutputStream()
val oos = new ObjectOutputStream(output)
oos.writeObject(p1)
oos.flush
oos.close
val input = new ByteArrayInputStream(output.toByteArray())
val ois = new ObjectInputStream(input)
val p2 = ois.readObject().asInstanceOf[Person]
assert(p2.name == "John")
assert(p2.age == 21)
Check your language appears on the langref.org site
Your language name should appear within the HTML found at the http:
//langreg.org main page.
scala
val url = "http://langref.org/" ; val language = "scala" ; val srchexp = url + language;
val source = Source.fromURL(url).getLines
while (source.hasNext) if (source.next.contains(srchexp)) printf("Language %s exists @ %s\n", language, url)
val source = Source.fromURL(url).getLines
while (source.hasNext) if (source.next.contains(srchexp)) printf("Language %s exists @ %s\n", language, url)
Send an email
Use library functions, classes or objects to create a short email addressed to your own email address. The subject should be,
"Greetings from langref.org", and the user should be prompted for the message body, and whether to cancel or proceed with sending the email.
scala
// requires Java Mail API (mail.jar), which must be in classpath
import javax.mail._
import javax.mail.internet._
import java.util.Properties._
// Get the user's message
println("Enter the text you wish to send in the message (hit Ctrl-D to finish):")
var bodyText = ""
var line = readLine
while (line != null) {
bodyText += line
line = readLine
}
// Confirm they want to send
println("Are you sure you want to send the message? [y/N]")
val yesOrNo = readLine
if (yesOrNo != "y" && yesOrNo != "Y") {
println("Aborted")
exit
}
// Set up the mail object
val properties = System.getProperties
properties.put("mail.smtp.host", "localhost")
val session = Session.getDefaultInstance(properties)
val message = new MimeMessage(session)
// Set the from, to, subject, body text
message.setFrom(new InternetAddress("test@example.org"))
message.setRecipients(Message.RecipientType.TO, "spam@mopoke.co.uk")
message.setSubject("Greetings from langref.org")
message.setText(bodyText)
// And send it
Transport.send(message)
import javax.mail._
import javax.mail.internet._
import java.util.Properties._
// Get the user's message
println("Enter the text you wish to send in the message (hit Ctrl-D to finish):")
var bodyText = ""
var line = readLine
while (line != null) {
bodyText += line
line = readLine
}
// Confirm they want to send
println("Are you sure you want to send the message? [y/N]")
val yesOrNo = readLine
if (yesOrNo != "y" && yesOrNo != "Y") {
println("Aborted")
exit
}
// Set up the mail object
val properties = System.getProperties
properties.put("mail.smtp.host", "localhost")
val session = Session.getDefaultInstance(properties)
val message = new MimeMessage(session)
// Set the from, to, subject, body text
message.setFrom(new InternetAddress("test@example.org"))
message.setRecipients(Message.RecipientType.TO, "spam@mopoke.co.uk")
message.setSubject("Greetings from langref.org")
message.setText(bodyText)
// And send it
Transport.send(message)
Process an XML document
Given the XML Document:
<shopping>
<item name=
<item name=
</shopping>
Print out the total cost of the items, e.g. $14.50
<shopping>
<item name=
"bread" quantity="3" price="2.50"/>
<item name=
"milk" quantity="2" price="3.50"/>
</shopping>
Print out the total cost of the items, e.g. $14.50
scala
val data = <shopping>
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>
val res = for (
item <- data \ "item" ;
price = (item \ "@price").text.toDouble ;
qty = (item \ "@quantity").text.toInt)
yield (price * qty)
printf("$%.2f\n", res.sum)
<item name="bread" quantity="3" price="2.50"/>
<item name="milk" quantity="2" price="3.50"/>
</shopping>
val res = for (
item <- data \ "item" ;
price = (item \ "@price").text.toDouble ;
qty = (item \ "@quantity").text.toInt)
yield (price * qty)
printf("$%.2f\n", res.sum)
create some XML programmatically
Given the following CSV:
bread,3,2.50
milk,2,3.50
Produce the equivalent information in XML, e.g.:
<shopping>
<item name=
<item name=
</shopping>
bread,3,2.50
milk,2,3.50
Produce the equivalent information in XML, e.g.:
<shopping>
<item name=
"bread" quantity="3" price="2.50" />
<item name=
"milk" quantity="2" price="3.50" />
</shopping>
scala
<shopping>
{List("bread,3,2.50", "milk,2,3.50") map { row =>
row split ","
} map { item =>
<item name={item(0)} quantity={item(1)} price={item(2)}/>
}}
</shopping>
{List("bread,3,2.50", "milk,2,3.50") map { row =>
row split ","
} map { item =>
<item name={item(0)} quantity={item(1)} price={item(2)}/>
}}
</shopping>
Find all Pythagorean triangles with length or height less than or equal to 20
Pythagorean triangles are right angle triangles whose sides comply with the following equation:
a * a + b * b = c * c
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:
a * a + b * b = c * c
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:
[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
scala
val res = for (
x <- 1 to 20 ;
y <- x to 20 ;
z = Math.sqrt(x*x + y*y) ;
if (z.toInt == z) )
yield (x, y, z.toInt)
res.toList.sortWith { (t1, t2) =>
t1._3 < t2._3
} foreach (println(_))
x <- 1 to 20 ;
y <- x to 20 ;
z = Math.sqrt(x*x + y*y) ;
if (z.toInt == z) )
yield (x, y, z.toInt)
res.toList.sortWith { (t1, t2) =>
t1._3 < t2._3
} foreach (println(_))
(for(x <- 1 to 20;
y<- x to 20;
z<- 1 to 30;
if(z*z == x*x + y*y)) yield(x, y, z)
).sortWith(_._3 < _._3) foreach println
y<- x to 20;
z<- 1 to 30;
if(z*z == x*x + y*y)) yield(x, y, z)
).sortWith(_._3 < _._3) foreach println
( for (
a <- 1 to 20 ;
b <- a to 20 ;
c = math.sqrt( a*a + b*b )
if c.toInt == c
) yield ( a, b, c.toInt )
).sortBy {_._3} foreach println
a <- 1 to 20 ;
b <- a to 20 ;
c = math.sqrt( a*a + b*b )
if c.toInt == c
) yield ( a, b, c.toInt )
).sortBy {_._3} foreach println
Greatest Common Divisor
Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.
scala
def gcd(x: Int, y: Int): Int =
if (b == 0) x
else gcd(b, x % y)
if (b == 0) x
else gcd(b, x % y)
produces a copy of its own source code
In computing, a quine is a computer program which produces a copy of its own source code as its only output.
scala
val s="val s=%c%s%c; printf(s, 34, s, 34)"; printf(s, 34, s, 34)
Subdivide A Problem To A Pool Of Workers (No Shared Data)
Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)
Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.
Example:
-Input-
(In python syntax)
In other words, a list of random strings.
-Output-
(In python syntax)
In other words, all possible permutations of each input string are computed.
Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.
Example:
-Input-
(In python syntax)
["ab", "we", "tfe", "aoj"]
In other words, a list of random strings.
-Output-
(In python syntax)
[ ["ab", "ba", "aa", "bb", "a", "b"], ["we", "ew", "ww", "ee", "w", "e"], ...
In other words, all possible permutations of each input string are computed.
scala
// as per Java answer, doesn't duplicate chars from input string, i.e. no 'aa'
// future detaches a computation whose result can
// be applied for at a later time
import scala.actors.Futures.future
def perm(s: String): IndexedSeq[String] =
if (s.length == 1)
IndexedSeq(s)
else
s map { c =>
future {
val subperms = perm(s filter (c !=))
(subperms map (c +)) ++ subperms
}
} flatMap (_ apply ())
def perms(l: Traversable[String]) =
l map (s => future(perm(s))) map (_ apply ())
val args = Seq("ab", "we", "tfe", "aoj")
println(perms(args))
// future detaches a computation whose result can
// be applied for at a later time
import scala.actors.Futures.future
def perm(s: String): IndexedSeq[String] =
if (s.length == 1)
IndexedSeq(s)
else
s map { c =>
future {
val subperms = perm(s filter (c !=))
(subperms map (c +)) ++ subperms
}
} flatMap (_ apply ())
def perms(l: Traversable[String]) =
l map (s => future(perm(s))) map (_ apply ())
val args = Seq("ab", "we", "tfe", "aoj")
println(perms(args))
Subdivide A Problem To A Pool Of Workers (Shared Data)
Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)
Note: In this question, there should be a need for shared state between worker threads while the problem is being solved.
Example:
-Conway Game of Life-
From Wikipedia:
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbors, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.
The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the one before). The rules continue to be applied repeatedly to create further generations.
--However, for our purposes, we will assign a size to the game
Notice that in this problem, at each step or
Note: In this question, there should be a need for shared state between worker threads while the problem is being solved.
Example:
-Conway Game of Life-
From Wikipedia:
The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, live or dead. Every cell interacts with its eight neighbors, which are the cells that are directly horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with more than three live neighbours dies, as if by overcrowding.
3. Any live cell with two or three live neighbours lives on to the next generation.
4. Any dead cell with exactly three live neighbours becomes a live cell.
The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths happen simultaneously, and the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the one before). The rules continue to be applied repeatedly to create further generations.
--However, for our purposes, we will assign a size to the game
"board": 2^k * 2^k . That is, the board should be easy to subdivide.
Notice that in this problem, at each step or
"tick", each thread/process will need to share data with its neighborhood.
scala
import scala.actors.Futures.future
class Generation(gen: Array[String]) {
val width = gen(0).length
val hight = gen.length
override def toString = gen.reduceLeft(_ + "\n" + _)
def nextGen = {
// Calculate each row separately as a "future"
val ngFuture = (0 until hight).map(row => future(nextRow(row)))
// Wait for each row to finish
val ng = ngFuture.map(_ apply ())
new Generation(ng.toArray)
}
private def nextRow(row: Int): String =
(0 until width).map(nextCell(row, _)).foldLeft("")(_ + _)
private def nextCell(row: Int, col: Int) = {
liveNeighbors(row, col) match {
case 2 => cellAt(row, col)
case 3 => gameOfLife.liveCell
case _ => gameOfLife.deadCell
}
}
private def cellAt(row: Int, col: Int) =
gen((row + hight) % hight)((col + width) % width)
private def liveNeighbors(row: Int, col: Int) =
// Generate coordinate to all adjacent cells
((row-1) to (row+1)).flatMap(x => ((col-1) to (col+1)).map((x,_)))
// Remove our own cell and all dead neighbor cells
.filter(p => p != (row,col) && cellAt(p._1, p._2) == gameOfLife.liveCell)
// Get the number of cells we kept
.length
}
object gameOfLife {
val liveCell = 'O'
val deadCell = '.'
val firstGen = new Generation(Array(".O......",
"..O.....",
"OOO.....",
"........",
"........",
"........",
"........"))
def main(args: Array[String]) {
val numGens = if (args.length > 0) args(0).toInt else 3
var thisGen = firstGen
for (genNr <- 0 to numGens) {
println("Generation " + genNr)
println(thisGen)
thisGen = thisGen.nextGen
}
}
}
class Generation(gen: Array[String]) {
val width = gen(0).length
val hight = gen.length
override def toString = gen.reduceLeft(_ + "\n" + _)
def nextGen = {
// Calculate each row separately as a "future"
val ngFuture = (0 until hight).map(row => future(nextRow(row)))
// Wait for each row to finish
val ng = ngFuture.map(_ apply ())
new Generation(ng.toArray)
}
private def nextRow(row: Int): String =
(0 until width).map(nextCell(row, _)).foldLeft("")(_ + _)
private def nextCell(row: Int, col: Int) = {
liveNeighbors(row, col) match {
case 2 => cellAt(row, col)
case 3 => gameOfLife.liveCell
case _ => gameOfLife.deadCell
}
}
private def cellAt(row: Int, col: Int) =
gen((row + hight) % hight)((col + width) % width)
private def liveNeighbors(row: Int, col: Int) =
// Generate coordinate to all adjacent cells
((row-1) to (row+1)).flatMap(x => ((col-1) to (col+1)).map((x,_)))
// Remove our own cell and all dead neighbor cells
.filter(p => p != (row,col) && cellAt(p._1, p._2) == gameOfLife.liveCell)
// Get the number of cells we kept
.length
}
object gameOfLife {
val liveCell = 'O'
val deadCell = '.'
val firstGen = new Generation(Array(".O......",
"..O.....",
"OOO.....",
"........",
"........",
"........",
"........"))
def main(args: Array[String]) {
val numGens = if (args.length > 0) args(0).toInt else 3
var thisGen = firstGen
for (genNr <- 0 to numGens) {
println("Generation " + genNr)
println(thisGen)
thisGen = thisGen.nextGen
}
}
}
Create a multithreaded "Hello World"
Create a program which outputs the string
Example:
-Output-
Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!
-Notice that the threads can print in any order.
"Hello World" to the console, multiple times, using separate threads or processes.
Example:
-Output-
Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!
-Notice that the threads can print in any order.
scala
import scala.actors.Actor
List("one", "two", "three", "four").foreach { name =>
new Actor { override def act() = { println("Thread " + name + " says Hello World!") } }.start
}
List("one", "two", "three", "four").foreach { name =>
new Actor { override def act() = { println("Thread " + name + " says Hello World!") } }.start
}
List("one", "two", "three", "four").foreach { name =>
new Thread { override def run() = { println("Thread " + name + " says Hello World!") } }.start
}
new Thread { override def run() = { println("Thread " + name + " says Hello World!") } }.start
}
import scala.actors.Futures._
List("one", "two", "three", "four").foreach(name => future(println("Thread " + name + " says hi")))
List("one", "two", "three", "four").foreach(name => future(println("Thread " + name + " says hi")))
Create read/write lock on a shared resource.
Create multiple threads or processes who are either readers or writers. There should be more readers then writers.
(From Wikipedia):
Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.
Example:
-Output-
Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...
--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
(From Wikipedia):
Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.
Example:
-Output-
Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...
--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
scala
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock
import scala.util.Random
class Reader(name: String, lock: ReadLock) extends Thread {
override def run() = {
println(name)
while (true) {
if (!lock.tryLock)
{
println("Thread " + name + " tried to read the value, but could not.")
lock.lock
}
println("Thread " + name + " says that the value is " + rwLockOnSharedResource.value)
lock.unlock
Thread.sleep(3) // Generates output more similar to the problem description
}
}
}
class Writer(name: String, lock: WriteLock) extends Thread {
override def run() = {
while (true) {
if (!lock.tryLock) {
println("Thread " + name + " tried to write the value, but could not.")
lock.lock
}
println("Thread " + name + " is taking the lock.")
rwLockOnSharedResource.value = rwLockOnSharedResource.nextValue
println("Thread " + name + " is changing the value to " + rwLockOnSharedResource.value)
lock.unlock
println("Thread " + name + " is releasing the lock.")
Thread.sleep(3) // Generates output more similar to the problem description
}
}
}
object rwLockOnSharedResource {
private val maxValue = 10
private val randomVal = new Random
var value = nextValue
def nextValue = randomVal.nextInt(maxValue)
def main(args: Array[String]) = {
val rwLock = new ReentrantReadWriteLock(true)
val threadNames = List("one", "two", "three", "four", "five")
val readerCnt = threadNames.length * 2 / 3
val readerNames = threadNames.take(readerCnt)
val writerNames = threadNames.drop(readerCnt)
readerNames.foreach(new Reader(_, rwLock.readLock).start)
writerNames.foreach(new Writer(_, rwLock.writeLock).start)
}
}
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock
import scala.util.Random
class Reader(name: String, lock: ReadLock) extends Thread {
override def run() = {
println(name)
while (true) {
if (!lock.tryLock)
{
println("Thread " + name + " tried to read the value, but could not.")
lock.lock
}
println("Thread " + name + " says that the value is " + rwLockOnSharedResource.value)
lock.unlock
Thread.sleep(3) // Generates output more similar to the problem description
}
}
}
class Writer(name: String, lock: WriteLock) extends Thread {
override def run() = {
while (true) {
if (!lock.tryLock) {
println("Thread " + name + " tried to write the value, but could not.")
lock.lock
}
println("Thread " + name + " is taking the lock.")
rwLockOnSharedResource.value = rwLockOnSharedResource.nextValue
println("Thread " + name + " is changing the value to " + rwLockOnSharedResource.value)
lock.unlock
println("Thread " + name + " is releasing the lock.")
Thread.sleep(3) // Generates output more similar to the problem description
}
}
}
object rwLockOnSharedResource {
private val maxValue = 10
private val randomVal = new Random
var value = nextValue
def nextValue = randomVal.nextInt(maxValue)
def main(args: Array[String]) = {
val rwLock = new ReentrantReadWriteLock(true)
val threadNames = List("one", "two", "three", "four", "five")
val readerCnt = threadNames.length * 2 / 3
val readerNames = threadNames.take(readerCnt)
val writerNames = threadNames.drop(readerCnt)
readerNames.foreach(new Reader(_, rwLock.readLock).start)
writerNames.foreach(new Writer(_, rwLock.writeLock).start)
}
}
Separate user interaction and computation.
Allow your program to accept user interaction while conducting a long running computation.
Example:
Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I
--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
Example:
Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
["abcdef", "abcefd", ... ] (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I
'll let my worker thread know... (input thread)
We're quitting! Alright! (worker thread)
--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
scala
import scala.actors.Actor
object Worker extends Actor {
def perm(s: String): List[String] =
s.length match {
case 0 => Nil
case 1 => s :: Nil
case sLen => (0 to sLen-1).map(i => perm(s.take(i) + s.drop(i+1)).map(s(i) + _)).toList.flatten
}
def act() = react {
case "EXIT" =>
println("We're quitting! Alright!")
case (s: String) =>
val r = perm(s)
println("Done working on " + s + "!")
print("[ ")
r.foreach(s => print("\"" + s + "\", "))
println("]")
act()
}
}
object userInteractBackgroundCalc {
def main(args: Array[String]) {
print("Hello user! ")
Worker.start
var str = ""
do {
println("Please input a string to permute:")
str = readLine()
Worker ! str
} while (str != "EXIT")
}
}
object Worker extends Actor {
def perm(s: String): List[String] =
s.length match {
case 0 => Nil
case 1 => s :: Nil
case sLen => (0 to sLen-1).map(i => perm(s.take(i) + s.drop(i+1)).map(s(i) + _)).toList.flatten
}
def act() = react {
case "EXIT" =>
println("We're quitting! Alright!")
case (s: String) =>
val r = perm(s)
println("Done working on " + s + "!")
print("[ ")
r.foreach(s => print("\"" + s + "\", "))
println("]")
act()
}
}
object userInteractBackgroundCalc {
def main(args: Array[String]) {
print("Hello user! ")
Worker.start
var str = ""
do {
println("Please input a string to permute:")
str = readLine()
Worker ! str
} while (str != "EXIT")
}
}
Put a internationalizate of HelloWorld program
Set locale to
In pseudocode:
Void main ()
"es" (spanish) and provide a program that changes outputs ("Helloworld") depending of locale.
In pseudocode:
Void main ()
{
Locale.set("es")
print.translate("Helloworld, Locale.get)
}
scala
import scala.collection.mutable
object SolutionXX {
// START
class I18N(s: String) {
def translate = {
Locale.current match {
case None => s
case Some(loc) => loc.translate(s).getOrElse(s)
}
}
}
implicit def stringToI18N(s: String) = new I18N(s)
class Locale(val name: String, map: Map[String, String]) {
Locale.registerLocale(this)
def translate(s: String) = map.get(s)
}
object Locale {
var current: Option[Locale] = None
var locales: mutable.Map[String, Locale] = mutable.Map()
def registerLocale(locale: Locale) {
locales += (locale.name -> locale)
//NOTE : here we could check locale translation completeness against others and prints whose entries are missing
}
def set(locale: String) {
current = locales.get(locale)
}
}
val helloworld = "Hello World!";
//NOTE :: just read out properties files in maps below
val en = new Locale("en", Map(helloworld -> "Hello World!"))
val fr = new Locale("fr", Map(helloworld -> "Bonjour le Monde !"))
val es = new Locale("es", Map(helloworld -> "¡Hola Mundo!"))
def main(args: Array[String]) {
def printIn(locale: Option[String]) {
locale match {
case None =>
case Some(l) => Locale.set(l)
}
println(helloworld.translate)
}
printIn(None)
printIn(Some("en"))
printIn(Some("fr"))
printIn(Some("es"))
printIn(Some("alien"))
}
// END
}
object SolutionXX {
// START
class I18N(s: String) {
def translate = {
Locale.current match {
case None => s
case Some(loc) => loc.translate(s).getOrElse(s)
}
}
}
implicit def stringToI18N(s: String) = new I18N(s)
class Locale(val name: String, map: Map[String, String]) {
Locale.registerLocale(this)
def translate(s: String) = map.get(s)
}
object Locale {
var current: Option[Locale] = None
var locales: mutable.Map[String, Locale] = mutable.Map()
def registerLocale(locale: Locale) {
locales += (locale.name -> locale)
//NOTE : here we could check locale translation completeness against others and prints whose entries are missing
}
def set(locale: String) {
current = locales.get(locale)
}
}
val helloworld = "Hello World!";
//NOTE :: just read out properties files in maps below
val en = new Locale("en", Map(helloworld -> "Hello World!"))
val fr = new Locale("fr", Map(helloworld -> "Bonjour le Monde !"))
val es = new Locale("es", Map(helloworld -> "¡Hola Mundo!"))
def main(args: Array[String]) {
def printIn(locale: Option[String]) {
locale match {
case None =>
case Some(l) => Locale.set(l)
}
println(helloworld.translate)
}
printIn(None)
printIn(Some("en"))
printIn(Some("fr"))
printIn(Some("es"))
printIn(Some("alien"))
}
// END
}
