diff --git a/concepts/maps/.meta/config.json b/concepts/maps/.meta/config.json new file mode 100644 index 000000000..98c459cdc --- /dev/null +++ b/concepts/maps/.meta/config.json @@ -0,0 +1,7 @@ +{ + "blurb": "Maps are a collection of key value pairs.", + "authors": [ + "kahgoh" + ], + "contributors": [] +} diff --git a/concepts/maps/about.md b/concepts/maps/about.md new file mode 100644 index 000000000..142db1139 --- /dev/null +++ b/concepts/maps/about.md @@ -0,0 +1,171 @@ +# About Maps + +A **Map** is a data structure for storing key value pairs. +It is similar to dictionaries in other programming languages. +The [Map][map-javadoc] interface defines the operations you can make with a map. + +## HashMap + +Java has a number of different Map implementations. +[HashMap][hashmap-javadoc] is a commonly used one. + +```java +// Make an instance +Map fruitPrices = new HashMap<>(); +``` + +~~~~exercism/note +When defining a `Map` variable, it is recommended to define the variable as a `Map` type rather than the specific type, as in the above example. +This practice makes it easy to change the `Map` implementation later. +~~~~ + +`HashMap` also has a copy constructor. + +```java +// Make a copy of a map +Map copy = new HashMap<>(fruitPrices); +``` + +Add entries to the map using [put][map-put-javadoc]. + +```java +fruitPrices.put("apple", 100); +fruitPrices.put("pear", 80); +// => { "apple" => 100, "pear" => 80 } +``` + +Only one value can be associated with each key. +Calling `put` with the same key will update the key's value. + +```java +fruitPrices.put("pear", 40); +// => { "apple" => 100, "pear" => 40 } +``` + +Use [get][map-get-javadoc] to get the value for a key. + +```java +fruitPrices.get("apple"); // => 100 +``` + +Use [containsKey][map-containskey-javadoc] to see if the map contains a particular key. + +```java +fruitPrices.containsKey("apple"); // => true +fruitPrices.containsKey("orange"); // => false +``` + +Remove entries with [remove][map-remove-javadoc]. + +```java +fruitPrices.put("plum", 90); // Add plum to map +fruitPrices.remove("plum"); // Removes plum from map +``` + +The [size][map-size-javadoc] method returns the number of entries. + +```java +fruitPrices.size(); // Returns 2 +``` + +You can use the [keys] or [values] methods to obtain the keys or the values in a Map as a Set or collection respectively. + +```java +fruitPrices.keys(); // Returns "apple" and "pear" in a set +fruitPrices.values(); // Returns 100 and 80, in a Collection +``` + +## HashMap uses `hashCode` and `equals` + +HashMaps uses the object's [hashCode][object-hashcode-javadoc] and [equals][object-equals-javadoc] method to work out where to store and how to retrieve the values for a key. +For this reason, it is important that their return values do not change between storing and getting them, otherwise the HashMap may not be able to find the value. + +For example, lets say we have the following class that will be used as the key to a map: + +```java +public class Stock { + private String name; + + public void setName(String name) { + this.name = name; + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (Objects.equals(Stock.class, obj.getClass()) && obj instanceof Stock other) { + return Objects.equals(name, other.name); + } + return false; + } +} +``` + +The `hashCode` and `equals` depend on the `name` field, which can be changed via `setName`. +Altering the `hashCode` can produce surprising results: + +```java +Stock stock = new Stock(); +stock.setName("Beanies"); + +Map stockCount = new HashMap<>(); +stockCount.put(stock, 80); + +stockCount.get(stock); // Returns 80 + +Stock other = new Stock(); +other.setName("Beanies"); + +stockCount.get(other); // Returns 80 because "other" and "stock" are equal + +stock.setName("Choccies"); +stockCount.get(stock); // Returns null because hashCode value has changed + +stockCount.get(other); // Also returns null because "other" and "stock" are not equal + +stock.setName("Beanies"); +stockCount.get(stock); // HashCode restored, so returns 80 again + +stockCount.get(other); // Also returns 80 again because "other" and "stock" are back to equal +``` + +## Map.of and Map.copyOf + +Another common way to create maps is to use [Map.of][map-of-javadoc] or [Map.ofEntries][map-ofentries-javadoc]. + +```java +// Using Map.of +Map temperatures = Map.of("Mon", 30, "Tue", 28, "Wed", 32); + +// or using Map.ofEntries +Map temperatures2 = Map.ofEntries(Map.entry("Mon", 30, "Tue", 28, "Wed", 32)); +``` + +Unlike `HashMap`, they populate the map upfront and become read-only once created. +[Map.copyOf][map-copyof-javadoc] makes a read-only copy of a map. + +```java +Map readOnlyFruitPrices = Map.copyOf(fruitPrices); +``` + +Calling methods like `put`, `remove` or `clear` results in an `UnsupportedOperationException`. + +[map-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html +[hashmap-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html +[map-put-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#put(K,V) +[map-get-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#get(java.lang.Object) +[map-containskey-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#containsKey(java.lang.Object) +[map-remove-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#remove(java.lang.Object) +[map-size-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#size() +[map-of-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#of() +[map-ofentries-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#ofEntries(java.util.Map.Entry...) +[map-copyof-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#copyOf(java.util.Map) +[object-hashcode-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Object.html#hashCode() +[object-equals-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object) diff --git a/concepts/maps/introduction.md b/concepts/maps/introduction.md new file mode 100644 index 000000000..aba6d4f4a --- /dev/null +++ b/concepts/maps/introduction.md @@ -0,0 +1,70 @@ +# Introduction + +A **Map** is a data structure for storing key value pairs. +It is similar to dictionaries in other programming languages. +The [Map][map-javadoc] interface defines operations on a map. + +Java has a number of different Map implementations. +[HashMap][hashmap-javadoc] is a commonly used one. + +```java +// Make an instance +Map fruitPrices = new HashMap<>(); +``` + +Add entries to the map using [put][map-put-javadoc]. + +```java +fruitPrices.put("apple", 100); +fruitPrices.put("pear", 80); +// => { "apple" => 100, "pear" => 80 } +``` + +Only one value can be associated with each key. +Calling `put` with the same key will update the key's value. + +```java +fruitPrices.put("pear", 40); +// => { "apple" => 100, "pear" => 40 } +``` + +Use [get][map-get-javadoc] to get the value for a key. + +```java +fruitPrices.get("apple"); // => 100 +``` + +Use [containsKey][map-containskey-javadoc] to see if the map contains a particular key. + +```java +fruitPrices.containsKey("apple"); // => true +fruitPrices.containsKey("orange"); // => false +``` + +Remove entries with [remove][map-remove-javadoc]. + +```java +fruitPrices.put("plum", 90); // Add plum to map +fruitPrices.remove("plum"); // Removes plum from map +``` + +The [size][map-size-javadoc] method returns the number of entries. + +```java +fruitPrices.size(); // Returns 2 +``` + +You can use the [keys] or [values] methods to obtain the keys or the values in a Map as a Set or collection respectively.studentScores + +```java +fruitPrices.keys(); // Returns "apple" and "pear" in a set +fruitPrices.values(); // Returns 100 and 80, in a Collection +``` + +[map-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html +[hashmap-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html +[map-put-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#put(K,V) +[map-get-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#get(java.lang.Object) +[map-containskey-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#containsKey(java.lang.Object) +[map-remove-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#remove(java.lang.Object) +[map-size-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#size() diff --git a/concepts/maps/links.json b/concepts/maps/links.json new file mode 100644 index 000000000..22258ff94 --- /dev/null +++ b/concepts/maps/links.json @@ -0,0 +1,10 @@ +[ + { + "url": "https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html", + "description": "Interface Map documentation" + }, + { + "url": "https://dev.java/learn/api/collections-framework/maps/", + "description": "Using Maps to Store Key Value Pairs" + } + ] diff --git a/config.json b/config.json index 86038a6b9..a4f248fc7 100644 --- a/config.json +++ b/config.json @@ -308,6 +308,19 @@ "generic-types" ], "status": "beta" + }, + { + "slug": "international-calling-connoisseur", + "name": "International Calling Connoisseur", + "uuid": "03506c5a-601a-42cd-b037-c310208de84d", + "concepts": [ + "maps" + ], + "prerequisites": [ + "classes", + "foreach-loops", + "generic-types" + ] } ], "practice": [ @@ -989,7 +1002,8 @@ "practices": [], "prerequisites": [ "if-else-statements", - "for-loops" + "for-loops", + "maps" ], "difficulty": 5 }, @@ -1092,7 +1106,8 @@ "practices": [], "prerequisites": [ "for-loops", - "arrays" + "arrays", + "maps" ], "difficulty": 5 }, @@ -1144,7 +1159,8 @@ "practices": [], "prerequisites": [ "chars", - "exceptions" + "exceptions", + "maps" ], "difficulty": 6 }, @@ -1205,6 +1221,7 @@ "practices": [], "prerequisites": [ "foreach-loops", + "maps", "strings" ], "difficulty": 6 @@ -1272,6 +1289,7 @@ "uuid": "38a405e8-619d-400f-b53c-2f06461fdf9d", "practices": [], "prerequisites": [ + "maps", "strings" ], "difficulty": 6 @@ -1447,7 +1465,8 @@ "uuid": "2e760ae2-fadd-4d31-9639-c4554e2826e9", "practices": [], "prerequisites": [ - "enums" + "enums", + "maps" ], "difficulty": 7 }, @@ -1495,7 +1514,8 @@ "chars", "if-else-statements", "lists", - "for-loops" + "for-loops", + "maps" ], "difficulty": 7 }, @@ -1556,7 +1576,8 @@ "prerequisites": [ "arrays", "strings", - "if-else-statements" + "if-else-statements", + "maps" ], "difficulty": 7 }, @@ -1703,6 +1724,7 @@ "exceptions", "for-loops", "if-else-statements", + "maps", "numbers" ], "difficulty": 8 @@ -1905,6 +1927,11 @@ "slug": "lists", "name": "Lists" }, + { + "uuid": "2f6fdedb-a0ac-4bab-92d6-3be61520b9bc", + "slug": "maps", + "name": "Maps" + }, { "uuid": "54118389-9c01-431b-a850-f47da498f845", "slug": "method-overloading", diff --git a/exercises/concept/international-calling-connoisseur/.docs/hints.md b/exercises/concept/international-calling-connoisseur/.docs/hints.md new file mode 100644 index 000000000..056edd53d --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/.docs/hints.md @@ -0,0 +1,39 @@ +# Hints + +## General + +- The [`Map` API documentation][map-docs] contains a list of methods available on the `Map` interface. + +## 1. Return the codes in a map + +- You will need to define a `Map` in [such a way][declaring-members] that you can use it in the class methods. + +## 2. Add entries to the dictionary + +- Maps have a [method][map-put-docs] to add and update the value for a key. + +## 3. Lookup a dialing code's country + +- Maps have a [method][map-get-docs] to get the key's value. + +## 4. Don't allow duplicates + +- There is a way to check if the map has a [key][map-contains-key-docs] or a [value][map-contains-value-docs]. + +## 5. Find a country's dialing code + +- There is a [way][map-values-docs] to get an iterable collection of values in a map. + +## 6. Update the country's dialing code + +- Do not forget about the country's previous dialing code will be in the map. +- There is a [method][map-remove-docs] to remove an entry from the map. + +[declaring-members]: https://dev.java/learn/classes-objects/creating-classes/#declaring-members +[map-docs]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html +[map-put-docs]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#put(K,V) +[map-get-docs]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#get(java.lang.Object) +[map-contains-key-docs]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#containsKey(java.lang.Object) +[map-contains-value-docs]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#containsValue(java.lang.Object) +[map-values-docs]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#values() +[map-remove-docs]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#remove(java.lang.Object) diff --git a/exercises/concept/international-calling-connoisseur/.docs/instructions.md b/exercises/concept/international-calling-connoisseur/.docs/instructions.md new file mode 100644 index 000000000..dc3934e28 --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/.docs/instructions.md @@ -0,0 +1,95 @@ +# Instructions + +In this exercise you'll be writing code to manage a dictionary of international dialing codes using a `Map`. + +The dictionary allows looking up the name of a country (the map's value, as a `String`) by the international dialing code (the map's key, as an `Integer`), + +## 1. Return the codes in a map + +Implement the method `getCodes` that takes no parameters and returns a map of the dialing codes to country currently in the dictionary. + +```java +DialingCodes dialingCodes = new DialingCodes(); +dialingCodes.getCodes(); +// => empty map +``` + +## 2. Add entries to the dictionary + +The dictionary needs to be populated. +Implement the `setDialingCode` method that takes a dialing code and the corresponding country and adds the dialing code and country. +If the dialing code is already in the map, update the map with the provided code and country. + +```java +DialingCodes dialingCodes = new DialingCodes(); +dialingCodes.setDialingCode(679, "Unknown"); +// => { 679 => "Unknown" } + +dialingCodes.setDialingCode(679, "Fiji"); +// => { 679 => "Fiji" } +``` + +## 3. Lookup a dialing code's country + +Implement the `getCountry` method that takes a map of dialing codes and a dialing code and returns the country name with the dialing code. + +```java +DialingCodes dialingCodes = new DialingCodes(); +dialingCodes.setDialingCode(55, "Brazil"); +dialingCodes.getCountry(55); +// => "Brazil" +``` + +## 4. Don't allow duplicates + +When adding a dialing code, care needs to be taken to prevent a code or country to be added twice. +In situations where this happens, it can be assumed that the first entry is the right entry. +Implement the `addNewDialingCode` method that adds an entry for the given dialing code and country. +However, unlike `setDialingCode`, it does nothing if the dialing code or the country is already in the map. + +```java +DialingCodes dialingCodes = new DialingCodes(); +dialingCodes.addNewDialingCode(32, "Belgium"); +dialingCodes.addNewDialingCode(379, "Vatican City"); +// => { 39 => "Italy", 379 => "Vatican City" } + + +dialingCodes.addNewDialingCode(32, "Other"); +dialingCodes.addNewDialingCode(39, "Vatican City"); +// => { 32 => "Belgium", 379 => "Vatican City" } +``` + +## 5. Find a country's dialing code + +Its rare, but mistakes can be made. +To correct the mistake, we will need to know what dialing code the country is currently mapped to. +To find which dialing code needs to be corrected, implement the `findDialingCode` method that takes in a map of dialing codes an a country and returns the country's dialing code. +Return `null` if the country is _not_ in the map. + +```java +DialingCodes dialingCodes = new DialingCodes(); +dialingCodes.addDialingCode(43, "UK"); +dialingCodes.findDialingCode("UK"); +// => 44 + +dialingCodes.findDialingCode("Unlisted"); +// => null +``` + +## 6. Update the country's dialing code + +Now that we know which dialing code needs to be corrected, we proceed to update the code. +Implement the `updateCountryDialingCode` method that takes the country's new dialing code and the country's name and updates accordingly. +Do nothing if the country is _not_ in the map (as this method is meant to only help correct mistakes). + +```java +DialingCodes dialingCodes = new DialingCodes(); +dialingCodes.addDialingCode(88, "Japan"); +// => { 88 => "Japan" } + +dialingCodes.updateCountryDialingCode(81, "Japan"); +// => { 81 => "Japan" } + +dialingCodes.updateCountryDialingCode(32, "Mars"); +// => { 81 => "Japan"} +``` diff --git a/exercises/concept/international-calling-connoisseur/.docs/introduction.md b/exercises/concept/international-calling-connoisseur/.docs/introduction.md new file mode 100644 index 000000000..a9d963a1a --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/.docs/introduction.md @@ -0,0 +1,72 @@ +# Introduction + +## Maps + +A **Map** is a data structure for storing key value pairs. +It is similar to dictionaries in other programming languages. +The [Map][map-javadoc] interface defines operations on a map. + +Java has a number of different Map implementations. +[HashMap][hashmap-javadoc] is a commonly used one. + +```java +// Make an instance +Map fruitPrices = new HashMap<>(); +``` + +Add entries to the map using [put][map-put-javadoc]. + +```java +fruitPrices.put("apple", 100); +fruitPrices.put("pear", 80); +// => { "apple" => 100, "pear" => 80 } +``` + +Only one value can be associated with each key. +Calling `put` with the same key will update the key's value. + +```java +fruitPrices.put("pear", 40); +// => { "apple" => 100, "pear" => 40 } +``` + +Use [get][map-get-javadoc] to get the value for a key. + +```java +fruitPrices.get("apple"); // => 100 +``` + +Use [containsKey][map-containskey-javadoc] to see if the map contains a particular key. + +```java +fruitPrices.containsKey("apple"); // => true +fruitPrices.containsKey("orange"); // => false +``` + +Remove entries with [remove][map-remove-javadoc]. + +```java +fruitPrices.put("plum", 90); // Add plum to map +fruitPrices.remove("plum"); // Removes plum from map +``` + +The [size][map-size-javadoc] method returns the number of entries. + +```java +fruitPrices.size(); // Returns 2 +``` + +You can use the [keys] or [values] methods to obtain the keys or the values in a Map as a Set or collection respectively.studentScores + +```java +fruitPrices.keys(); // Returns "apple" and "pear" in a set +fruitPrices.values(); // Returns 100 and 80, in a Collection +``` + +[map-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html +[hashmap-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/HashMap.html +[map-put-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#put(K,V) +[map-get-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#get(java.lang.Object) +[map-containskey-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#containsKey(java.lang.Object) +[map-remove-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#remove(java.lang.Object) +[map-size-javadoc]: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Map.html#size() diff --git a/exercises/concept/international-calling-connoisseur/.docs/introduction.md.tpl b/exercises/concept/international-calling-connoisseur/.docs/introduction.md.tpl new file mode 100644 index 000000000..f1ea541d1 --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:maps} diff --git a/exercises/concept/international-calling-connoisseur/.meta/config.json b/exercises/concept/international-calling-connoisseur/.meta/config.json new file mode 100644 index 000000000..45d387012 --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/.meta/config.json @@ -0,0 +1,17 @@ +{ + "authors": [ + "kahgoh" + ], + "files": { + "solution": [ + "src/main/java/DialingCodes.java" + ], + "test": [ + "src/test/java/DialingCodesTest.java" + ], + "exemplar": [ + ".meta/src/reference/java/DialingCodes.java" + ] + }, + "blurb": "Learn about maps while managing international calling codes." +} diff --git a/exercises/concept/international-calling-connoisseur/.meta/design.md b/exercises/concept/international-calling-connoisseur/.meta/design.md new file mode 100644 index 000000000..a173c4900 --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/.meta/design.md @@ -0,0 +1,38 @@ +# Design + +## Learning objectives + +- Know about the `Map` interface. +- Know about `HashMap`. +- Know how to put, remove and retrieve items from a `Map`. +- Know how to find the keys of the map. + +## Out of scope + +- Map equality. +- The importance of the key object's `hashCode` and `equals` implementation and how `HashMap` uses them. +- More advanced or specific types of `Map`, such as `WeakHashMap` or `TreeMap`. +- Handling concurrency. + +## Concepts + +- `map` + +## Prerequisites + +This exercise's prerequisites Concepts are: + +- `classes` +- `foreach-loops` +- `generic-types` + +## Analyzer + +This exercise could benefit from the following rules in the [analyzer]: + +- `actionable`: If the user directly returns the class field, recommend returning a copy to the student. + +If the solution does not receive any of the above feedback, it must be exemplar. +Leave a `celebratory` comment to celebrate the success! + +[analyzer]: https://github.com/exercism/java-analyzer diff --git a/exercises/concept/international-calling-connoisseur/.meta/src/reference/java/DialingCodes.java b/exercises/concept/international-calling-connoisseur/.meta/src/reference/java/DialingCodes.java new file mode 100644 index 000000000..d3ecb0a36 --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/.meta/src/reference/java/DialingCodes.java @@ -0,0 +1,43 @@ +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +public class DialingCodes { + + private final Map countryByDialingCode = new HashMap<>(); + + public Map getCodes() { + return Map.copyOf(countryByDialingCode); + } + + public void setDialingCode(Integer code, String country) { + countryByDialingCode.put(code, country); + } + + public String getCountry(Integer code) { + return countryByDialingCode.get(code); + } + + public void addNewDialingCode(Integer code, String country) { + if (!countryByDialingCode.containsValue(country)) { + countryByDialingCode.putIfAbsent(code, country); + } + } + + public Integer findDialingCode(String country) { + for (Map.Entry entry : countryByDialingCode.entrySet()) { + if (Objects.equals(entry.getValue(), country)) { + return entry.getKey(); + } + } + return null; + } + + public void updateCountryDialingCode(Integer code, String country) { + Integer existingCode = findDialingCode(country); + if (existingCode != null) { + countryByDialingCode.remove(existingCode); + countryByDialingCode.put(code, country); + } + } +} diff --git a/exercises/concept/international-calling-connoisseur/build.gradle b/exercises/concept/international-calling-connoisseur/build.gradle new file mode 100644 index 000000000..d28f35dee --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/build.gradle @@ -0,0 +1,25 @@ +plugins { + id "java" +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation platform("org.junit:junit-bom:5.10.0") + testImplementation "org.junit.jupiter:junit-jupiter" + testImplementation "org.assertj:assertj-core:3.25.1" + + testRuntimeOnly "org.junit.platform:junit-platform-launcher" +} + +test { + useJUnitPlatform() + + testLogging { + exceptionFormat = "full" + showStandardStreams = true + events = ["passed", "failed", "skipped"] + } +} diff --git a/exercises/concept/international-calling-connoisseur/gradle/wrapper/gradle-wrapper.jar b/exercises/concept/international-calling-connoisseur/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e6441136f Binary files /dev/null and b/exercises/concept/international-calling-connoisseur/gradle/wrapper/gradle-wrapper.jar differ diff --git a/exercises/concept/international-calling-connoisseur/gradle/wrapper/gradle-wrapper.properties b/exercises/concept/international-calling-connoisseur/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..2deab89d5 --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/exercises/concept/international-calling-connoisseur/gradlew b/exercises/concept/international-calling-connoisseur/gradlew new file mode 100755 index 000000000..1aa94a426 --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/exercises/concept/international-calling-connoisseur/gradlew.bat b/exercises/concept/international-calling-connoisseur/gradlew.bat new file mode 100644 index 000000000..25da30dbd --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/exercises/concept/international-calling-connoisseur/src/main/java/DialingCodes.java b/exercises/concept/international-calling-connoisseur/src/main/java/DialingCodes.java new file mode 100644 index 000000000..0c40e1835 --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/src/main/java/DialingCodes.java @@ -0,0 +1,34 @@ +import java.util.Map; + +public class DialingCodes { + + public Map getCodes() { + throw new UnsupportedOperationException( + "Delete this statement and write your own implementation."); + } + + public void setDialingCode(Integer code, String country) { + throw new UnsupportedOperationException( + "Delete this statement and write your own implementation."); + } + + public String getCountry(Integer code) { + throw new UnsupportedOperationException( + "Delete this statement and write your own implementation."); + } + + public void addNewDialingCode(Integer code, String country) { + throw new UnsupportedOperationException( + "Delete this statement and write your own implementation."); + } + + public Integer findDialingCode(String country) { + throw new UnsupportedOperationException( + "Delete this statement and write your own implementation."); + } + + public void updateCountryDialingCode(Integer code, String country) { + throw new UnsupportedOperationException( + "Delete this statement and write your own implementation."); + } +} diff --git a/exercises/concept/international-calling-connoisseur/src/test/java/DialingCodesTest.java b/exercises/concept/international-calling-connoisseur/src/test/java/DialingCodesTest.java new file mode 100644 index 000000000..4d9727a3a --- /dev/null +++ b/exercises/concept/international-calling-connoisseur/src/test/java/DialingCodesTest.java @@ -0,0 +1,139 @@ +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +public class DialingCodesTest { + + @Test + @Tag("task:1") + @DisplayName("getCodes initially returns an empty map") + public void testGetCodesReturnsMap() { + DialingCodes dialingCodes = new DialingCodes(); + + assertThat(dialingCodes.getCodes()).isEmpty(); + } + + @Test + @Tag("task:2") + @DisplayName("setDialingCode adds new entry") + public void testSetDialingCodeAddsEntry() { + DialingCodes dialingCodes = new DialingCodes(); + dialingCodes.setDialingCode(679, "Fiji"); + + assertThat(dialingCodes.getCodes()).containsOnly(entry(679, "Fiji")); + } + + @Test + @Tag("task:2") + @DisplayName("setDialingCode updates existing entry") + public void testSetDialingCodeUpdatesEntry() { + DialingCodes dialingCodes = new DialingCodes(); + dialingCodes.setDialingCode(679, "Unknown"); + dialingCodes.setDialingCode(679, "Fiji"); + + assertThat(dialingCodes.getCodes()).containsOnly(entry(679, "Fiji")); + } + + @Test + @Tag("task:2") + @DisplayName("setDialingCode with multiple entries") + public void testSetDialingCodeWithMultipleEntries() { + DialingCodes dialingCodes = new DialingCodes(); + dialingCodes.setDialingCode(60, "Malaysia"); + dialingCodes.setDialingCode(233, "Retrieving..."); + dialingCodes.setDialingCode(56, "Chile"); + dialingCodes.setDialingCode(233, "Ghana"); + + assertThat(dialingCodes.getCodes()).containsOnly(entry(60, "Malaysia"), entry(233, "Ghana"), + entry(56, "Chile")); + } + + @Test + @Tag("task:3") + @DisplayName("getCountry returns a code's country") + public void testGetCountryForCode() { + DialingCodes dialingCodes = new DialingCodes(); + dialingCodes.setDialingCode(55, "Brazil"); + + assertThat(dialingCodes.getCountry(55)).isEqualTo("Brazil"); + } + + @Test + @Tag("task:3") + @DisplayName("getCountry returns updated country") + public void testGetCountryForUpdatedCode() { + DialingCodes dialingCodes = new DialingCodes(); + dialingCodes.setDialingCode(962, "Retrieving..."); + dialingCodes.setDialingCode(962, "Jordan"); + + assertThat(dialingCodes.getCountry(962)).isEqualTo("Jordan"); + } + + @Test + @Tag("task:4") + @DisplayName("addNewDialingCode adds new codes") + public void testAddNewDialingCodeAddsNewCodes() { + DialingCodes dialingCodes = new DialingCodes(); + dialingCodes.addNewDialingCode(32, "Belgium"); + dialingCodes.addNewDialingCode(379, "Vatican City"); + + assertThat(dialingCodes.getCodes()).containsOnly(entry(32, "Belgium"), + entry(379, "Vatican City")); + } + + @Test + @Tag("task:4") + @DisplayName("addNewDialingCode leaves already added code") + public void testAddNewDialingCodeLeavesExistingCode() { + DialingCodes dialingCodes = new DialingCodes(); + dialingCodes.addNewDialingCode(32, "Belgium"); + dialingCodes.addNewDialingCode(379, "Vatican City"); + dialingCodes.addNewDialingCode(32, "Other"); + + assertThat(dialingCodes.getCodes()).containsOnly(entry(32, "Belgium"), + entry(379, "Vatican City")); + } + + @Test + @Tag("task:4") + @DisplayName("addNewDialingCode leaves already added country") + public void testAddNewDialingCodeLeavesExistingCountry() { + DialingCodes dialingCodes = new DialingCodes(); + dialingCodes.addNewDialingCode(61, "Australia"); + dialingCodes.addNewDialingCode(1000, "Australia"); + + assertThat(dialingCodes.getCodes()).containsOnly(entry(61, "Australia")); + } + + @Test + @Tag("task:5") + @DisplayName("findDialingCode returns a country's dialing code") + public void testFindDialingCode() { + DialingCodes dialingCodes = new DialingCodes(); + dialingCodes.addNewDialingCode(43, "UK"); + + assertThat(dialingCodes.findDialingCode("UK")).isEqualTo(43); + } + + @Test + @Tag("task:5") + @DisplayName("findDialingCode returns null for country not yet added") + public void testFindDialingCodeWithUnlistedCountry() { + DialingCodes dialingCodes = new DialingCodes(); + dialingCodes.addNewDialingCode(43, "UK"); + + assertThat(dialingCodes.findDialingCode("Unlisted")).isNull(); + } + + @Test + @Tag("task:6") + @DisplayName("updateDialingCode updates the map") + public void testUpdateDialingCode() { + DialingCodes dialingCodes = new DialingCodes(); + dialingCodes.addNewDialingCode(88, "Japan"); + dialingCodes.updateCountryDialingCode(81, "Japan"); + } +} diff --git a/exercises/settings.gradle b/exercises/settings.gradle index a6686a473..470f7aba7 100644 --- a/exercises/settings.gradle +++ b/exercises/settings.gradle @@ -11,6 +11,7 @@ include 'concept:cars-assemble' include 'concept:elons-toy-car' include 'concept:football-match-reports' include 'concept:gotta-snatch-em-all' +include 'concept:international-calling-connoisseur' include 'concept:karls-languages' include 'concept:lasagna' include 'concept:log-levels'