diff --git a/concepts/maps/.meta/config.json b/concepts/maps/.meta/config.json new file mode 100644 index 000000000..7818701c2 --- /dev/null +++ b/concepts/maps/.meta/config.json @@ -0,0 +1,7 @@ +{ + "blurb": "Maps are a data structure that holds key-value pairs. Keys and values can be of any reference data type, and the keys must be unique.", + "authors": [ + "smcg468" + ], + "contributors": [] +} diff --git a/concepts/maps/about.md b/concepts/maps/about.md new file mode 100644 index 000000000..f2078c807 --- /dev/null +++ b/concepts/maps/about.md @@ -0,0 +1,78 @@ +# About + +[Maps][maps] in Java is an interface that holds data in key-value pairs. + +- Keys can be of any [reference type][reference-data-types], but must be unique. +- Values can be of any reference type, they do not have to be unique. + +We have three different views that can all be accessed individually + +- keys, + +```java +Map map = new HashMap<>(); + +// Generates a set view of the keys in the hashmap +map.keySet(); +``` + +- values + +```java +Map map = new HashMap<>(); + +// Generates a set view of the values in the hashmap +map.values(); +``` + +- and key-value mappings. + +````java +Map map = new HashMap<>(); + +for (String key: map.keySet()) { + System.out.println("Key = " + key); + System.out.println("Value = " + map.get(key)); +} +```` + +## Map declaration + +Due to Map being an interface, it is recommended we create an object of a class that implements the map interface as shown in the example below that is creating an object of the HashMap class. +There are many useful [built-in functions][start-of-map-functions] that allow you to modify these map objects. + +```java +Map hashmap = new HashMap<>(); +``` + +In regards to the declaration of the HashMap object, the first data type specified `String` represents the data type of the key, and `Integer` represents the data type of the value in the example above. + +## Classes that implement Map + +We then have the main three classes that are used which implement the Map interface, these are [HashMap][hash-map], [LinkedHashMap][linked-hash-map] and [TreeMap][tree-map]. +Below are some key differences in the three classes. + +### Hashmap + +- Implements the Map interface. +- No guaranteed order of the elements inserted. +- Null values are allowed. + +### LinkedHashMap + +- Implements the Map interface. +- Elements are in the order that they have been inserted. +- Null values are allowed. + +### Treemap + +- Implements the Map, SortedMap and NavigableMap interfaces. +- Elements are sorted according to the natural ordering, keys will be compared using the compareTo() method by default or keys can be compared using another comparator if specified. +- Null values are **not** allowed. + +[maps]: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html +[reference-data-types]: https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.3 +[hash-map]: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html +[linked-hash-map]: https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html +[tree-map]: https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html +[start-of-map-functions]: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#size-- diff --git a/concepts/maps/introduction.md b/concepts/maps/introduction.md new file mode 100644 index 000000000..9fcb21ecd --- /dev/null +++ b/concepts/maps/introduction.md @@ -0,0 +1,44 @@ +# Introduction + +[Maps][maps] in Java is an interface that holds data in key-value pairs. + +- Keys can be of any [reference type][reference-data-types], but must be unique. +- Values can be of any reference type, they do not have to be unique. + +## Map declaration + +Due to Map being an interface, it is recommended we create an object of a class that implements the map interface as shown in the example below that is creating an object of the HashMap class. +There are many useful [built-in functions][start-of-map-functions] that allow you to modify these map objects. + +```java +Map hashmap = new HashMap<>(); +``` + +In regards to the declaration of the HashMap object, the first data type specified `String` represents the data type of the key, and `Integer` represents the data type of the value in the example above. + +## Adding values to a Map + +The [put][put] method is what is used to add a value to a map. The first argument passed will be the key which must be unique +and the second argument will be the value. Both the key and value can be of any data type + +```java +Map hashmap = new HashMap<>(); + +hashmap.put(String key, Integer value) +``` + +## Retrieving values from a Map + +The [get][get] method is used to retrieve values from a map. Only one argument is passed to this method which is the key of the map entry you want to retrieve. + +```java +Map hashmap = new HashMap<>(); + +hashmap.get(String key) +``` + +[maps]: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html +[reference-data-types]: https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.3 +[start-of-map-functions]: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#size-- +[put]: google +[get]: google diff --git a/concepts/maps/links.json b/concepts/maps/links.json new file mode 100644 index 000000000..c8b4c8403 --- /dev/null +++ b/concepts/maps/links.json @@ -0,0 +1,26 @@ +[ + { + "url": "https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html", + "description": "Detailed explanation of the map interface in Java." + }, + { + "url": "https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.3", + "description": "Reference types defined in Java, reference types are the data types used for the key/value pairs." + }, + { + "url": "https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html", + "description": "Detailed explanation of the HashMap class in Java." + }, + { + "url": "https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html", + "description": "Detailed explanation of the LinkedHashMap class in Java." + }, + { + "url": "https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html", + "description": "Detailed explanation of the TreeMap class in Java." + }, + { + "url": "https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#size--", + "description": "List of the built-in functions that can be utilised with map objects." + } +] \ No newline at end of file diff --git a/config.json b/config.json index 0b281151c..f53a6806b 100644 --- a/config.json +++ b/config.json @@ -308,6 +308,18 @@ "generic-types" ], "status": "beta" + }, + { + "slug": "arcade-high-score", + "name": "Arcade High Score", + "uuid": "07893a1a-eb93-4ad2-b98e-f3946c5e7fb2", + "concepts": [ + "maps" + ], + "prerequisites": [ + "numbers", + "strings" + ] } ], "practice": [ @@ -1455,7 +1467,9 @@ "slug": "poker", "name": "Poker", "uuid": "57eeac00-741c-4843-907a-51f0ac5ea4cb", - "practices": [], + "practices": [ + "maps" + ], "prerequisites": [ "constructors", "if-else-statements", @@ -1473,7 +1487,8 @@ "chars", "if-else-statements", "lists", - "for-loops" + "for-loops", + "maps" ], "difficulty": 7 }, @@ -1922,55 +1937,60 @@ "uuid": "78f3c7b2-cb9c-4d21-8cb4-7106a188f713", "slug": "ternary-operators", "name": "Ternary Operators" - } - ], - "key_features": [ - { - "title": "Modern", - "content": "Java is a modern, fast-evolving language with releases every 6 months.", - "icon": "evolving" - }, - { - "title": "Statically-typed", - "content": "Every expression has a type known at compile time.", - "icon": "statically-typed" - }, - { - "title": "Multi-paradigm", - "content": "Java is primarily an object-oriented language, but has many functional features introduced in v1.8.", - "icon": "multi-paradigm" - }, - { - "title": "General purpose", - "content": "Java is used for a variety of workloads like web, cloud, mobile and game applications.", - "icon": "general-purpose" }, { - "title": "Portable", - "content": "Java was designed to be cross-platform with the slogan \"Write once, run anywhere\".", - "icon": "portable" - }, - { - "title": "Garbage Collection", - "content": "Java programs perform automatic memory management for their lifecycles.", - "icon": "garbage-collected" + "uuid": "5a10c26d-1f8a-46d3-ab85-686235000f0e", + "slug": "maps", + "name": "Maps" } ], - "tags": [ - "execution_mode/compiled", - "paradigm/functional", - "paradigm/imperative", - "paradigm/object_oriented", - "platform/android", - "platform/linux", - "platform/mac", - "platform/windows", - "runtime/jvm", - "typing/static", - "used_for/artificial_intelligence", - "used_for/backends", - "used_for/cross_platform_development", - "used_for/games", - "used_for/mobile" - ] -} + "key_features": [ + { + "title": "Modern", + "content": "Java is a modern, fast-evolving language with releases every 6 months.", + "icon": "evolving" + }, + { + "title": "Statically-typed", + "content": "Every expression has a type known at compile time.", + "icon": "statically-typed" + }, + { + "title": "Multi-paradigm", + "content": "Java is primarily an object-oriented language, but has many functional features introduced in v1.8.", + "icon": "multi-paradigm" + }, + { + "title": "General purpose", + "content": "Java is used for a variety of workloads like web, cloud, mobile and game applications.", + "icon": "general-purpose" + }, + { + "title": "Portable", + "content": "Java was designed to be cross-platform with the slogan \"Write once, run anywhere\".", + "icon": "portable" + }, + { + "title": "Garbage Collection", + "content": "Java programs perform automatic memory management for their lifecycles.", + "icon": "garbage-collected" + } + ], + "tags": [ + "execution_mode/compiled", + "paradigm/functional", + "paradigm/imperative", + "paradigm/object_oriented", + "platform/android", + "platform/linux", + "platform/mac", + "platform/windows", + "runtime/jvm", + "typing/static", + "used_for/artificial_intelligence", + "used_for/backends", + "used_for/cross_platform_development", + "used_for/games", + "used_for/mobile" + ] + } diff --git a/exercises/concept/arcade-high-score/.docs/hints.md b/exercises/concept/arcade-high-score/.docs/hints.md new file mode 100644 index 000000000..45f35668f --- /dev/null +++ b/exercises/concept/arcade-high-score/.docs/hints.md @@ -0,0 +1,41 @@ +# Hints + +## General + +- A [map][maps] is an associative data structure of key-value pairs. + +## 1. Get all Highscores + +- It should return a [map][maps] with all the players and their scores. +- [Create an object][create-object] of the HashMap class using the declared `Map highScores` to initialise the map. + +## 2. Add players to the high score map + +- The resulting map should be returned. +- One of the [built-in functions][map-put] can be used to put a value in a map under a given key. + +## 3. Remove players from the score map + +- The resulting map should be returned. +- One of the [built-in functions][map-remove] can be used to remove a key/value pair from a map. + +## 4. Reset a player's score + +- The resulting map should be returned with the player's score reset to an initial value of 0. +- One of the [built-in functions][map-put] can be used to put a value in a map under a given key. + +## 5. Update a player's score + +- The resulting map should be returned with the player's updated score. +- One of the [built-in functions][map-get-or-default] can be used to get a value in a map under a given key if the key is present and update the value, or add the key with a default value if it is not present.. + +## 6. Get all players + +- One of the [built-in functions][map-keys] returns a set of all keys in a map. + +[maps]: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html +[create-object]: https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html +[map-put]: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#put-K-V- +[map-remove]: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#remove-java.lang.Object- +[map-get-or-default]: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#getOrDefault-java.lang.Object-V- +[map-keys]: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#keySet-- diff --git a/exercises/concept/arcade-high-score/.docs/instructions.md b/exercises/concept/arcade-high-score/.docs/instructions.md new file mode 100644 index 000000000..6f4514ffe --- /dev/null +++ b/exercises/concept/arcade-high-score/.docs/instructions.md @@ -0,0 +1,82 @@ +# Instructions + +In this exercise, you're implementing a way to keep track of the high scores for the most popular game in your local arcade hall. + +## 1. Define a new high score map + +To make a new high score map, create an empty `HashMap` object by initialising the `Map highScores` declaration provided. + +```java +ArcadeHighScore arcadeHighScore = new ArcadeHighScore(); +arcadeHighScore.getHighScores(); +// => {} +``` + +## 2. Add players to the high score map + +To add a player to the high score map, implement the `ArcadeHighScore.addPlayer()` method, which takes the player's name and score as arguments. + +When called, it should store the player and their score in the `highScores` map. + +````java +arcadeHighScore.addPlayer("Dave Thomas", 0); +arcadeHighScore.getHighScores(); +// => {Dave Thomas=0} +```` + +## 3. Remove players from the score map + +To remove a player from the high score map, implement the `ArcadeHighScore.removePlayer()` method, which takes the player's name as an argument. + +When called, it should remove the entry associated to the player from the `highScores` map. + +````java +arcadeHighScore.removePlayer("Dave Thomas"); +arcadeHighScore.getHighScores(); +// => {} +```` + +## 4. Reset a player's score + +To reset a player's score, implement the `ArcadeHighScore.resetScore()` method, which takes the player's name as an argument. + +When called, it should reset the score of the player to `0` in the `highScores` map. + +```java +arcadeHighScore.resetScore("Dave Thomas"); +arcadeHighScore.getHighScores(); +// => (Dave Thomas=0); +``` + +## 5. Update a player's score + +To update a player's score by adding to the previous score, implement `ArcadeHighScore.updateScore()` method, which takes the player's name and their new score as arguments. + +When called, it should _add_ the new score to the player's previous score stored in the `highScores` map. + +If the player doesn't have a previous score, assume the previous score is `0`. + +```java +ArcadeHighScore arcadeHighScore = new ArcadeHighScore(); +// Adding a players score to update +arcadeHighScore.addPlayer("Lionel Messi", 48); +arcadeHighScore.updateScore("Lionel Messi", 40); +arcadeHighScore.getHighScores(); +// => {Lionel Messi=88} + +// Updating a players score who doesn't have a previous score +arcadeHighScore.updateScore("Dave Thomas", 57); +arcadeHighScore.getHighScores(); +// => {Lionel Messi=88, Dave Thomas=57} +``` + +## 6. Get a list of players + +To get a list of players, implement the `ArcadeHighScore.getPlayers()` method. + +When called, it should return a collection containing all player's names currently stored in the `highScores` map. + +````java +arcadeHighScore.getPlayers(); +// => {Lionel Messi, Dave Thomas} +```` diff --git a/exercises/concept/arcade-high-score/.docs/introduction.md b/exercises/concept/arcade-high-score/.docs/introduction.md new file mode 100644 index 000000000..80347541f --- /dev/null +++ b/exercises/concept/arcade-high-score/.docs/introduction.md @@ -0,0 +1,52 @@ +# Introduction + +[Maps][maps] in Java is an interface that holds data in key-value pairs. + +- Keys can be of any [reference type][reference-data-types], but must be unique. +- Values can be of any reference type, they do not have to be unique. + +We have three different views that can all be accessed individually + +- set of keys, + +```java +Map map = new HashMap<>(); + +// Generates a set view of the keys in the hashmap +map.keySet(); +``` + +- collection of values + +```java +Map map = new HashMap<>(); + +// Generates a set view of the values in the hashmap +map.values(); +``` + +- set of key-value mappings. + +````java +Map map = new HashMap<>(); + +for (String key: map.keySet()) { + System.out.println("Key = " + key); + System.out.println("Value = " + map.get(key)); +} +```` + +## Map declaration + +Due to Map being an interface, it is recommended we create an object of a class that implements the map interface as shown in the example below that is creating an object of the HashMap class. +There are many useful [built-in functions][start-of-map-functions] that allow you to modify these map objects. + +```java +Map hashmap = new HashMap<>(); +``` + +In regard to the declaration of the HashMap object, the first data type specified `String` represents the data type of the key, and `Integer` represents the data type of the value in the example above. + +[maps]: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html +[reference-data-types]: https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.3 +[start-of-map-functions]: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#size-- diff --git a/exercises/concept/arcade-high-score/.docs/introduction.md.tpl b/exercises/concept/arcade-high-score/.docs/introduction.md.tpl new file mode 100644 index 000000000..f1ea541d1 --- /dev/null +++ b/exercises/concept/arcade-high-score/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:maps} diff --git a/exercises/concept/arcade-high-score/.meta/config.json b/exercises/concept/arcade-high-score/.meta/config.json new file mode 100644 index 000000000..8a42a4b7c --- /dev/null +++ b/exercises/concept/arcade-high-score/.meta/config.json @@ -0,0 +1,23 @@ +{ + "authors": [ + "smcg468" + ], + "files": { + "solution": [ + "src/main/java/ArcadeHighScore.java" + ], + "test": [ + "src/test/java/ArcadeHighScoreTest.java" + ], + "exemplar": [ + ".meta/src/reference/java/ArcadeHighScore.java" + ], + "invalidator": [ + "build.gradle" + ] + }, + "forked_from": [ + "elixir/high-score" + ], + "blurb": "Learn about maps by keeping track of the high scores in your local arcade" +} diff --git a/exercises/concept/arcade-high-score/.meta/design.md b/exercises/concept/arcade-high-score/.meta/design.md new file mode 100644 index 000000000..d508d2ee0 --- /dev/null +++ b/exercises/concept/arcade-high-score/.meta/design.md @@ -0,0 +1,24 @@ +# Design + +## Learning objectives + +- Know what a map is. +- Know how to define a map literal. +- Know how to add key/value pairs in a map. +- Know how to get values from a map. +- Know how to get keys from a map. +- Know how to update values in a map. +- Know how to remove items from a map. +- Know what a `HashMap` is. + +## Out of scope + +- Other Implementations of the `Map` Interface + +## Concepts + +- `maps` + +## Prerequisites + +- `numbers`: know how to apply basic mathematical operators. diff --git a/exercises/concept/arcade-high-score/.meta/src/reference/java/ArcadeHighScore.java b/exercises/concept/arcade-high-score/.meta/src/reference/java/ArcadeHighScore.java new file mode 100644 index 000000000..110eacfe4 --- /dev/null +++ b/exercises/concept/arcade-high-score/.meta/src/reference/java/ArcadeHighScore.java @@ -0,0 +1,39 @@ +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class ArcadeHighScore { + + private Map highScores = new HashMap<>(); + + Map getHighScores() { + return highScores; + } + + Map defineMap() { + return highScores; + } + + void addPlayer(String name, Integer score) { + highScores.put(name, score); + } + + void removePlayer (String name) { + highScores.remove(name); + } + + void resetScore (String name) { + highScores.put(name, 0); + } + + void updateScore (String name, Integer score) { + + Integer oldScore = highScores.getOrDefault(name, 0); + + highScores.put(name, oldScore + score); + } + + Set getPlayers () { + return highScores.keySet(); + } +} diff --git a/exercises/concept/arcade-high-score/build.gradle b/exercises/concept/arcade-high-score/build.gradle new file mode 100644 index 000000000..9daa11cb3 --- /dev/null +++ b/exercises/concept/arcade-high-score/build.gradle @@ -0,0 +1,23 @@ +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.15.0" +} + +test { + useJUnitPlatform() + + testLogging { + exceptionFormat = "full" + showStandardStreams = true + events = ["passed", "failed", "skipped"] + } +} diff --git a/exercises/concept/arcade-high-score/gradle/wrapper/gradle-wrapper.jar b/exercises/concept/arcade-high-score/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e6441136f Binary files /dev/null and b/exercises/concept/arcade-high-score/gradle/wrapper/gradle-wrapper.jar differ diff --git a/exercises/concept/arcade-high-score/gradle/wrapper/gradle-wrapper.properties b/exercises/concept/arcade-high-score/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..2deab89d5 --- /dev/null +++ b/exercises/concept/arcade-high-score/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/arcade-high-score/gradlew b/exercises/concept/arcade-high-score/gradlew new file mode 100644 index 000000000..1aa94a426 --- /dev/null +++ b/exercises/concept/arcade-high-score/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/arcade-high-score/gradlew.bat b/exercises/concept/arcade-high-score/gradlew.bat new file mode 100644 index 000000000..25da30dbd --- /dev/null +++ b/exercises/concept/arcade-high-score/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/arcade-high-score/src/main/java/ArcadeHighScore.java b/exercises/concept/arcade-high-score/src/main/java/ArcadeHighScore.java new file mode 100644 index 000000000..9e5e6ded1 --- /dev/null +++ b/exercises/concept/arcade-high-score/src/main/java/ArcadeHighScore.java @@ -0,0 +1,32 @@ +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +class ArcadeHighScore { + + Map highScores = new HashMap<>(); + + Map getHighScores(){ + throw new UnsupportedOperationException("Please initialise the ArcadeHighScore.highScores map"); + } + + Map addPlayer (String name, Integer score) { + throw new UnsupportedOperationException("Please implement the ArcadeHighScore.addPlayer(name, score) method"); + } + + Map removePlayer (String name) { + throw new UnsupportedOperationException("Please implement the ArcadeHighScore.removePlayer(name) method"); + } + + Map resetScore (String name) { + throw new UnsupportedOperationException("Please implement the ArcadeHighScore.resetScore(name) method"); + } + + Map updateScore (String name, Integer score) { + throw new UnsupportedOperationException("Please implement the ArcadeHighScore.updateScore(name, score) method"); + } + + Set getPlayers () { + throw new UnsupportedOperationException("Please implement the ArcadeHighScore.listOfPlayers() method"); + } +} diff --git a/exercises/concept/arcade-high-score/src/test/java/ArcadeHighScoreTest.java b/exercises/concept/arcade-high-score/src/test/java/ArcadeHighScoreTest.java new file mode 100644 index 000000000..77c8a3d16 --- /dev/null +++ b/exercises/concept/arcade-high-score/src/test/java/ArcadeHighScoreTest.java @@ -0,0 +1,109 @@ +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class ArcadeHighScoreTest { + + private ArcadeHighScore arcadeHighScore; + + @BeforeEach + public void setUp() { + arcadeHighScore = new ArcadeHighScore(); + } + + @Test + @Tag("task:1") + @DisplayName("Define an empty map to store the high scores") + public void getHighScores() { + assertNotNull(arcadeHighScore.getHighScores()); + assertThat(arcadeHighScore.highScores.isEmpty()); + } + + @Test + @Tag("task:2") + @DisplayName("Add a player to the high scores map") + public void addPlayer() { + String name = "David James"; + Integer score = 67; + + arcadeHighScore.addPlayer(name, score); + assertThat(arcadeHighScore.highScores).containsEntry(name, score); + } + + @Test + @Tag("task:3") + @DisplayName("Remove a player from the high scores map") + public void removePlayer() { + String name = "David James"; + Integer score = 67; + + arcadeHighScore.addPlayer(name, score); + assertThat(arcadeHighScore.highScores).containsEntry(name, score); + + arcadeHighScore.removePlayer(name); + assertThat(arcadeHighScore.highScores).isEmpty(); + } + + @Test + @Tag("task:4") + @DisplayName("Reset a players score to 0") + public void resetScore() { + String name = "David James"; + Integer score = 67; + + arcadeHighScore.addPlayer(name, score); + assertThat(arcadeHighScore.highScores).containsEntry(name, score); + + arcadeHighScore.resetScore("David James"); + assertThat(arcadeHighScore.highScores).containsEntry(name, 0); + } + + @Test + @Tag("task:5") + @DisplayName("Update a players score") + public void updateScore() { + String name = "David James"; + Integer score = 67; + + arcadeHighScore.addPlayer(name, score); + assertThat(arcadeHighScore.highScores).containsEntry(name, score); + + Integer newScore = 31; + + arcadeHighScore.updateScore(name, newScore); + assertThat(arcadeHighScore.highScores).containsEntry(name, score + newScore); + } + + @Test + @Tag("task:5") + @DisplayName("Update a players score who does not exist") + public void updateScoreOfNonExistentPlayer() { + String name = "David James"; + Integer score = 67; + + assertThat(arcadeHighScore).isNull(); + + arcadeHighScore.updateScore(name, score); + assertThat(arcadeHighScore.highScores).containsEntry(name, score); + } + + @Test + @Tag("task:6") + @DisplayName("Get all players") + public void getPlayers() { + String name = "David James"; + Integer score = 67; + + String secondName = "Lionel Messi"; + Integer secondScore = 87; + + arcadeHighScore.addPlayer(name, score); + arcadeHighScore.addPlayer(secondName, secondScore); + + assertThat(arcadeHighScore.getPlayers()).contains(name).contains(secondName); + } +} diff --git a/exercises/settings.gradle b/exercises/settings.gradle index 916d7dd7f..f974acf33 100644 --- a/exercises/settings.gradle +++ b/exercises/settings.gradle @@ -2,6 +2,7 @@ rootProject.name = 'exercism-java' // concept exercises include 'concept:annalyns-infiltration' +include 'concept:arcade-high-score' include 'concept:bird-watcher' // include 'concept:blackjack' // deprecated include 'concept:booking-up-for-beauty'