Regenerated samples & exercise descriptions
This commit is contained in:
parent
52a11e8004
commit
dad77e0342
|
@ -1,4 +1,4 @@
|
|||
// BuildingMaps/ImmutableBlendMap.kt
|
||||
// BuildingMaps/ReadOnlyBlendMap.kt
|
||||
@file:OptIn(ExperimentalStdlibApi::class)
|
||||
package buildingmaps
|
||||
|
|
@ -24,5 +24,5 @@ files:
|
|||
visible: true
|
||||
- name: src/ColorBlend.kt
|
||||
visible: true
|
||||
- name: src/ImmutableBlendMap.kt
|
||||
- name: src/ReadOnlyBlendMap.kt
|
||||
visible: true
|
||||
|
|
|
@ -3,5 +3,5 @@
|
|||
The starter code provides a `Condition` class and a function
|
||||
`Condition.combine()` that combines two conditions. There's also a skeleton
|
||||
for the `List<Condition>` extension function `combineAll()` that combines all
|
||||
conditions in the `List`. Complete the implementation using `reduce()`,
|
||||
the conditions in the `List`. Complete the implementation using `reduce()`,
|
||||
assuming the `List` is non-empty.
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## Manipulating Lists (#3)
|
||||
|
||||
Reimplement the `authorBooksMap()` function from the Data Classes atom,
|
||||
Reimplement the `authorBooksMap()` function from [Data Classes],
|
||||
using operations for manipulating collections. `authorBooksMap()` takes a
|
||||
`List<Book>` as a parameter and builds a `Map` from each `Author` to the
|
||||
`Book`s they have written.
|
||||
|
|
|
@ -12,7 +12,7 @@ Bob - Charlie
|
|||
`friendSuggestions()` should return Charlie for Alice, because Charlie is a
|
||||
friend of Alice's friend Bob and isn't yet a friend of Alice.
|
||||
|
||||
The following example produces no friend suggestions for Alice because Bob and
|
||||
The following example produces no friend suggestions for Alice, because Bob and
|
||||
Charlie are already her friends:
|
||||
|
||||
```text
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
## Operations on Collections (#4)
|
||||
|
||||
`all()`, `none()` and `any()` can be used to produce identical results.
|
||||
Implement `List<Int>` extension functions `allNonZero()` and `hasZero()` using
|
||||
each of `all()`, `none()` and `any()`.
|
||||
Implement the `List<Int>` extension functions `allNonZero()` and `hasZero()`
|
||||
using each of `all()`, `none()` and `any()`.
|
||||
|
||||
- `allNonZero()` checks that all elements in the list are non-zero.
|
||||
|
||||
|
|
|
@ -2,5 +2,5 @@
|
|||
|
||||
Write a tail recursive function called `simulation()` that takes a `String`
|
||||
called `group` and an `Int` called `level`. It displays `"Simulation: $group
|
||||
Reality: level"`, then recursively calls itself with `level - 1` as long as
|
||||
`level` is greater than zero.
|
||||
Reality: level"`, then calls itself with `level - 1` as long as `level` is
|
||||
greater than zero.
|
||||
|
|
|
@ -1,13 +1,13 @@
|
|||
## Recursion (#4)
|
||||
|
||||
The starter code defines a `City` class. Implement an extension function
|
||||
The starter code provides a class `City`. Implement an extension function
|
||||
`City.allReachable()` that builds a set of all cities reachable from the
|
||||
current `City`. Implement it in two ways: recursive and iterative.
|
||||
|
||||
The direct connections for each `City` are stored in its `connections`
|
||||
property. `allReachable()` should return all cities reachable from the given
|
||||
city via other cities. The city is reachable from itself, so it should be also
|
||||
present in the resulting set.
|
||||
property. `allReachable()` should return all the cities reachable from the
|
||||
given city via other cities. The city is reachable from itself, so it should be
|
||||
also present in the resulting set.
|
||||
|
||||
For example, consider the following connections graph:
|
||||
|
||||
|
|
|
@ -2,6 +2,6 @@
|
|||
|
||||
Implement the `School` extension function `averageInstructorRating()` that
|
||||
takes `Instructor` as a parameter and calculates the average rating that the
|
||||
instructor was given by all students that attended his or her classes. If a
|
||||
instructor was given by all the students that attended his or her classes. If a
|
||||
student attended several lessons by that instructor, the ratings for individual
|
||||
lessons should be treated separately.
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## The Importance of Lambdas (#3)
|
||||
|
||||
Implement the function `other(s: String)` so it returns a `String` containing
|
||||
Implement the function `other(s: String)` that returns a `String` containing
|
||||
every other letter of `s`. For example, for an input of "cement" it returns
|
||||
"cmn".
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
## Constraining Visibility (#2)
|
||||
|
||||
Continue developing the `Robot` class from the exercises in the previous atoms.
|
||||
Use `private` on all the properties and the `crossBoundary()` function, and
|
||||
verify that you can't access the `private` members outside the class.
|
||||
Use `private` on all the properties and `crossBoundary()`, and verify that you
|
||||
can't access the private members outside of the class.
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
## Constructors (#2)
|
||||
|
||||
Continue developing the `Robot` class from the exercises in the previous atom.
|
||||
Convert the properties that store the size of the field and the current
|
||||
Convert the properties storing the size of the field and the current
|
||||
coordinates into `Robot` constructor parameters.
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
## Creating Classes (#1)
|
||||
|
||||
Create a class named `SomeClass` with three member functions: `a()` which
|
||||
displays `42` on the console, `b()` which calls `a()`, and `c()` which calls
|
||||
`b()` by qualifying it.
|
||||
displays `42` on the console when you call it, `b()` which calls `a()`,
|
||||
and `c()` which calls `b()` by qualifying it.
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
## Creating Classes (#3)
|
||||
|
||||
Create a `Robot` class with the following four member functions: `right(steps:
|
||||
Int)`, `left(steps: Int)`, `down(steps: Int)` and `up(steps: Int)`. Each
|
||||
function should display one of the following phrases on the console:
|
||||
Create a `Robot` class with the following four member functions:
|
||||
`right(steps: Int)`, `left(steps: Int)`, `down(steps: Int)` and
|
||||
`up(steps: Int)`. Each function should display one of the following
|
||||
phrases on the console:
|
||||
|
||||
```
|
||||
Right N steps
|
||||
|
@ -11,4 +12,4 @@ Down N steps
|
|||
Up N steps
|
||||
```
|
||||
|
||||
N is the provided number of steps.
|
||||
where N is the provided number of steps.
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## Exceptions (#1)
|
||||
|
||||
Display on the console all the following `String`s that can't be converted to
|
||||
Display to the console all of the following `String`s that can't be converted to
|
||||
`Double` (that is, those where an attempt to convert it throws an exception):
|
||||
|
||||
```
|
||||
|
|
|
@ -5,6 +5,6 @@ fun main() {
|
|||
val ints = listOf(1, 2, 3)
|
||||
capture {
|
||||
ints[3]
|
||||
} eq "ArrayIndexOutOfBoundsException: " +
|
||||
"Index 3 out of bounds for length 3"
|
||||
} contains
|
||||
listOf("ArrayIndexOutOfBoundsException")
|
||||
}
|
|
@ -1,14 +1,14 @@
|
|||
## Lists (#3)
|
||||
|
||||
Write a function that determines whether two `String`s are anagrams. An anagram
|
||||
Write a function to determine whether two `String`s are anagrams. An anagram
|
||||
is a word formed by rearranging the letters of a different word, using all the
|
||||
original letters exactly once.
|
||||
|
||||
<div class="hint">
|
||||
|
||||
Compare two sorted `Lists` of characters obtained from two `String`s. Convert a
|
||||
`String` to a `List` by calling `toList()`. If the `Lists` are equal, the words
|
||||
are anagrams. For example, for the two anagrams "terrain" and "trainer", the
|
||||
sorted character `List` will be `[a, e, i, n, r, r, t]`.
|
||||
Compare two sorted `Lists` of characters obtained from two `String`s.
|
||||
Convert a `String` to a `List` by calling `toList()`. If the `Lists` are equal,
|
||||
the words are anagrams. For example, for two anagrams "terrain" and "trainer"
|
||||
the sorted character `List` will be `[a, e, i, n, r, r, t]`.
|
||||
|
||||
</div>
|
||||
|
|
|
@ -6,5 +6,5 @@ constant time. With a `List`, in the worst case you must iterate over every
|
|||
element.
|
||||
|
||||
Change the internal implementation of the `Cage` class to store elements in a
|
||||
`Map` rather than a `List`. To get an element, use the `getValue()` member
|
||||
`Map` rather than a `List`. To get an element use the `getValue()` member
|
||||
function, which throws `NoSuchElementException` if the key is missing.
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## Properties (#1)
|
||||
|
||||
Create a class `X` containing three `Int` properties: `a` and `b` are `val`s
|
||||
Create a class `X` that contains three `Int` properties: `a` and `b` are `val`s
|
||||
and `c` is a `var`. Initialize `a` to 3, `b` to 42, and `c` to zero. Create an
|
||||
`add()` member function that sums `a` and `b` and assigns the result to `c`,
|
||||
then returns `c`. Write a `main()` to test `X`.
|
||||
|
|
|
@ -11,8 +11,7 @@ is the top-left corner:
|
|||
```
|
||||
|
||||
Moving right increases the `x` coordinate, moving down increases the `y`
|
||||
coordinate, while moving left and up decrease the `x` and `y` coordinates,
|
||||
respectively.
|
||||
coordinate, while moving left and up decrease the `x` and `y` coordinates.
|
||||
|
||||
Implement `Robot`'s member functions `right()`, `left()`, `up()` and `down()`,
|
||||
each of which takes a `steps` parameter. Also implement `getLocation()` which
|
||||
|
|
|
@ -4,6 +4,6 @@ Create a class `MessageStorage` with two properties: a `private` one named
|
|||
`_messages` of type `MutableList<String>` and a `public` one named `messages`
|
||||
of type `List<String>`. The custom getter for `messages` returns `_messages`.
|
||||
|
||||
Since `_messages` is `private`, its contents can be only changed within the
|
||||
Because `_messages` is `private` its contents can be only changed within the
|
||||
`MessageStorage` class. Define an `addMessage()` member function that takes a
|
||||
`String` parameter and adds it to the `_messages` list.
|
||||
|
|
|
@ -2,5 +2,5 @@
|
|||
|
||||
Create a class named `Boring2` that is just like `Boring` except it has
|
||||
constructor parameters, which are all `val`s. The parameter `a` holds the value
|
||||
that `a()` produces, `b` holds the value that `b()` produces, and `c` holds the
|
||||
value produced by `c()`. Test `Boring2` using `atomictest`.
|
||||
that `a()` produces, the parameter `b` holds the value that `b()` produces, and
|
||||
`c` holds the value produced by `c()`. Test `Boring2` using `atomictest`.
|
||||
|
|
|
@ -2,30 +2,18 @@
|
|||
|
||||
Convert a natural number into a number in the Roman numeral system.
|
||||
|
||||
| Roman | Decimal |
|
||||
|-------|---------|
|
||||
| I | 1 |
|
||||
| IV | 4 |
|
||||
| V | 5 |
|
||||
| IX | 9 |
|
||||
| X | 10 |
|
||||
| XL | 40 |
|
||||
| L | 50 |
|
||||
| XC | 90 |
|
||||
| C | 100 |
|
||||
| CD | 400 |
|
||||
| D | 500 |
|
||||
| CM | 900 |
|
||||
| M | 1000 |
|
||||
Roman numerals:
|
||||
1000 = M, 900 = CM, 500 = D, 400 = CD, 100 = C, 90 = XC,
|
||||
50 = L, 40 = XL, 10 = X, 9 = IX, 5 = V, 4 = IV, 1 = I.
|
||||
|
||||
For example: 23 = XXIII, 44 = XLIV, 100 = C.
|
||||
|
||||
<div class="hint">
|
||||
|
||||
Perform the conversion in steps. Use an auxiliary `remainder` variable to store
|
||||
the remaining part of the converted integer and a `result` variable to store
|
||||
the resulting Roman numeral representation. For each step, the initial `number`
|
||||
equals the sum of `remainder` and `result`.
|
||||
Perform the conversion in steps. Use an auxiliary `remainder`
|
||||
variable to store the remaining part of the converted integer and the `result`
|
||||
variable to store the resulting Roman numeral representation. For each step,
|
||||
the initial `number` equals the sum of the `remainder` and `result`.
|
||||
|
||||
Store the Roman numerals in a mapping from `Int` to the associated `String`
|
||||
representation. For each pair `int = roman` starting from `1000 = M`:
|
||||
|
|
|
@ -1,20 +1,21 @@
|
|||
## Summary 2 (#8)
|
||||
|
||||
Convert from a Roman number into a natural number. For
|
||||
example: XXIII is 23, XLIV is 44, and C is 100.
|
||||
example: XXIII = 23, XLIV = 44, C = 100.
|
||||
|
||||
<div class="hint">
|
||||
|
||||
Iterate over each digit in the Roman number and calculate the answer. Traverse
|
||||
a Roman number in reverse order, a single digit at a time (for example, `IV`
|
||||
contains two digits) and store the maximum value found so far. If the next
|
||||
Roman digit is greater than or equal to the current maximum value, add it to
|
||||
the result. If it's less than the maximum, subtract it instead. For example, to
|
||||
convert XLIV, iterate over `VILX` which is the reverse of `XLIV`. Add `V`(`5`)
|
||||
and `L`(`50`), but subtract `1`(`I`) because it's less than the current maximum
|
||||
`V`, and subtract `10`(`X`) because it's less than the updated maximum `X`:
|
||||
Simply iterate over each digit in the Roman number and calculate the
|
||||
answer. Traverse a Roman number in reverse order, a single digit at a time (for
|
||||
example, `IV` contains two digits) and store the maximum value found so far. If
|
||||
the next Roman digit is greater than or equal to the current maximum value, add
|
||||
it to the result. If it's less than the maximum, subtract it instead. For
|
||||
example, to convert `XLIV = 44`, iterate over `VILX` which is the reverse of
|
||||
`XLIV`. You add `V`(`5`) and `L`(`50`), but subtract `1`(`I`) because it's less
|
||||
than the current maximum `V`, and subtract `10`(`X`) because it's less than the
|
||||
updated maximum `X`:
|
||||
|
||||
| Numeral | Current Maximum | Action |
|
||||
| numeral | current maximum | action |
|
||||
| ------- |-----------------|--------|
|
||||
| V | 5 | + 5 |
|
||||
| I | 5 | - 1 |
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
Write a function `printArgs()` with a `String` as the first parameter, and a
|
||||
`vararg` parameter of `Int` as the second parameter. `printArgs()` displays its
|
||||
arguments on the console: first the `String`, then the `Int`s, separated by
|
||||
arguments to the console: first the `String`, then the `Int`s, separated by
|
||||
commas and surrounded by square brackets.
|
||||
|
||||
For example, the output for `printArgs("Numbers: ", 1, 2, 3)` should be:
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## Class Delegation (#2)
|
||||
|
||||
Exercise 1 from the Inheritance & Extensions atom uses
|
||||
Exercise 1 in [Inheritance & Extensions] uses
|
||||
composition to adapt `Crocodile` to work with `interactWithDuck()`. This
|
||||
produces an inconsistency when using `IAmHonestlyDuck` with the
|
||||
`interactWithCrocodile()` function---the composed `crocodile` must be
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
## Complex Constructors (#1)
|
||||
|
||||
Modify `Alien` to use "verbose" syntax: make `name` a constructor parameter
|
||||
Modify `Alien` to use the "verbose" syntax: make `name` a constructor parameter
|
||||
rather than a property, add the `val` property `myName` and assign `name` value
|
||||
to the property `myName` inside the `init` section.
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## Complex Constructors (#3)
|
||||
|
||||
Show that multiple `init` sections are executed in declaration order. The starter
|
||||
Show that multiple init sections are executed in declaration order. The starter
|
||||
code contains `MultipleInit` class with a
|
||||
`val initOrder = mutableListOf<String>()` property. Add the `String`s `"one"`,
|
||||
`"two"` and `"three"` to the `initOrder` property in three different `init`
|
||||
|
|
|
@ -2,4 +2,4 @@
|
|||
|
||||
The starter code contains the classes `Shape`, `Circle` and `Rectangle`.
|
||||
`Circle` and `Rectangle` use composition and store an instance of `Shape`.
|
||||
Modify them to use inheritance instead of composition.
|
||||
Modify them to use inheritance instead.
|
||||
|
|
|
@ -2,11 +2,11 @@
|
|||
|
||||
The starter code contains implementations of `Stack` and `Queue` classes.
|
||||
|
||||
`Stack` provides last-in-first-out access to elements. You can add ("push")
|
||||
new elements, and get ("pop") the last element that was added.
|
||||
`Stack` provides a last-in-first-out access to elements. You can add ("push")
|
||||
new elements to it, and get ("pop") the last one that was added.
|
||||
|
||||
`Queue` provides first-in-first-out access to elements. You can add new
|
||||
elements to it, and get ("poll") returns the first element that was added.
|
||||
`Queue` provides a first-in-first-out access to elements. You can add new
|
||||
elements to it, and get ("poll") returns you the first one that was added.
|
||||
|
||||
In the starter code, both `Stack` and `Queue` extend `ArrayList`, which opens
|
||||
too many methods in the public API (for example, you can get the first element
|
||||
|
|
|
@ -5,7 +5,7 @@ Based on your solution for the previous exercise, modify the implementation of
|
|||
`MutableList`. `ArrayDeque` represents a "double ended queue", so it provides
|
||||
member functions to add last and remove first elements.
|
||||
|
||||
Note that composition allows you to change the internal implementation of the
|
||||
Note how with composition you can change the internal implementation of the
|
||||
class without changing the code that uses that class.
|
||||
|
||||
`ArrayDeque` is currently experimental in the Kotlin library, so we must add
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
## Inheritance & Extensions (#1)
|
||||
|
||||
The starter code contains `Duck` and `interactWithDuck()` declarations (we
|
||||
assume they're part of a third-party library). Implement the `mimicDuck()`
|
||||
assume they're part of the third-party library). Implement the `mimicDuck()`
|
||||
function that dynamically adapts an object, accepting a `Crocodile` and
|
||||
returning an `IAmHonestlyDuck`. `IAmHonestlyDuck` should implement `Duck` and
|
||||
delegate both `Duck` member functions to `crocodile.bite()`. Is it possible to
|
||||
|
|
|
@ -4,4 +4,4 @@ The starter code contains an `open` class `Cleanser` and a class `Detergent`
|
|||
that inherits it. Add to the `Cleanser` class the property
|
||||
`var ops: MutableList<String>` and the functions `dilute()`, `apply()` and
|
||||
`scrub()` that simply add their names to `ops`. In `main`, make sure that
|
||||
`Detergent` now has the same functions as `Cleanser`.
|
||||
`Detergent` has now the same functions as `Cleanser`.
|
||||
|
|
|
@ -22,7 +22,7 @@ Define a standalone function `<T> traceAll(select: Selector<T>)` that uses
|
|||
`select` to append all the values of `current()` to `trace` using `+=`, then
|
||||
returns `trace`.
|
||||
|
||||
Inherit `Container` from `Iterable<T>`, and add a function called
|
||||
Now make `Container` inherit from `Iterable<T>`, and add a function called
|
||||
`iterator()` that returns an instance of an anonymous inner class that inherits
|
||||
from `Iterator<T>`. Add a standalone function `<T> traceAll2(ib: Iterable<T>)`
|
||||
that produces the same behavior as `traceAll()`.
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## Sealed Classes (#3)
|
||||
|
||||
Modify `SealedSubclasses.kt` so that all subclasses of `Top` are nested
|
||||
Modify `SealedSubclasses.kt` so that all the subclasses of `Top` are nested
|
||||
within `Top`. Create a seeded random-number generator by defining `val rand =
|
||||
Random(17)`. Use this generator to randomly select a subclass of `Top` and
|
||||
display its `simpleName`.
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
## Secondary Constructors (#3)
|
||||
|
||||
Replace all constructors in the `GardenItem` class with a single primary
|
||||
Replace all the constructors in the `GardenItem` class with a single primary
|
||||
constructor using default arguments.
|
||||
|
|
|
@ -4,8 +4,8 @@ Modify `Insects.kt` so that `Insect` is a `sealed` class (this may require
|
|||
modifications to other components). Change `basic()` to use a `when`
|
||||
expression.
|
||||
|
||||
What does this gain you, since the `else` clauses in the `when` expressions
|
||||
still make sense?
|
||||
The `else` clauses in the `when` expressions still make sense, so how does this
|
||||
benefit you?
|
||||
|
||||
<sub> This task doesn't contain automatic tests,
|
||||
so it's always marked as "Correct" when you run "Check".
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
Create a generic interface called `Items` with a single function `next()` that
|
||||
returns an object of the generic type, or `null`. Make `Items` usable for
|
||||
SAM conversions.
|
||||
SAM conversions (see [Interfaces]).
|
||||
|
||||
Create a generic function called `itemIter()` that takes a `vararg items` of
|
||||
the type parameter and returns an `Items` object produced with a SAM
|
||||
|
|
|
@ -9,11 +9,11 @@ return the `String` result.
|
|||
|
||||
- `createList()` behaves like `buildList()`. This function has one generic
|
||||
parameter. Create an `ArrayList<T>`, call the extension lambda argument on it,
|
||||
and return the `List` in immutable form.
|
||||
and return a read-only `List`.
|
||||
|
||||
- `createMap()` behaves like `buildMap()`. This function has two generic
|
||||
parameters. Create a `HashMap<K, V>`, call the extension lambda argument on it,
|
||||
and return the `Map` in immutable form.
|
||||
and return a read-only `Map`.
|
||||
|
||||
The code in `main()` tests your functions against the standard library
|
||||
versions. Notice that `buildList()` and `buildMap()` infer their generic
|
||||
|
|
|
@ -7,7 +7,7 @@ default value of `false`. In `main()`, create three `var`s: `d` of type `Double`
|
|||
for `notNull()`.
|
||||
|
||||
Using `capture` from `atomictest`, try reading from `d`, `s` and `f` before
|
||||
they are initialized. Validate the output using `atomictest.eq`. Then set
|
||||
they are initialized and validate the output using `atomictest.eq`. Then set
|
||||
`d` to `1.1`, `s` to `"yes"` and `f` to `Flag(true)` and use `eq` to verify
|
||||
that they all take on the new values.
|
||||
|
||||
|
|
|
@ -9,8 +9,9 @@ class Delegator {
|
|||
}
|
||||
```
|
||||
|
||||
Define `getValue()` and `setValue()` as extension functions to `List<String>`.
|
||||
The code in `main()` will test your solution.
|
||||
Define `getValue()` and `setValue()` as extension functions to `List<String>`
|
||||
(Hint: IntelliJ IDEA will generate skeletons for you). The code in `main()`
|
||||
will test your solution.
|
||||
|
||||
BONUS: Try adjusting `getValue()` and `setValue()` to work with:
|
||||
|
||||
|
@ -22,12 +23,6 @@ class Delegator {
|
|||
|
||||
And explain what happens.
|
||||
|
||||
<div class="hint">
|
||||
|
||||
IntelliJ IDEA will generate skeletons for you.
|
||||
|
||||
</div>
|
||||
|
||||
<sub> This task doesn't contain automatic tests, so
|
||||
it's always marked as "Correct" when you run "Check".
|
||||
Please compare your solution to the one provided! </sub>
|
||||
<sub> This task doesn't contain automatic tests,
|
||||
so it's always marked as "Correct" when you run "Check".
|
||||
Please compare your solution with the one provided! </sub>
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
## Check Instructions (#3)
|
||||
|
||||
This exercise further explores ranges, introduced in the atom Looping & Ranges,
|
||||
and shows how they can be used with check instructions.
|
||||
This exercise further explores ranges, introduced in [Looping &
|
||||
Ranges], and shows how they can be used with check
|
||||
instructions.
|
||||
|
||||
Create a class `Level` with two constructor arguments: `val range: IntRange`,
|
||||
and `private var level: Int`. `level` has a default argument that is the
|
||||
|
|
|
@ -1,16 +1,13 @@
|
|||
// ExceptionHandling/CaptureImplementation.kt
|
||||
package exceptionhandling
|
||||
import atomictest.CapturedException
|
||||
import atomictest.eq
|
||||
|
||||
fun capture(f: () -> Unit): CapturedException =
|
||||
try { // [1]
|
||||
fun capture(f: () -> Unit): String = // [1]
|
||||
try { // [2]
|
||||
f()
|
||||
CapturedException(null, // [2]
|
||||
"<Error>: Expected an exception")
|
||||
} catch (e: Throwable) { // [3]
|
||||
CapturedException(e::class,
|
||||
if (e.message != null) ": ${e.message}"
|
||||
else "")
|
||||
"Error: Expected an exception" // [3]
|
||||
} catch (e: Throwable) { // [4]
|
||||
"${e::class.simpleName}: ${e.message}"
|
||||
}
|
||||
|
||||
fun main() {
|
||||
|
@ -19,5 +16,5 @@ fun main() {
|
|||
} eq "Exception: !!!"
|
||||
capture {
|
||||
1
|
||||
} eq "<Error>: Expected an exception"
|
||||
} eq "Error: Expected an exception"
|
||||
}
|
|
@ -1,7 +1,7 @@
|
|||
## Logging (#1)
|
||||
|
||||
The starter code includes `class Level`, which is the solution of Exercise 3
|
||||
from the Check Instructions atom.
|
||||
from [Check Instructions].
|
||||
|
||||
Create a class called `Pipe` that takes `val level: Level` as a constructor
|
||||
parameter. Give this parameter a default argument with a range `0..10`.
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
## Logging (#2)
|
||||
|
||||
Starting with the solution from Exercise 3 from the Exception
|
||||
Handling atom, use `AtomicLog.kt` to log exceptions into the
|
||||
Starting with the solution from Exercise 3 in [Exception
|
||||
Handling], use `AtomicLog.kt` to log exceptions into the
|
||||
`Logger` file `"LoggingSoln1.txt"`. You will need to modify `transact()`:
|
||||
|
||||
- Add a call to `Logger`s `error()` function before any exception is thrown
|
||||
|
|
|
@ -6,7 +6,7 @@ function that uses `java.io.File`. Create a `File` object initialized to
|
|||
and add `text` to the file (IntelliJ IDEA will give you hints to help choose
|
||||
the member functions to call for `File`). Use `useLines()` to read the file and
|
||||
display it with `println()`, then use `forEachLine()` to read the file and
|
||||
display it with `println()`. The starter code in `main()` tests
|
||||
display it with `println()`. The starter code in `main()`
|
||||
`writeAndRead()`.
|
||||
|
||||
<sub> This task doesn't contain automatic tests,
|
||||
|
|
|
@ -1,19 +1,6 @@
|
|||
// NothingType/ListOfNothing.kt
|
||||
import atomictest.eq
|
||||
|
||||
fun main() {
|
||||
val none: Nothing? = null
|
||||
|
||||
var nullableString: String? = null // [1]
|
||||
nullableString = "abc"
|
||||
nullableString eq "abc"
|
||||
nullableString = none
|
||||
nullableString eq null
|
||||
|
||||
val nullableInt: Int? = none
|
||||
nullableInt eq null
|
||||
|
||||
val listNone: List<Nothing?> = listOf(null)
|
||||
val ints: List<Int?> = listOf(null) // [4]
|
||||
ints eq listNone
|
||||
}
|
|
@ -4,8 +4,8 @@ Create an exception class called `Failure` that takes a `msg: String` parameter
|
|||
and passes it to the base-class constructor. Write a function `fail(msg:
|
||||
String)` that passes `msg` to `trace()`, and then throws a `Failure`.
|
||||
|
||||
Now write your own versions of `require()` and `check()` (from the Check
|
||||
Instructions atom) that use `fail()`. The starter code in `main()` tests your
|
||||
Now write your own versions of `require()` and `check()` (from [Check
|
||||
Instructions]) that use `fail()`. The starter code in `main()` tests your
|
||||
functions.
|
||||
|
||||
<sub> This task doesn't contain automatic tests,
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## Booleans (#1)
|
||||
|
||||
Guess the answers for the following Boolean expressions and then check yourself
|
||||
Guess the answers for the following boolean expressions and then check yourself
|
||||
using Kotlin:
|
||||
|
||||
```kotlin
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
Attempt to combine various `val`s of different types using the `+` operator.
|
||||
Only combine two at a time, and assign each combination to a `val` result. See
|
||||
which types combine. On the console, display the name of the type that can be
|
||||
combined with any other type if it appears first, and the name of the type that
|
||||
combined with any other type if it goes first, and the name of the type that
|
||||
can't be combined with itself using `+`.
|
||||
|
||||
Replace the lines containing `TODO()` in the solution code with working code.
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
## Data Types (#3)
|
||||
|
||||
Guess the results of the following expressions, then check your guesses using
|
||||
Kotlin:
|
||||
Guess the results of the following expressions and then check your guesses
|
||||
using Kotlin:
|
||||
|
||||
```kotlin
|
||||
val c1 = 'a' + 1
|
||||
|
@ -9,7 +9,7 @@ val c2 = 'a' + 25
|
|||
val c3 = 'E' - 2
|
||||
```
|
||||
|
||||
Open the hint within IntelliJ IDEA to understand the results.
|
||||
You can open the hint within IntelliJ IDEA to understand the results.
|
||||
|
||||
<div class="hint">
|
||||
|
||||
|
|
|
@ -3,9 +3,5 @@
|
|||
Using a `for` loop, create a function that calculates the factorial of its
|
||||
parameter (`n! = 1 * 2 * ... * n`).
|
||||
|
||||
<div class="hint">
|
||||
|
||||
Put an `L` at the end of a number literal or use `.toLong()` to convert an
|
||||
integer constant or expression to type `Long`.
|
||||
|
||||
</div>
|
||||
|
|
|
@ -1,11 +1,8 @@
|
|||
## Number Types (#2)
|
||||
|
||||
Discover which of the following values can't be stored in an `Int` type:
|
||||
Check which of the following values can't be stored in an `Int` type:
|
||||
|
||||
- A million (10^6^)
|
||||
|
||||
- A billion (10^9^)
|
||||
|
||||
- A trillion (10^12^)
|
||||
|
||||
- A quintillion (10^18^)
|
||||
|
|
|
@ -2,11 +2,6 @@
|
|||
|
||||
Create two functions: the first converts Fahrenheit to Celsius, and the second
|
||||
converts Celsius to Fahrenheit. To convert Fahrenheit to Celsius, first
|
||||
subtract `32`, then multiply by `5/9`. To convert Celsius to Fahrenheit, first
|
||||
multiply by `9/5`, then add `32`.
|
||||
|
||||
<div class="hint">
|
||||
|
||||
If you get an unexpected `0`, check to make sure you aren't using integer math.
|
||||
|
||||
</hint>
|
||||
subtract `32`, then multiply by `5/9`. If you get `0`, check to make sure you
|
||||
aren't using integer math. To convert Celsius to Fahrenheit, first multiply by
|
||||
`9/5`, then add `32`.
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
## Summary 1 (#4)
|
||||
|
||||
This exercise modifies `Overflow.kt` to test `Long` and `Double`. Implement
|
||||
`testLong()` to display `Long`'s maximum value incremented by `1`. Make
|
||||
`testLong()` to display the `Long` maximum value incremented by `1`. Make
|
||||
`testDouble()` display the `Double` maximum value incremented by `1`. Make
|
||||
`testDouble2()` display the result of comparing `Double.MAX_VALUE` and
|
||||
`Double.MAX_VALUE + 1`.
|
||||
|
|
|
@ -2,5 +2,5 @@
|
|||
|
||||
Implement `everyFifthNonWhitespace()` to display every fifth non-whitespace
|
||||
character in the given text. For example, `everyFifthNonWhitespace("abc d e fgh
|
||||
ik")` displays the characters `e` (the fifth character if not counting
|
||||
whitespaces) and `k` (the tenth).
|
||||
ik")` displays the characters `e` (fifth character if not counting
|
||||
whitespaces) and `k` (tenth).
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
## The `in` Keyword (#2)
|
||||
|
||||
Use `step` to write a function that sums only even numbers, up to a given
|
||||
Use `step` to write a function that sums only even numbers up to a given
|
||||
number (the parameter).
|
||||
|
|
|
@ -4,8 +4,4 @@ Write a function that checks whether its `String` parameter is a valid
|
|||
identifier. A valid identifier is a non-empty `String` that starts with a letter
|
||||
or underscore and consists of only letters, digits and underscores.
|
||||
|
||||
<div class="hint">
|
||||
|
||||
Use `s.isEmpty()` to check whether `s` is an empty `String`.
|
||||
|
||||
</div>
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
## `var` & `val` (#1)
|
||||
|
||||
Define `val answer` and initialize it to `42`. On the next line, try to
|
||||
Define a `val answer` and set its value to `42`. On the next line, try to
|
||||
reassign `answer` to `43`. What error does Kotlin produce? Fix the error by
|
||||
replacing `val` with `var`. Display the value of `answer` on the console.
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
## `var` & `val` (#2)
|
||||
|
||||
Define `var a = 10` and a `val b = a`. Now assign `42` to `a` and
|
||||
Define `var a = 10`. Now define a `val b = a`. Now assign `42` to `a` and
|
||||
display both `a` and `b` on different lines.
|
||||
|
|
|
@ -12,7 +12,8 @@ println(y) // 1
|
|||
```
|
||||
|
||||
Your code should remain unchanged for different initializers, like `var x =
|
||||
"first"`, `var y = "second"`.
|
||||
"first"`, `var y = "second"`. Thus, using `x = 2`, `y = 1` is not the expected
|
||||
solution.
|
||||
|
||||
<div class="hint">
|
||||
|
||||
|
|
|
@ -6,7 +6,7 @@ values during the copy:
|
|||
|
||||
```kotlin
|
||||
fun AirlineTicket.transferTicket(
|
||||
newFirstName: String,
|
||||
newLastName: String
|
||||
otherFirstName: String,
|
||||
otherLastName: String
|
||||
): AirlineTicket
|
||||
```
|
||||
|
|
|
@ -6,8 +6,8 @@ allow that class to be used in a destructuring declaration. Start with
|
|||
The code no longer compiles. IntelliJ IDEA will prompt you and automatically
|
||||
fill in the skeleton definitions for `operator fun component1()` and `operator
|
||||
fun component2()`, or you may do this by hand. (Note: we do not cover the
|
||||
`operator` keyword until [Operator Overloading], but you don't need to
|
||||
understand it for this exercise). Provide bodies for these functions and show
|
||||
that the rest of the code now works. Consider how much more work (and visual
|
||||
noise) results from more fields in the class, and how much effort is saved by
|
||||
using `data` classes.
|
||||
`operator` keyword until [Operator Overloading], but you
|
||||
don't need to understand it for this exercise). Provide the correct bodies for
|
||||
these functions and show that the rest of the code still works without
|
||||
modifying it. Consider how much more work (and visual noise) results from more
|
||||
fields in the class, and how much effort is saved by using `data` classes.
|
||||
|
|
|
@ -15,5 +15,4 @@ top-left corner:
|
|||
```
|
||||
|
||||
Moving right increases the `x` coordinate, moving down increases the `y`
|
||||
coordinate, moving left and up decrease the `x` and `y` coordinates,
|
||||
respectively.
|
||||
coordinate, moving left and up decrease the `x` and `y` coordinates.
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
## Extension Functions (#1)
|
||||
|
||||
Implement an `xmlTag(tag: String)` extension function that wraps the `String`
|
||||
it extends inside the XML `tag` given in the parameter. (See Wikipedia for an
|
||||
it extends inside the XML tag given in the parameter. (See Wikipedia for an
|
||||
overview of XML).
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
## Extension Functions (#2)
|
||||
|
||||
Implement `isOdd()` and `isEven()` as `Int` extension functions that produce
|
||||
a `Boolean` indicating whether the `Int` is odd or even, respectively.
|
||||
a `Boolean` indicating whether that `Int` is odd or even, respectively.
|
||||
|
|
|
@ -2,4 +2,4 @@
|
|||
|
||||
Implement a `String` extension function `orEmpty()` that returns the receiver
|
||||
`String` if it is not `null`, and an empty `String` if the receiver is `null`.
|
||||
(The Kotlin standard library contains `orEmpty()`).
|
||||
(Note that the Kotlin standard library contains `orEmpty()`).
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## Extensions for Nullable Types (#2)
|
||||
|
||||
Implement `and()` and `or()` functions that extend nullable `Boolean`. These
|
||||
Implement `and()` and `or()` functions that extend a nullable `Boolean`. These
|
||||
functions each take a second nullable `Boolean` as a parameter and return
|
||||
`null` if either the receiver or the argument is `null`. For non-`null` values
|
||||
these functions behave the same as ordinary `and` and `or` operations.
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
## Extensions for Nullable Types (#3)
|
||||
|
||||
The starter code contains a `data` class called `Container`. Write extension
|
||||
functions for nullable `Container`s called `empty()` and `full()` which check
|
||||
whether the `contents` are `null` or not `null`, respecively.
|
||||
functions for nullable `Container`s called `empty()` and `full()` checking
|
||||
that the `contents` is `null` or not `null` accordingly.
|
||||
|
|
|
@ -12,4 +12,4 @@ three member functions:
|
|||
the `CountingSet`. If the element isn't present in `CountingSet` the result
|
||||
is zero.
|
||||
|
||||
- `toSet()` returns a set containing the stored elements.
|
||||
- `toSet()` returns a set of stored elements.
|
||||
|
|
|
@ -3,5 +3,5 @@
|
|||
Define a `Rectangle` class with a constructor that takes parameters of `side1:
|
||||
Double`, `side2: Double` and `color: String`. Assign default arguments of
|
||||
`1.0` for `side1`, `2.0` for `side2` and `"yellow"` for `color`. Add a
|
||||
`toString()` that produces `"$color Rectangle $side1 x $side2"`. In `main()`,
|
||||
`toString()` that produces: `"$color Rectangle $side1 x $side2"`. In `main()`,
|
||||
show all possible ways to call the constructor.
|
||||
|
|
|
@ -7,6 +7,7 @@ the comment slashes along with any whitespace after the slashes (`// `).
|
|||
|
||||
<div class="hint">
|
||||
|
||||
Use the extension function `lines()` to split a `String` into a list of lines.
|
||||
Use the extension function `lines()` to split a `String` into a list of
|
||||
lines.
|
||||
|
||||
</div>
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
## Non-`null` Assertions (#2)
|
||||
|
||||
Implement the function `sumFirstAndLast(ints: List<Int>)` so it returns a sum
|
||||
Implement the function `sumFirstAndLast(ints: List<Int>)` that returns a sum
|
||||
of the first and the last elements in `ints`. If `ints` is empty, return zero.
|
||||
If `ints` consists of a single element, return that element as the result.
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
## Non-`null` Assertions (#3)
|
||||
|
||||
Implement `absValueMaxEqualsMin(ints: List<Int>)` so that it checks whether the
|
||||
Implement `absValueMaxEqualsMin(ints: List<Int>)` that checks whether the
|
||||
maximum absolute value in `ints` equals the minimum absolute value in `ints`.
|
||||
If the list is empty, return `false`.
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
## Nullable Types (#1)
|
||||
|
||||
Change the `get()` member function in the `Cage` class from the exercises in
|
||||
[Maps] so it returns `null` if the `Cage` doesn't contain a `Hamster`
|
||||
Change the `get()` member function in the `Cage` class, from the exercises in
|
||||
[Maps], so it returns `null` if the `Cage` doesn't contain a `Hamster`
|
||||
with the given name (the parameter to `get()`).
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
## `break` & `continue` (#1)
|
||||
|
||||
Implement a function `readNumbers()` that reads user input in an infinite loop.
|
||||
When the user enters zero, it `break`s from the loop and displays the sum of
|
||||
the entered numbers. If the user enters a non-number, it displays "Not a
|
||||
number: $input" and goes back to accepting input.
|
||||
When the user enters zero, it `break`s from the loop and prints the sum of the
|
||||
entered numbers. If the user enters a non-number, it prints "Not a number:
|
||||
$input" and goes back to accepting input.
|
||||
|
|
|
@ -2,17 +2,17 @@
|
|||
|
||||
Complete the implementation of the functions `analyzeStrings1()` and
|
||||
`analyzeStrings2()` provided in the starter code. Each function takes a
|
||||
parameter which is a `List<List<String>>` and displays its contents to the
|
||||
console. If a `String` is the word `"stop"`, don't display any more elements
|
||||
from the current (inner) `List`. The code in `analyzeStrings1()` uses `break`,
|
||||
while `analyzeStrings2()` uses `continue`. Add the missing labels for `break`
|
||||
and `continue`.
|
||||
`List<List<String>>` as an argument and displays its contents to the console.
|
||||
If a `String` is the word `"stop"`, don't display any more elements from the
|
||||
current (inner) `List`. The code in `analyzeStrings1()` uses `break`, while
|
||||
`analyzeStrings2()` uses `continue`. Add the missing labels for `break` and
|
||||
`continue`.
|
||||
|
||||
Now rewrite `analyzeStrings1()` without using labels.
|
||||
|
||||
<div class="hint">
|
||||
|
||||
You can remove all the labels from `analyzeStrings1()` and `break` will
|
||||
jump from the closest inner loop, so that loop doesn't need labels.
|
||||
jump from the closest inner loop, so this loop doesn't need labels.
|
||||
|
||||
</div>
|
||||
|
|
|
@ -4,4 +4,4 @@ Create a function `cloudiness(cloudPercent: Int)` that returns a description
|
|||
based on the percentage of cloudiness: "Sunny" (when `cloudPercent` is in the
|
||||
range 81..100), "Mostly Sunny" (61..80), "Partly Sunny" (41..60), "Mostly
|
||||
Cloudy" (21..40), and "Cloudy" (0..20). If the argument is not in the range
|
||||
0..100, throw an `IllegalArgumentException`.
|
||||
0..100, throw `IllegalArgumentException`.
|
||||
|
|
|
@ -1,14 +1,15 @@
|
|||
## `when` Expressions (#3)
|
||||
|
||||
Implement the `balanced()` function, which takes a `String` parameter. The
|
||||
Implement the function `balanced()` that takes a `String` parameter. The
|
||||
argument must consist of parentheses and optional spaces; for example:
|
||||
`"()(())"`. `balanced()` checks whether each opening parenthesis has a
|
||||
corresponding closing parenthesis and if all parentheses are properly nested.
|
||||
`"()(())"`. When you pass this argument to `balanced()`, it checks whether each
|
||||
opening parenthesis has a corresponding closing parenthesis and if all
|
||||
parentheses are properly nested.
|
||||
|
||||
Ignore whitespace in the input `String`. If the `String` contains characters
|
||||
other than parentheses and whitespace, throw an `IllegalArgumentException`.
|
||||
|
||||
Examples:
|
||||
Some examples:
|
||||
|
||||
- `"()"` is balanced
|
||||
|
||||
|
|
|
@ -1487,8 +1487,8 @@ public class TestAllExamples extends AbstractTestExamples {
|
|||
}
|
||||
|
||||
@Test
|
||||
public void testImmutableBlendMap() {
|
||||
testExample("../AtomicKotlinCourse/Functional Programming/Building Maps/Examples/src/ImmutableBlendMap.kt", buildingmaps.ImmutableBlendMapKt::main);
|
||||
public void testReadOnlyBlendMap() {
|
||||
testExample("../AtomicKotlinCourse/Functional Programming/Building Maps/Examples/src/ReadOnlyBlendMap.kt", buildingmaps.ReadOnlyBlendMapKt::main);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
Loading…
Reference in New Issue