Introduction to Map-based or Dictionary Data Structures with SARL
Note 1 In SARL, a map is a data structure that is also known as dictionary in other programming languages. This type of data structure maps keys to values.
Note 2 If you don’t know how to solve an problem, or what is the function to be used, you could search on Internet for the answer using the API of the Java programming language. Indeed, since SARL is fully compatible with the Java API, you could use all the types or functions that are defined in this Java API.
1. Exercise 1
Write a SARL script to sort (ascending and descending) a map by value.
import java.util.Map
class Solution2 {
static var original1 = #{1 -> 154, 2 -> 44, 3 -> 9}
static var original2 = #{4 -> 16, 5 -> 25}
static def main : void {
println(original1.union(original2))
}
}
## 9. Exercise 9
* Write a SARL program to sum all the values in a maps.
Answer
Two answers are possible. Answer #1 is:
import java.util.Map
class Solution1 {
static var original = #{1 -> 154, 2 -> 44, 3 -> 9}
static def sum(m : Map) : int {
var s = 0
for (v : m.values) {
s += v
}
return s
}
static def main : void {
println(sum(original))
}
}
Answer #2 is:
import java.util.Map
class Solution2 {
static var original = #{1 -> 154, 2 -> 44, 3 -> 9}
static def sum(m : Map) : int {
m.values.reduce[accumulator, current | accumulator + current]
}
static def main : void {
println(sum(original))
}
}
## 10. Exercise 10
* Write a SARL program to multiply all the values in a map.
Answer
Two answers are possible. Answer #1 is:
import java.util.Map
class Solution1 {
static var original = #{1 -> 154, 2 -> 44, 3 -> 9}
static def mul(m : Map) : int {
var s = 1
for (v : m.values) {
s *= v
}
return s
}
static def main : void {
println(mul(original))
}
}
Answer #2 is:
import java.util.Map
class Solution2 {
static var original = #{1 -> 154, 2 -> 44, 3 -> 9}
static def mul(m : Map) : int {
m.values.reduce[accumulator, current | accumulator * current]
}
static def main : void {
println(mul(original))
}
}
## 11. Exercise 11
* Write a SARL program to remove a key from a map.
Answer
import java.util.Map
class Solution {
static var original = #{1 -> 154, 2 -> 44, 3 -> 9}
static def main : void {
original.remove(2)
println(original)
}
}
## 12. Exercise 12
* Write a SARL program to map two lists into a map.
Answer
Two answers are possible. Answer #1 is:
import java.util.Map
class Solution1 {
static var original1 = #[1, 2, 9]
static var original2 = #[154, 44, 9]
static def main : void {
var map = newHashMap
var iter1 = original1.iterator
var iter2 = original2.iterator
while (iter1.hasNext && iter2.hasNext) {
map.put(iter1.next, iter2.next)
}
println(map)
}
}
Answer #2 is:
import java.util.Map
class Solution2 {
static var original1 = #[1, 2, 9]
static var original2 = #[154, 44, 9]
static def main : void {
var iter1 = original1.iterator
var map = original2.toMap[iter1.next]
println(map)
}
}
## 13. Exercise 13
* Write a SARL program to sort a given map by key.
Answer
import java.util.Map
class Solution {
static var original = #{1 -> 154, 3 -> 9, 2 -> 44}
static def main : void {
var sortedMap = newTreeSet(null)
sortedMap.addAll(original)
println(sortedMap)
}
}
## 14. Exercise 14
* Write a SARL program to get the maximum and minimum values of a map.
Answer
Two answers are possible. Answer #1 is:
class Solution1 {
static var original = #{1 -> 154, 3 -> 9, 2 -> 44}
static def main : void {
var min = Integer::MAX_VALUE
var max = Integer::MIN_VALUE
for (e : original.entrySet) {
if (e.value < min) {
min = e.value
}
if (e.value > max) {
max = e.value
}
}
println("Min = " + min)
println("Max = " + max)
}
}
Answer #2 is:
class Solution2 {
static var original = #{1 -> 154, 3 -> 9, 2 -> 44}
static def main : void {
var min = original.values.min
var max = original.values.max
println("Min = " + min)
println("Max = " + max)
}
}
## 15. Exercise 15
* Write a SARL program to remove duplicated values from the map.
Answer
class Solution {
static var original = #{1 -> 154, 3 -> 9, 2 -> 44, 6 -> 9}
static def main : void {
var newmap = newHashMap
for (e : original.entrySet) {
if (!newmap.containsValue(e.value)) {
newmap.put(e.key, e.value)
}
}
println(newmap)
}
}
## 16. Exercise 16
* Write a SARL program to check if a map is empty or not.
Answer
Two answers are possible. Answer #1 is:
class Solution1 {
static var original = #{1 -> 154, 3 -> 9, 2 -> 44, 6 -> 9}
static def main : void {
println(original.isEmpty)
}
}
Answer #2 is:
class Solution2 {
static var original = #{1 -> 154, 3 -> 9, 2 -> 44, 6 -> 9}
static def main : void {
println(original.size == 0)
}
}
## 17. Exercise 17
* Write a SARL program to combine two maps by adding values for common keys.
* Inputs:
```text
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
```
* Sample output: `{'a': 400, 'b': 400, 'd': 400, 'c': 300}`
Answer
class Solution {
static var d1 = #{'a' -> 100, 'b' -> 200, 'c' -> 300}
static var d2 = #{'a' -> 300, 'b' -> 200, 'd' -> 400}
static def main : void {
var m = newHashMap
for (e : d1.entrySet) {
var v = d2.get(e.key)
if (v === null) {
m.put(e.key, e.value)
} else {
m.put(e.key, e.value + v)
}
}
for (e : d2.entrySet) {
m.putIfAbsent(e.key, e.value)
}
println(m)
}
}
## 18. Exercise 18
* Write a SARL program to print all distinct values in a map.
* Sample Data : `[{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]`
* Expected Output : `{'S005', 'S002', 'S007', 'S001', 'S009'}`
Answer
Two answers are possible. Answer #1 is:
class Solution1 {
static var original = #[
#{"V" -> "S001"}, #{"V" -> "S002"},
#{"VI" -> "S001"}, #{"VI" -> "S005"},
#{"VII" -> "S005"}, #{"V" -> "S009"},
#{"VIII" -> "S007"}
]
static def main : void {
var m = newTreeSet(null)
for (e : original) {
m.addAll(e.values)
}
println(m)
}
}
Answer #2 is:
class Solution2 {
static var original = #[
#{"V" -> "S001"}, #{"V" -> "S002"},
#{"VI" -> "S001"}, #{"VI" -> "S005"},
#{"VII" -> "S005"}, #{"V" -> "S009"},
#{"VIII" -> "S007"}
]
static def main : void {
var m = newTreeSet(null)
original.forEach[m.addAll(it.values)]
println(m)
}
}
## 19. Exercise 19
* Write a SARL program to create and display all combinations of letters, selecting each letter from a different key in a map.
* Sample data: `{'1':['a','b'], '2':['c','d']}`
* Expected Output:
```text
ac
ad
bc
bd
```
Answer
class Solution {
static var original = #{'1' -> #['a','b'], '2' -> #['c','d']}
static def main : void {
var m = newArrayList
var candidates = original.get(1)
if (candidates.isNullOrEmpty) {
m.addAll(candidates)
var i = 2
candidates = original.get(i)
while (candidates !== null) {
var m2 = newArrayList
for (cand0 : m) {
for (cand1 : candidates) {
m2 += cand0 + cand1
}
}
m = m2
i++
candidates = original.get(i)
}
}
println(m)
}
}
## 20. Exercise 20
* Write a SARL program to find the highest 3 values of corresponding keys in a map.
Answer
Two answers are possible. Answer #1 is:
class Solution1 {
static var original = #{'A' -> 67, 'B' -> 23, 'C' -> 45,
'D' -> 56, 'E' -> 12, 'F' -> 69}
static def main : void {
var iter = original.entrySet.iterator
var en = iter.next
var max0 = en.value
var key0 = en.key
var max1 : int
var key1 : String
var max2 : int
var key2 : String
while (iter.hasNext) {
en = iter.next
val m = en.value
val k = en.key
if (m > max0) {
max2 = max1
key2 = key1
max1 = max0
key1 = key0
max0 = m
key0 = k
} else if (m > max1) {
max2 = max1
key2 = key1
max1 = m
key1 = k
} else if (m > max0) {
max2 = m
key2 = k
}
}
var newmap = #{key0 -> max0, key1 -> max1, key2 -> max2}
println(newmap)
}
}
Answer #2 is:
class Solution2 {
static var original = #[
#{"V" -> "S001"}, #{"V" -> "S002"},
#{"VI" -> "S001"}, #{"VI" -> "S005"},
#{"VII" -> "S005"}, #{"V" -> "S009"},
#{"VIII" -> "S007"}
]
static def main : void {
var m = newTreeSet(null)
original.forEach[m.addAll(it.values)]
println(m)
}
}
## 21. Exercise 21
* Write a SARL program to combine values in a list of maps.
* Sample data: `[{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1', 'amount': 750}]`
* Expected Output: `{'item1': 1150, 'item2': 300}`
Answer
class Solution {
static var original = #[
#{'item' -> 'item1', 'amount' -> 400},
#{'item' -> 'item2', 'amount' -> 300},
#{'item' -> 'item1', 'amount' -> 750}
]
static def main : void {
var newmap = newHashMap
for (m : original) {
newmap.put(m.get("item"), m.get("amount"))
}
println(newmap)
}
}
## 22. Exercise 22
* Write a SARL program to create a map from a string. Track the count of the letters from the string.
* Sample string: `w3resource`
* Expected output: `{'w': 1, '3': 1, 'r': 2, 'e': 2, 's': 1, 'o': 1, 'u': 1, 'c': 1}`
Answer
import java.util.Map
class Solution {
static def letters(value : String) : Map {
var map = newHashMap
for (b : value.bytes) {
var c = b as char
var n = map.getOrDefault(c, 0)
map.put(c, n + 1)
}
return map
}
static def main : void {
println(letters("w3resource"))
}
}
## 23. Exercise 23
* Write a SARL program to print a map in table format.
* Sample Input:
```text
{1: ["Samuel", 21, 'Data Structures'],
2: ["Richie", 20, 'Machine Learning'],
3: ["Lauren", 21, 'OOPS with java'],
}
```
* Expected Output:
```text
Samuel 21 Data Structures
Richie 20 Machine Learning
Lauren 21 OOPS with java
```
Answer
class Solution {
static var original = #{
1 -> #["Samuel", 21, 'Data Structures'],
2 -> #["Richie", 20, 'Machine Learning'],
3 -> #["Lauren", 21, 'OOPS with java']
}
static def main : void {
var i = 1
var row = original.get(i)
while (row !== null) {
if (!row.isEmpty) {
var iter = row.iterator
print(iter.next)
while (iter.hasNext) {
print(" " + iter.next)
}
}
println
i++
row = original.get(i)
}
}
}
## 24. Exercise 24
* Write a SARL program to sort a list alphabetically in a map.
* Sample Input: `{'n1': [2, 3, 1], 'n2': [5, 1, 2], 'n3': [3, 2, 4]}`
* Expected Output: `{'n1': [1, 2, 3], 'n2': [1, 2, 5], 'n3': [2, 3, 4]}`
Answer
class Solution1 {
static var original = #{'n1' -> #[2, 3, 1], 'n2' -> #[5, 1, 2], 'n3' -> #[3, 2, 4]}
static def main : void {
var newmap = newHashMap
for (e : original.entrySet) {
var nv = e.value.sort
newmap.put(e.key, nv)
}
println(newmap)
}
}
## 25. Exercise 25
* Write a SARL program to remove spaces from map keys.
Answer
class Solution {
static var original = #{'P 01' -> 'DBMS', 'P 02' -> 'OS', 'P 0 3 ' -> 'Soft Computing'}
static def main : void {
var newmap = newHashMap
for (e : original.entrySet) {
var nk = e.key.replaceAll("\s+", "")
newmap.put(nk, e.value)
}
println(newmap)
}
}
## 26. Exercise 26
* Write a SARL program to get the top three items in a shop.
* Sample data: `{'item1': 45.50, 'item2':35, 'item3': 41.30, 'item4':55, 'item5': 24}`
* Expected Output:
```text
item4 55
item1 45.5
item3 41.3
```
Answer
Two answers are possible. Answer #1 is:
class Solution1 {
static var original = #{'item1' -> 45.50, 'item2' -> 35.0, 'item3' -> 41.30, 'item4' -> 55.0, 'item5' -> 24.0}
static def main : void {
var iter = original.entrySet.iterator
var en = iter.next
var max0 = en.value
var key0 = en.key
var max1 : double
var key1 : String
var max2 : double
var key2 : String
while (iter.hasNext) {
en = iter.next
val m = en.value
val k = en.key
if (m > max0) {
max2 = max1
key2 = key1
max1 = max0
key1 = key0
max0 = m
key0 = k
} else if (m > max1) {
max2 = max1
key2 = key1
max1 = m
key1 = k
} else if (m > max0) {
max2 = m
key2 = k
}
}
println(key0 + " " + max0)
println(key1 + " " + max1)
println(key2 + " " + max2)
}
}
Answer #2 is:
class Solution2 {
static var original = #{'item1' -> 45.50, 'item2' -> 35.0, 'item3' -> 41.30, 'item4' -> 55.0, 'item5' -> 24.0}
static def main : void {
var max0 = original.values.max
var max1 = original.values.filter[it < max0].max
var max2 = original.values.filter[it < max1].max
var newmap = original.filter[k, v | v >= max2]
for (e : newmap.entrySet) {
println(e.key + " " + e.value)
}
}
}
## 27. Exercise 27
*Write a SARL program to get the key, value and item in a map.
Answer
class Solution {
static var original = #{1 -> 10, 2 -> 20, 3 -> 30, 4 -> 40, 5 -> 50, 6 -> 60}
static def main : void {
for (e : original.entrySet) {
println(e.key + "t" + e.value + "t" + e)
}
}
}
## 28. Exercise 28
* Write a SARL program to print a map line by line.
Answer
class Solution {
static var original = #{1 -> 10, 2 -> 20, 3 -> 30, 4 -> 40, 5 -> 50, 6 -> 60}
static def main : void {
for (e : original.entrySet) {
println(e.key + "t" + e.value)
}
}
}
## 29. Exercise 29
* Write a SARL program to count the number of items in a map value that is a list.
Answer
Two answers are possible. Answer #1 is:
class Solution1 {
static var original = #{
'Alex' -> #['subj1', 'subj2', 'subj3'],
'David' -> #['subj1', 'subj2']
}
static def main : void {
var sum = 0
for (v : original.values) {
sum += v.size
}
println(sum)
}
}
Answer #2 is:
class Solution2 {
static var original = #{
'Alex' -> #['subj1', 'subj2', 'subj3'],
'David' -> #['subj1', 'subj2']
}
static def main : void {
var sum = original.values.map[it.size].reduce(accumulator, current | accumulator + current)
println(sum)
}
}
## 30. Exercise 30
* Write a SARL program to sort items by value in reverse order.
* Sample data: `{'Math':81, 'Physics':83, 'Chemistry':87}`
* Expected data: `[('Chemistry', 87), ('Physics', 83), ('Math', 81)]`
Answer
class Solution {
static var original = #{
'Math' -> 81, 'Physics' -> 83, 'Chemistry' -> 87
}
static def main : void {
var result = original.entrySet.sortWith[a, b | b.value <=> a.value].map[#[it.key, it.value]].toList
println(result)
}
}
## 31. Exercise 31
* Write a SARL program to create a map from two lists without losing duplicate values.
* Sample lists: `['Class-V', 'Class-VI', 'Class-VII', 'Class-VIII']` and `[1, 2, 2, 3]`
* Expected Output: `{'Class-V': {1}, 'Class-VI': {2}, 'Class-VII': {2}, 'Class-VIII': {3}}`
Answer
class Solution {
static var original1 = #['Class-V', 'Class-VI', 'Class-VII', 'Class-VIII']
static var original2 = #[1, 2, 2, 3]
static def main : void {
var iter1 = original1.iterator
var iter2 = original2.iterator
var newmap = newHashMap
while (iter1.hasNext && iter2.hasNext) {
newmap.put(iter1.next, iter2.next)
}
println(newmap)
}
}
## 32. Exercise 32
* Write a SARL program to match key values in two dictionaries.
* Sample maps: `{'key1': 1, 'key2': 3, 'key3': 2}` and `{'key1': 1, 'key2': 2}`
* Expected output: `{'key1': 1}` is present in both input maps
Answer
class Solution {
static var original1 = #{'key1' -> 1, 'key2' -> 3, 'key3' -> 2}
static var original2 = #{'key1' -> 1, 'key2' -> 2}
static def main : void {
var newmap = newHashMap
for (e1 : original1.entrySet) {
var v2 = original2.get(e1.key)
if (v2 == e1.value) {
newmap.put(e1.key, e1.value)
}
}
println(newmap)
}
}
## 33. Exercise 33
* Write a SARL program to store map data in a JSON file.
* Original map:
```json
{'students': [{'firstName': 'Nikki', 'lastName': 'Roysden'}, {'firstName': 'Mervin', 'lastName': 'Friedland'}, {'firstName': 'Aron ', 'lastName': 'Wilkins'}], 'teachers': [{'firstName': 'Amberly', 'lastName': 'Calico'}, {'firstName': 'Regine', 'lastName': 'Agtarap'}]}
```
* Json file:
```json
{'students': [{'firstName': 'Nikki', 'lastName': 'Roysden'}, {'firstName': 'Mervin', 'lastName': 'Friedland'}, {'firstName': 'Aron ', 'lastName': 'Wilkins'}], 'teachers': [{'firstName': 'Amberly', 'lastName': 'Calico'}, {'firstName': 'Regine', 'lastName': 'Agtarap'}]}
```
Answer
import java.util.Map
class Solution {
static var original = #{'students' -> #[
#{'firstName' -> 'Nikki', 'lastName' -> 'Roysden'},
#{'firstName' -> 'Mervin', 'lastName' -> 'Friedland'},
#{'firstName' -> 'Aron ', 'lastName' -> 'Wilkins'}
],
'teachers' -> #[
#{'firstName' -> 'Amberly', 'lastName' -> 'Calico'},
#{'firstName' -> 'Regine', 'lastName' -> 'Agtarap'}
]
}
static def toJson(data : Object, buffer : StringBuilder) {
if (data instanceof Map) {
buffer.append("{")
var iter = (data as Map).entrySet.iterator
if (iter.hasNext) {
var me = iter.next
buffer.append(me.key).append(":")
toJson(me.value, buffer)
while (iter.hasNext) {
buffer.append(", ")
me = iter.next
buffer.append(me.key).append(":")
toJson(me.value, buffer)
}
}
buffer.append("}")
} else if (data instanceof Iterable) {
buffer.append("[")
var iter = data.iterator
if (iter.hasNext) {
toJson(iter.next, buffer)
while (iter.hasNext) {
buffer.append(", ")
toJson(iter.next, buffer)
}
}
buffer.append("]")
} else {
buffer.append(data)
}
}
static def main : void {
var json = new StringBuilder
original.toJson(json)
println(json.toString)
}
}
34. Exercise 34
Write a SARL program to create a map of keys x, y, and z where each key has as value a list from 11-20, 21-30, and 31-40 respectively. Access the fifth value of each key from the map.
{'x': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
'y': [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
'z': [31, 32, 33, 34, 35, 36, 37, 38, 39, 40]}
15
25
35
x has value [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
y has value [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
z has value [31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
class Solution {
static var original = #[
#['yellow', 1], #['blue', 2], #['yellow', 3], #['blue', 4], #['red', 1]
]
static def main : void {
var map = newHashMap
for (e : original) {
var list = map.computeIfAbsent(e.get(0)) [newArrayList]
list += e.get(1)
}
println(map)
}
}
41. Exercise 41
Write a SARL program to split a given map of lists into lists of maps.
Original map of lists: {'Science': [88, 89, 62, 95], 'Language': [77, 78, 84, 80]}
Split said map of lists into list of dictionaries: [{'Science': 88, 'Language': 77}, {'Science': 89, 'Language': 78}, {'Science': 62, 'Language': 84}, {'Science': 95, 'Language': 80}]
import java.util.Map
import java.util.List
class Solution {
static var original = #{'Science' -> #[88, 89, 62, 95], 'Language' -> #[77, 78, 84, 80]}
static def list_of_dicts(marks : Map<String, List>) : List<Map<String, Integer>> {
var list = newArrayList
for (value : marks.entrySet) {
var i = 0
for (value0 : value.value) {
var m : Map<String, Integer>
if (i >= list.size) {
m = newHashMap
list.add(m)
} else {
m = list.get(i)
}
m.put(value.key, value0)
i++
}
}
return list
}
static def main : void {
println(list_of_dicts(original))
}
}
</code></pre>
</div>
## 42. Exercise 42
* Write a SARL program to remove a specified map from a given list.
* Original list of map: `[{'id': '#FF0000', 'color': 'Red'}, {'id': '#800000', 'color': 'Maroon'}, {'id': '#FFFF00', 'color': 'Yellow'}, {'id': '#808000', 'color': 'Olive'}]`
* Remove id `#FF0000` from the said list of map: `[{'id': '#800000', 'color': 'Maroon'}, {'id': '#FFFF00', 'color': 'Yellow'}, {'id': '#808000', 'color': 'Olive'}]`
Answer
Two answers are possible. Answer #1 is:
import java.util.Map
import java.util.List
class Solution1 {
static var original = #[
#{'id' -> '#FF0000', 'color' -> 'Red'},
#{'id' -> '#800000', 'color' -> 'Maroon'},
#{'id' -> '#FFFF00', 'color' -> 'Yellow'},
#{'id' -> '#808000', 'color' -> 'Olive'}
]
static def remove_color(colors : List<Map<String, String>>, id : String) : List<Map<String, String>> {
var newlist = newArrayList
for (c : colors) {
if (c.get("id") != id) {
newlist.add(c)
}
}
return newlist
}
static def main : void {
println(remove_color(original, '#FF0000'))
}
}
## 44. Exercise 44
* A SARL map contains List as a value. Write a SARL program to clear the list values in the said map.
* Original Map: `{'C1': [10, 20, 30], 'C2': [20, 30, 40], 'C3': [12, 34]}`
* Clear the list values in the said map: `{'C1': [], 'C2': [], 'C3': []}`
Answer
Two answers are possible. Answer #1 is:
import java.util.Map
import java.util.List
class Solution1 {
static var original = #{'C1' -> #[10, 20, 30], 'C2' -> #[20, 30, 40], 'C3' -> #[12, 34]}
static def clear(map : Map<String, List>) : Map<String, List> {
var newmap = newHashMap
for (e : map.entrySet) {
newmap.put(e.key, newArrayList)
}
return newmap
}
static def main : void {
println(clear(original))
}
}
</code></pre>
Answer #2 is:
import java.util.Map
import java.util.List
class Solution2 {
static var original = #{'C1' -> #[10, 20, 30], 'C2' -> #[20, 30, 40], 'C3' -> #[12, 34]}
static def clear(map : Map<String, List>) : Map<String, List> {
map.mapValues[newArrayList]
}
static def main : void {
println(clear(original))
}
}
</code></pre>
</div>
## 45. Exercise 45
* A SARL map contains List as a value. Write a SARL program to update the list values in the said map by adding 1 to the scores in Math and substracting 2 to the scores in Physics
* Original Map: `{'Math': [88, 89, 90], 'Physics': [92, 94, 89], 'Chemistry': [90, 87, 93]}`
* Update the list values of the said map: `{'Math': [89, 90, 91], 'Physics': [90, 92, 87], 'Chemistry': [90, 87, 93]}`
Answer
Two answers are possible. Answer #1 is:
import java.util.Map
import java.util.List
class Solution1 {
static var original = #{'Math' -> #[88, 89, 90], 'Physics' -> #[92, 94, 89], 'Chemistry' -> #[90, 87, 93]}
static def update(map : Map<String, List>, name : String, delta : int) : Map<String, List> {
var newmap = newHashMap
for (e : map.entrySet) {
if (e.key == name) {
var ns = newArrayList
for (s : e.value) {
ns += s + delta
}
newmap.put(e.key, ns)
} else {
newmap.put(e.key, e.value)
}
}
return newmap
}
static def main : void {
var m = original.update("Math", 1)
m = m.update("Physics", -2)
println(m)
}
}
</code></pre>
Answer #2 is:
import java.util.Map
import java.util.List
class Solution2 {
static var original = #{'Math' -> #[88, 89, 90], 'Physics' -> #[92, 94, 89], 'Chemistry' -> #[90, 87, 93]}
static def update(map : Map<String, List>, name : String, delta : int) : Map<String, List> {
map.entrySet.toMap(
[it.key],
[
if (it.key == name) {
it.value.map[it + delta]
} else {
it.value
}
]
)
}
static def main : void {
var m = original.update("Math", 1)
m = m.update("Physics", -2)
println(m)
}
}
</code></pre>
</div>
## 46. Exercise 46
* Write a SARL program to extract a list of values from a given list of maps.
* Original Map: `[{'Math': 90, 'Science': 92}, {'Math': 89, 'Science': 94}, {'Math': 92, 'Science': 88}]`
* Extract a list of values from said list of maps where subject = Science: `[92, 94, 88]`
* Original Map: `[{'Math': 90, 'Science': 92}, {'Math': 89, 'Science': 94}, {'Math': 92, 'Science': 88}]`
* Extract a list of values from said list of maps where subject = Math: `[90, 89, 92]`
Answer
Two answers are possible. Answer #1 is:
import java.util.Map
import java.util.List
class Solution1 {
static var original = #[
#{'Math' -> 90, 'Science' -> 92},
#{'Math' -> 89, 'Science' -> 94},
#{'Math' -> 92, 'Science' -> 88}
]
static def extract(list : List<Map<String, Integer>>, name : String) : List {
var scores = newArrayList
for (map : list) {
var score = map.get(name)
if (score !== null) {
scores += score
}
}
return scores
}
static def main : void {
println(original.extract("Science"))
}
}
</code></pre>
Answer #2 is:
import java.util.Map
import java.util.List
class Solution2 {
static var original = #[
#{'Math' -> 90, 'Science' -> 92},
#{'Math' -> 89, 'Science' -> 94},
#{'Math' -> 92, 'Science' -> 88}
]
static def extract(list : List<Map<String, Integer>>, name : String) : List {
list.map[it.get(name)]
}
static def main : void {
println(original.extract("Science"))
}
}
</code></pre>
</div>
## 47. Exercise 47
* Write a SARL program to find the length of a map of values.
* Original Map: `{1: 'red', 2: 'green', 3: 'black', 4: 'white', 5: 'black'}`
* Length of map values: `{'red': 3, 'green': 5, 'black': 5, 'white': 5}`
* Original Map: `{'1': 'Austin Little', '2': 'Natasha Howard', '3': 'Alfred Mullins', '4': 'Jamie Rowe'}`
* Length of map values: `{'Austin Little': 13, 'Natasha Howard': 14, 'Alfred Mullins': 14, 'Jamie Rowe': 10}`
Answer
Two answers are possible. Answer #1 is:
import java.util.List
import java.util.Map
class Solution1 {
static var original = #[
#{'Math' -> 90, 'Science' -> 92},
#{'Math' -> 89, 'Science' -> 94},
#{'Math' -> 92, 'Science' -> 88}
]
static def extract(list : List<Map<String, Integer>>, name : String) : List {
var scores = newArrayList
for (map : list) {
var score = map.get(name)
if (score !== null) {
scores += score
}
}
return scores
}
static def main : void {
println(original.extract("Science"))
}
}
</code></pre>
Answer #2 is:
</div>
## 48. Exercise 48
* Write a SARL program to get the depth of a map.
Answer
Two answers are possible. Answer #1 is:
import java.util.Map
class Solution1 {
static var original = #{'a' -> 1, 'b' -> #{'c' -> #{'d' -> #{}}}}
static def depth(map : Object) : int {
if (map instanceof Map) {
var iter = map.values.iterator
if (iter.hasNext) {
var max = depth(iter.next)
while (iter.hasNext) {
var m = depth(iter.next)
if (m > max) {
max = m
}
}
return max + 1
}
}
return 0
}
static def main : void {
println(original.depth)
}
}
Answer #2 is:
import java.util.Map
class Solution2 {
static var original = #{'a' -> 1, 'b' -> #{'c' -> #{'d' -> #{}}}}
static def depth(map : Object) : int {
if (map instanceof Map) {
return map.values.map[depth(it)].max + 1
}
return 0
}
static def main : void {
println(original.depth)
}
}
## 49. Exercise 49
* Write a SARL program to access map key's element by index.
* Sample Input: `{'physics': 80, 'math': 90, 'chemistry': 86}`
* Expected Output:
```text
0 = physics
1 = math
2 = chemistry
```
Answer
class Solution {
static var original = #{'physics' -> 80, 'math' -> 90, 'chemistry' -> 86}
static def main : void {
for (i : 0..<3) {
println(i + " = " + original.keySet.get(i))
}
}
}
## 50. Exercise 50
* Write a SARL program to convert a map into a list of lists.
* Original Map: `{1: 'red', 2: 'green', 3: 'black', 4: 'white', 5: 'black'}`
* Convert the said map into a list of lists: `[[1, 'red'], [2, 'green'], [3, 'black'], [4, 'white'], [5, 'black']]`
* Original Map: `{'1': 'Austin Little', '2': 'Natasha Howard', '3': 'Alfred Mullins', '4': 'Jamie Rowe'}`
* Convert the said map into a list of lists: `[['1', 'Austin Little'], ['2', 'Natasha Howard'], ['3', 'Alfred Mullins'], ['4', 'Jamie Rowe']]`
Answer