Computing the value of a hand¶
Level: beginner
Our first challenge is to fix the computation of the value of a hand.
When there are multiple cards on the table, the player is only allowed to place cards with a higher value.
For example, if the card 3 is placed on the table, it is legal to play 4 (because 4 is strictly greater than 3), but it is not legal to play 2 , because 2 is not strictly greater than 3.
I already know Kotlin, and want to solve this without help
The goal is to implement the placing rule. You can run the tests using Check (JVM-only). Only one file needs to be changed, the challenge is successful when all tests pass.
1. Reading the existing code¶
Let's start by looking at the existing code in core/src/commonMain/kotlin/Deck.kt. A deck represents multiple cards placed together.
The file starts with:
This is a comment. Comments are messages that developers leave for other developers; they are ignored by the programming language. There are three types of comments:- Anything on the right side of
//is a comment, on the same line. - Everything between
/*and*/is a comment, even if they are on multiple lines.
This declares that this file belongs to the package io.bordeauxkt.kotlin15. A package is similar to a folder: it helps organize similar code so it stays together.
/**
* Multiple cards placed together.
*
* The cards must **either**:
* - All have the same [value][Card.value].
* - All have the same [color][Card.color].
*
* A deck has a [value].
*
* To store arbitrary cards, see [Hand].
*/
data class Deck(
val cards: Set<Card>,
) {
// …
}
Here, we create a data class called Deck. A data class is an entity composed of some data. The data that composes it is declared between the parentheses. We call it a property. Deck has a single property:
valmeans "value". A value does not change over time.cardsis the name of the property.- The
:means that what follows is the type of the property. The type specifies what kind of data the property holds. Set<Card>is read "set of cards". A set is a collection of cards that cannot contain duplicates: all cards must be different from each other.
All together, we declare that a Deck is something composed of multiple cards (stored in a property called cards), and a deck cannot contain the same card multiple times.
The class declaration ends with brackets: { and } multiple lines later. Brackets represent a "block" that gives more information about something. Here, all the contents of the block describe what a deck does.
init {
require(isLegal(cards)) { "All cards in a deck must either have the same color, or have the same value, but this deck has neither: $cards" }
}
init {} is a special block in a class that specifies code to execute when the class is created.
Here the code is calling the require() function, which verifies a constraint and crashes the application when the verification fails.
The verification is a call to isLegal(cards), which verifies that the cards contained in the deck are valid. We can ignore this for now.
/**
* The value of a deck.
*
* A deck `[2 Red, 3 Red]` has value 32:
* - The cards are sorted in descending order
* - The cards' values are concatenated together
*/
val value: Int = 0 // TODO!
This is the property we're interested in!
As a reminder:
/** … */is a comment: it is documentation for the other developers.valdeclares a value: a property that doesn't change.valueis its name.: Intis its type.Intis an integer: a number that does not have a decimal part. For example,1,19or-7.= 0is the actual value of thevalueproperty. As it is written, no matter what happens, the value is0.
Currently, the code computes the value 0 for any deck. Our first challenge will be to fix the value computation so the game can function properly.
2. Running the tests¶
The project comes with an extensive test suite which we can use to verify that our changes are correct.
To run the tests, find the green arrow on the top right. In the drop-down, choose Check (JVM-only), which will run all tests using the JVM.
To run all tests using all supported platforms (JVM, JS using a browser, Node.js and iOS), you can run Check. However, in this project, the platforms all use the exact same code, so running just the JVM tests gives us enough information and is faster.
The first run can take some time, but the next ones should only take a few seconds.
You should see 21 failed tests, the first one being:
java.lang.IllegalStateException:
check(deck.value == 1)
| | |
| 0 false
[1 Red]
at io.bordeauxkt.kotlin15.DeckTestKt$DeckTest$2$2$2.invokeSuspend(DeckTest.kt:76)
at io.bordeauxkt.kotlin15.DeckTestKt$DeckTest$2$2$2.invoke(DeckTest.kt)
at io.bordeauxkt.kotlin15.DeckTestKt$DeckTest$2$2$2.invoke(DeckTest.kt)
Tip
If the test names look like <tb<io.bordeauxkt.kotlin15.DeckTest↘Value↘A deck with a single card…>tb>, install the TestBalloon plugin in (top left) | File | Settings | Plugins and searching for TestBalloon, then clicking 'Install'. Once the plugin is installed, you can rerun the Check (JVM-only) configuration to see the real test names.
Let's read the failed test.
The first line tells us that the error is Java's
IllegalStateException. IllegalStateException means "the program detected that it is in an incorrect state".
check()is a function that verifies a condition. If the condition isfalse, it fails the test withIllegalStateException. Since that's the exception we have, we know that the condition failed.- We start the line with
deck. Following the|symbol down, we can see that thedeckcontained a single card: 1 . - Then, the test accesses the value of the deck:
deck.value. Following the|symbol down, we can see that the value of the deck is0. This is what we just saw in the code! - However,
== 1means that the test expected the value to be1in this situation.
Tip
This visualization of the test results is provided by the Power Assert plugin, which is already configured in the project.
at io.bordeauxkt.kotlin15.DeckTestKt$DeckTest$2$2$2.invokeSuspend(DeckTest.kt:76)
at io.bordeauxkt.kotlin15.DeckTestKt$DeckTest$2$2$2.invoke(DeckTest.kt)
at io.bordeauxkt.kotlin15.DeckTestKt$DeckTest$2$2$2.invoke(DeckTest.kt)
at io.bordeauxkt.kotlin15means that the code is from theio.bordeauxkt.kotlin15package, which is the same package as the code we're writing.DeckTestKtmeans that the code is from theDeckTestKtclass, which is created by theDeckTest.ktfile.$DeckTest$2$2$2.invokeSuspend()is the method identifier, but it is not particularly useful for tests, so we will not explain it here.DeckTest.kt:76tells us that it is in theDeckTest.ktfile at line76. In Android Studio, you can click it to go to the correct file if you want to read how the test is written. We will not touch the tests in this challenge.
3. The value of a single card¶
The value of a single card deck, for example
3 ,
is the value of the card, here 3. Let's implement it!
Let's go back to core/src/commonMain/kotlin/Deck.kt.
Currently, the code reads:
We want to replace the 0 by the value of the card.
For now, if a deck has multiple cards, or no cards at all, we will continue to return 0.
Therefore, we need:
- A way to make a decision: we want a different behavior if there is exactly one card, or if there are 0 or more than one card.
- A way to count the number of cards in a set of cards: we need to know if there is exactly one card to make the decision.
- A way to get the value of a card, because that's the result we want.
- Making a decision
-
Decisions are the most important part of programming: it's how we tell the computer what to do. There are many ways to express decisions, but the simpler is the
Replace:ifkeyword.- condition by the code that decides which branch to take. For example, we saw an example condition previously in the test:
deck.value == 1which verifies that thevalueof thedeckis equal to1. Note that we use two=symbols, not just one, to differentiate the creation of the value like inval value: Int = 0. - code-true by any code you want to run if the condition is
true(success). - code-false by any code you want to run if the condition is
false(failure).
- condition by the code that decides which branch to take. For example, we saw an example condition previously in the test:
- Counting cards
-
A set of cards can hold any number of cards. For now, we only want to handle the case with a single card, so we need to be able to count them. Kotlin provides one of the richest APIs of any programming language for dealing with collections, including sets. Can you find the correct property?
Also find a way to access the first card in a set.
- Getting the value of a card
-
Cards are defined in the
Card.ktfile.
Now that you have all the pieces, you only need to assemble the puzzle!
To verify your solution, run Check (JVM-only) again. There should only be 13 failed tests, and they should all strictly have more than one card in their deck.
Once you succeeded in this step, you can move on to the next one. If you have any questions, don't hesitate to ask the organizers!
4. Multiple cards¶
Congratulations on the first step.
We're not done yet, however: a player can place one more card than is on the table.
For example, if the cards 7 3 are on the table, a player must play either 2 cards (the same number of cards as the table) or 3 cards (one more card than the table).
When playing multiple cards at once, all the cards must either:
- Be of the same color, for example 2 1 , or,
- Be of the same value, for example 3 3 .
This verification is already implemented by the method isLegal() in Deck.kt.
However, our code computes a value of 0 for any deck with multiple cards. Instead, the value should be computed using the following rules:
The played cards must have greater value than the table. The value of a deck is the concatenation of the values of the individual cards, in descending order.
Examples:
- 7 3 has value 73 (concatenation of 7 and 3).
- 3 3 has value 33 (concatenation of 3 and 3).
- 1 2 has value 21 (concatenation of 2 and 1: the highest card goes first).
- 3 9 2 6 5 has value 96532.
Notice that the color of the cards does not matter. The order of the cards does not matter either, since the value is always in descending order.
To solve this challenge, we need:
- Since we only care about the value of the cards, a way to convert a list of cards into a list of values.
- A way to sort values, to be sure we read them from the highest to the lowest.
- A way to concatenate values.
- Converting a collection into another
-
When we have a list of something, we can convert it into a list of something else by providing a way to convert one element into another. This is one of the powers of functional programming: we can perform any operation on a collection if we know how to perform it on one item, using the function
.map {}.For example, we can get the first name of a player in all upper-case with
player.name.uppercase().If we have multiple players in a
List<Player>or aSet<Player>calledplayers, we can writeplayers.map { it.name.uppercase() }, which will output aList<String>(Stringmeans text). Inside the brackets, we use the same code as for a single player, but using the special variableit. The code will run multiple times (once for each player). On each run, the current player will be init. - Sorting
-
Sorting is one of the most common problems in programming. Of course, Kotlin provides multiple ways to sort items.
The simplest way is to use the
.sorted()function, which can sort any list as long as its items can be sorted in natural order. Such items are calledComparable. Some types are comparable, some are not. Numeric types (Int,Float, etc) are comparable and sort from lowest to highest. Text types (Char,String) are comparable and sort in alphanumeric order of the Unicode code points (dictionary order). However, aCarditself is not comparable: what would be the default order? By value, by color, by a combination of the two?Remember that we want the values from highest to lowest, but sort functions return values from the lowest to highest by default. You can find useful functions in list.
- Concatenating values
-
When we have the values
5and4, we want to return the number54. This is called concatenation. Concatenation is not a standard mathematical operator on numeric types, but it is a standard operator on text types. This leads to two main different ways to solve this problem: textually or numerically.The textual solution is the simplest to write. It uses the function
.joinToString()on a list to concatenate all its elements together. However, by default, it gives an output like5, 4, not54. Additionally, the output is aString, but we must return anInt, how can we do that?The numeric solution is slightly more involved but is faster and uses less memory. It is based on the realization that concatenation of two numbers
5and4can be written as5 * 10 + 4, which gives the expected result54(in programming languages,*is often used for the product operator×). This relationship holds for more numbers: the concatenation of8,3and2can be written(8 * 10 + 3) * 10 + 2. To combine items of a list into a single value using a mathematical operator, we can use the function.reduce {}.
Now that you hold all pieces of the puzzle, can you solve it?
Once your code is correct, all the tests should be successful.
You can now play the game for real! Congratulations!
5. Optimize¶
Level: beginner with more autonomy
If you want to go further, we can take a few steps to further optimize our solution. Remember to re-run the tests after each change to verify you didn't break your solution.
- Currently,
valueis computed once for everyDeck. Some decks are created without ever accessingvalue. Instead, we could computevaluelazily, the first time it is needed. - If you used the textual concatenation, replace it by the numeric concatenation, which uses less memory and is slightly faster.
- If you used different code for the case with a single card and the case with multiple cards, try to merge them to use the exact same code for both cases.
- If you used different code for the case with no cards at all and the other cases, try to merge them to use the exact same code for all cases. You may be interested in learning more about null safety.
- Try avoiding intermediary lists. For example,
.map {}creates a temporary list.valuecan be implemented using a single intermediary list. - Try to simplify the code as much as possible. In Kotlin, it is frequent that the shortest code is the simplest to understand and also the most efficient.
The simplest solution we found uses only two function calls and a single intermediary list. Tell us if you find better!