diff --git a/concepts/when/.meta/config.json b/concepts/when/.meta/config.json new file mode 100644 index 00000000..3da8d712 --- /dev/null +++ b/concepts/when/.meta/config.json @@ -0,0 +1,7 @@ +{ + "authors": [ + "kahgoh" + ], + "contributors": [], + "blurb": "When is an alternative to long if / else if / else chains." +} diff --git a/concepts/when/about.md b/concepts/when/about.md new file mode 100644 index 00000000..7fab5927 --- /dev/null +++ b/concepts/when/about.md @@ -0,0 +1,147 @@ +# Introduction + +Kotlin's `when` is a conditional expression for choosing among several options. +It is similar to `switch` in Java, and more flexible than a chain of `if` ... `else if` ... `else`. + +Like `if`, `when` can also be used as an expression that produces a value. + +## Matching a value + +Give `when` a value to match in parentheses. +Each branch compares that value until one matches: + +```kotlin +val animal = "chicken" +val type = when (animal) { + "chicken" -> "bird" + "poodle" -> "dog" + else -> "unknown" +} +// type => "bird" +``` + +- Each branch is written as `pattern -> result`. +- Branches are tried from top to bottom until a match is found. + Only the first branch runs. +- Use `else` for any value not listed above (similar to the final `else` in an `if` chain). + +This is similar to [pattern matching][pattern-matching]. +The `pattern` can be a value to match, or use `is` to match by type: + +```kotlin +fun typeText(subject: Any): String { + return when(subject) { + is Animal -> "Animal" + is Fruit -> "Fruit" + is String -> "Text" + else -> "Unknown" + } +} +``` + +or use `in` to check if it is contained in a range, collection, string or anything else with a `contains` method: + +```kotlin +fun describe(number: Int, position: String) { + // Range + when(number) { + in 1..10 -> println("From 1 to 10") + in 11..20 -> println("From 11 to 20") + } + + // Collection + when(number) { + in listOf(2, 4, 6) -> println("small even") + in listOf(3, 5, 7) -> println("small odd") + } + + // String + when(position) { + in "center middle" -> println("inner") + in "left right boundary" -> println("outer") + } +} +``` + +~~~exercism/note +You can also use `in` with other objects by defining the `contains` [operator extension function][kotlin-operator-overloading]. +For example, using it with [Regex][kotlin-regex]: + +```kotlin +operator fun Regex.contains(text: CharSequence): Boolean = this.matches(text) + +fun replace(input: String) { + return when(input) { + in Regex("""ani*""") -> println("animal") + in Regex("""fru.*""") -> println("fruit") + in Regex("""num.*""") -> println("number") + else -> println("unknown") + } +} +``` +~~~ + +## Guard conditions + +When matching a value, additional conditions can be placed in an `if` after the pattern. +These conditions are called guard conditions. + +```kotlin +val x = 5 +val y = 10 +val description = when (x) { + 5 if y % 2 == 0 -> "x is 5, y is even" + else -> "other" +} +// description => "x is 5, y is even" +``` + +Even `else if` can be used. + +```kotlin +val x = 7 +val y = 10 +val description = when (x) { + 5 if y % 2 == 0 -> "x is 5, y is even" + else if y % 2 == 0 -> "y is an even number" + else -> "other" +} +// description => "y is an even number" +``` + + +## Matching conditions + +Alternatively, the value can be omitted and boolean conditions can be placed on each branch: + +```kotlin +val x = 5 +val y = 8 +val description = when { + x % 2 != 0 -> "x is odd" + y % 2 == 0 -> "y is even" + else -> "neither condition matched first" +} +// description => "x is odd" +``` + +Again, branches are checked from top to bottom and only the first branch whose condition is `true` runs. + +## Using `when` as an expression + +When `when` is used for its result (assigned to a variable, returned from a function, and so on), every possible case must be covered. + +- When matching with a value, add `else` unless every possible value is already handled (for example, all values of a `Boolean` or an `enum`). +- When matching conditions, an `else` branch is required, because the compiler cannot know that your conditions cover every case. + +```kotlin +fun label(n: Int): String = when (n) { + 0 -> "zero" + 1 -> "one" + else -> "other" +} +``` + +[kotlin-operator-overloading]: https://kotlinlang.org/docs/operator-overloading.html +[kotlin-regex]: https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/-regex/ +[pattern-matching]: https://en.wikipedia.org/wiki/Pattern_matching \ No newline at end of file diff --git a/concepts/when/introduction.md b/concepts/when/introduction.md new file mode 100644 index 00000000..cd53c1bc --- /dev/null +++ b/concepts/when/introduction.md @@ -0,0 +1,127 @@ +# Introduction + +Kotlin's `when` is a conditional expression for choosing among several options. +It is similar to `switch` in Java, and more flexible than a chain of `if` ... `else if` ... `else`. + +Like `if`, `when` can also be used as an expression that produces a value. + +## Matching a value + +Give `when` a value to match in parentheses. +Each branch compares that value until one matches: + +```kotlin +val animal = "chicken" +val type = when (animal) { + "chicken" -> "bird" + "poodle" -> "dog" + else -> "unknown" +} +// type => "bird" +``` + +- Each branch is written as `pattern -> result`. +- Branches are tried from top to bottom until a match is found. + Only the first branch runs. +- Use `else` for any value not listed above (similar to the final `else` in an `if` chain). + +This is similar to [pattern matching][pattern-matching]. +The `pattern` can be a value to match, or use `is` to match by type: + +```kotlin +fun typeText(subject: Any): String { + return when(subject) { + is Animal -> "Animal" + is Fruit -> "Fruit" + is String -> "Text" + else -> "Unknown" + } +} +``` + +or use `in` to check if it is contained in a range, collection, string or anything else with a `contains` method: + +```kotlin +fun describe(number: Int, position: String) { + // Range + when(number) { + in 1..10 -> println("From 1 to 10") + in 11..20 -> println("From 11 to 20") + } + + // Collection + when(number) { + in listOf(2, 4, 6) -> println("small even") + in listOf(3, 5, 7) -> println("small odd") + } + + // String + when(position) { + in "center middle" -> println("inner") + in "left right boundary" -> println("outer") + } +} +``` + +## Guard conditions + +When matching a value, additional conditions can be placed in an `if` after the pattern. +These conditions are called guard conditions. + +```kotlin +val x = 5 +val y = 10 +val description = when (x) { + 5 if y % 2 == 0 -> "x is 5, y is even" + else -> "other" +} +// description => "x is 5, y is even" +``` + +Even `else if` can be used. + +```kotlin +val x = 7 +val y = 10 +val description = when (x) { + 5 if y % 2 == 0 -> "x is 5, y is even" + else if y % 2 == 0 -> "y is an even number" + else -> "other" +} +// description => "y is an even number" +``` + + +## Matching conditions + +Alternatively, the value can be omitted and boolean conditions can be placed on each branch: + +```kotlin +val x = 5 +val y = 8 +val description = when { + x % 2 != 0 -> "x is odd" + y % 2 == 0 -> "y is even" + else -> "neither condition matched first" +} +// description => "x is odd" +``` + +Again, branches are checked from top to bottom and only the first branch whose condition is `true` runs. + +## Using `when` as an expression + +When `when` is used for its result (assigned to a variable, returned from a function, and so on), every possible case must be covered. + +- When matching with a value, add `else` unless every possible value is already handled (for example, all values of a `Boolean` or an `enum`). +- When matching conditions, an `else` branch is required, because the compiler cannot know that your conditions cover every case. + +```kotlin +fun label(n: Int): String = when (n) { + 0 -> "zero" + 1 -> "one" + else -> "other" +} +``` + +[pattern-matching]: https://en.wikipedia.org/wiki/Pattern_matching \ No newline at end of file diff --git a/concepts/when/links.json b/concepts/when/links.json new file mode 100644 index 00000000..bdd49ba5 --- /dev/null +++ b/concepts/when/links.json @@ -0,0 +1,6 @@ +[ + { + "url": "https://kotlinlang.org/docs/control-flow.html#when-expressions-and-statements", + "description": "Kotlin when expressions and statements" + } +] diff --git a/config.json b/config.json index d2e02ae3..d61eddb1 100644 --- a/config.json +++ b/config.json @@ -58,7 +58,7 @@ }, { "slug": "log-levels", - "name": "log-levels", + "name": "Log Levels", "uuid": "ef54c5e6-7d31-42d1-a300-e405169dbd7f", "concepts": [ "strings" @@ -68,6 +68,18 @@ ], "status": "wip" }, + { + "slug": "guessing-game", + "name": "Guessing Game", + "uuid": "8ef61603-c6c0-4188-8436-9bd194a2850f", + "concepts": [ + "when" + ], + "prerequisites": [ + "conditionals" + ], + "status": "wip" + }, { "slug": "secret-agent", "name": "secret-agent", @@ -1430,26 +1442,26 @@ "slug": "basics", "name": "Basics" }, + { + "uuid": "1050abed-4271-4519-a44c-a0ca121c7de2", + "slug": "bitwise-operations", + "name": "Bitwise Operations" + }, { "uuid": "53e0b729-810e-4042-9477-8c8d05a7b302", "slug": "booleans", "name": "Booleans" }, { - "uuid": "157bbe3b-e4f5-41f7-8e0e-e2f57d526617", - "slug": "strings", - "name": "Strings" + "uuid": "660e1acd-3072-4bbc-ae44-bbc204da5eab", + "slug": "chars", + "name": "Chars" }, { "uuid": "168827c0-4867-449a-ad22-611c87314c48", "slug": "conditionals", "name": "Conditionals" }, - { - "uuid": "660e1acd-3072-4bbc-ae44-bbc204da5eab", - "slug": "chars", - "name": "Chars" - }, { "uuid": "c26a1939-deb9-4df7-85c3-f505cdf89e8c", "slug": "higher-order-functions", @@ -1461,9 +1473,14 @@ "name": "Nullability" }, { - "uuid": "1050abed-4271-4519-a44c-a0ca121c7de2", - "slug": "bitwise-operations", - "name": "Bitwise Operations" + "uuid": "157bbe3b-e4f5-41f7-8e0e-e2f57d526617", + "slug": "strings", + "name": "Strings" + }, + { + "uuid": "86b469a5-c21b-4c8b-98c8-942ca210fe36", + "slug": "when", + "name": "When" } ], "key_features": [ diff --git a/exercises/concept/guessing-game/.docs/hints.md b/exercises/concept/guessing-game/.docs/hints.md new file mode 100644 index 00000000..bfcd6088 --- /dev/null +++ b/exercises/concept/guessing-game/.docs/hints.md @@ -0,0 +1,29 @@ +# Hints + +## General + +## 1. Reply to a correct guess + +- You can match a specific value in a [when][kotlin-when] expression or statement. + +## 2. Reply to a close guess + +- You can match [multiple values][kotlin-when-multiple-values] on a branch. + +## 3. Reply to too low guesses + +- The [when][kotlin-when] expression or statement has a way to match anything else that is not matched by the branches. + +## 4. Reply to too high guesses + +- The [when][kotlin-when] expression or statement has a way to match anything else that is not matched by the branches. +- You may need to adjust one of the branches from a previous task. + +## 5. Reply to a close guess after more than 5 guesses + +- There is a [way][kotlin-when-guard-conditions] to add conditions to branches. +- Remember, the order of the branches is important! + +[kotlin-when]: https://kotlinlang.org/docs/control-flow.html#when-expressions-and-statements +[kotlin-when-multiple-values]: https://kotlinlang.org/docs/control-flow.html#other-ways-to-use-when +[kotlin-when-guard-conditions]: https://kotlinlang.org/docs/control-flow.html#guard-conditions-in-when-expressions diff --git a/exercises/concept/guessing-game/.docs/instructions.md b/exercises/concept/guessing-game/.docs/instructions.md new file mode 100644 index 00000000..03f1d7bd --- /dev/null +++ b/exercises/concept/guessing-game/.docs/instructions.md @@ -0,0 +1,58 @@ +# Instructions + +In this exercise, you are playing a number guessing game with a friend. +The rules are simple: you secretly choose a number between `1` and `100` and your friend tries to guess what number you've chosen. +To help your friend, you respond differently depending on how close the guess was to the number you've chosen (`42`) and how many guesses have been made. +These are the rules for the different replies: + +- If the guess is `42`: "Correct" +- If the guess is `41` or `43` and there have been no more than 5 guesses : "So close" +- If the guess is less than `41`: "Too low" +- If the guess is greater than `43`: "Too high" + +You have four tasks to encode the replies to the guesses. + +## 1. Reply to a correct guess + +Implement the `reply` function to reply to a correct guess: + +```kotlin +reply(42, 1) +// => "Correct" +``` + +## 2. Reply to a close guess + +Modify the `reply` function to reply to close guesses: + +```kotlin +reply(41, 1) +// => "So close" +``` + +## 3. Reply to too low guesses + +Modify the `reply` function to reply to too low guesses: + +```kotlin +reply(25, 1) +// => "Too low" +``` + +## 4. Reply to too high guesses + +Modify the `reply` function to reply to too high guesses: + +```kotlin +reply(88, 1) +// => "Too high" +``` + +## 5. Reply to a close guess after more than 5 guesses + +Modify the `reply` function to reply to close guesses after more than 5 guesses have been made. + +```kotlin +reply(43, 6) +// => "Try one lower" +``` \ No newline at end of file diff --git a/exercises/concept/guessing-game/.docs/introduction.md b/exercises/concept/guessing-game/.docs/introduction.md new file mode 100644 index 00000000..c17df911 --- /dev/null +++ b/exercises/concept/guessing-game/.docs/introduction.md @@ -0,0 +1,129 @@ +# Introduction + +## When + +Kotlin's `when` is a conditional expression for choosing among several options. +It is similar to `switch` in Java, and more flexible than a chain of `if` ... `else if` ... `else`. + +Like `if`, `when` can also be used as an expression that produces a value. + +### Matching a value + +Give `when` a value to match in parentheses. +Each branch compares that value until one matches: + +```kotlin +val animal = "chicken" +val type = when (animal) { + "chicken" -> "bird" + "poodle" -> "dog" + else -> "unknown" +} +// type => "bird" +``` + +- Each branch is written as `pattern -> result`. +- Branches are tried from top to bottom until a match is found. + Only the first branch runs. +- Use `else` for any value not listed above (similar to the final `else` in an `if` chain). + +This is similar to [pattern matching][pattern-matching]. +The `pattern` can be a value to match, or use `is` to match by type: + +```kotlin +fun typeText(subject: Any): String { + return when(subject) { + is Animal -> "Animal" + is Fruit -> "Fruit" + is String -> "Text" + else -> "Unknown" + } +} +``` + +or use `in` to check if it is contained in a range, collection, string or anything else with a `contains` method: + +```kotlin +fun describe(number: Int, position: String) { + // Range + when(number) { + in 1..10 -> println("From 1 to 10") + in 11..20 -> println("From 11 to 20") + } + + // Collection + when(number) { + in listOf(2, 4, 6) -> println("small even") + in listOf(3, 5, 7) -> println("small odd") + } + + // String + when(position) { + in "center middle" -> println("inner") + in "left right boundary" -> println("outer") + } +} +``` + +### Guard conditions + +When matching a value, additional conditions can be placed in an `if` after the pattern. +These conditions are called guard conditions. + +```kotlin +val x = 5 +val y = 10 +val description = when (x) { + 5 if y % 2 == 0 -> "x is 5, y is even" + else -> "other" +} +// description => "x is 5, y is even" +``` + +Even `else if` can be used. + +```kotlin +val x = 7 +val y = 10 +val description = when (x) { + 5 if y % 2 == 0 -> "x is 5, y is even" + else if y % 2 == 0 -> "y is an even number" + else -> "other" +} +// description => "y is an even number" +``` + + +### Matching conditions + +Alternatively, the value can be omitted and boolean conditions can be placed on each branch: + +```kotlin +val x = 5 +val y = 8 +val description = when { + x % 2 != 0 -> "x is odd" + y % 2 == 0 -> "y is even" + else -> "neither condition matched first" +} +// description => "x is odd" +``` + +Again, branches are checked from top to bottom and only the first branch whose condition is `true` runs. + +### Using `when` as an expression + +When `when` is used for its result (assigned to a variable, returned from a function, and so on), every possible case must be covered. + +- When matching with a value, add `else` unless every possible value is already handled (for example, all values of a `Boolean` or an `enum`). +- When matching conditions, an `else` branch is required, because the compiler cannot know that your conditions cover every case. + +```kotlin +fun label(n: Int): String = when (n) { + 0 -> "zero" + 1 -> "one" + else -> "other" +} +``` + +[pattern-matching]: https://en.wikipedia.org/wiki/Pattern_matching diff --git a/exercises/concept/guessing-game/.docs/introduction.md.tpl b/exercises/concept/guessing-game/.docs/introduction.md.tpl new file mode 100644 index 00000000..6a8a2f34 --- /dev/null +++ b/exercises/concept/guessing-game/.docs/introduction.md.tpl @@ -0,0 +1,3 @@ +# Introduction + +%{concept:when} diff --git a/exercises/concept/guessing-game/.meta/config.json b/exercises/concept/guessing-game/.meta/config.json new file mode 100644 index 00000000..18152fde --- /dev/null +++ b/exercises/concept/guessing-game/.meta/config.json @@ -0,0 +1,20 @@ +{ + "authors": [ + "kahgoh" + ], + "files": { + "solution": [ + "src/main/kotlin/GuessingGame.kt" + ], + "test": [ + "src/test/kotlin/GuessingGameTest.kt" + ], + "exemplar": [ + ".meta/src/reference/kotlin/GuessingGame.kt" + ] + }, + "forked_from": [ + "fsharp/guessing-game" + ], + "blurb": "Learn about when expressions by implementing a simple game in which the player needs to guess a secret number" +} diff --git a/exercises/concept/guessing-game/.meta/design.md b/exercises/concept/guessing-game/.meta/design.md new file mode 100644 index 00000000..9d472ecc --- /dev/null +++ b/exercises/concept/guessing-game/.meta/design.md @@ -0,0 +1,15 @@ +# Design + +## Learning objectives + +- Know how to use `when`. +- Know how to use guard conditions + +## Concepts + +- `when` + +## Prerequisites + +- `strings`: strings will be compared to null and basic methods from strings will be called. +- `conditionals`: using a conditional statement. diff --git a/exercises/concept/guessing-game/.meta/src/reference/kotlin/GuessingGame.kt b/exercises/concept/guessing-game/.meta/src/reference/kotlin/GuessingGame.kt new file mode 100644 index 00000000..50e39300 --- /dev/null +++ b/exercises/concept/guessing-game/.meta/src/reference/kotlin/GuessingGame.kt @@ -0,0 +1,10 @@ +fun reply(guess : Int, guessCount : Int) : String { + return when(guess) { + 42 -> "Correct" + 41 if guessCount > 5 -> "Try one higher" + 43 if guessCount > 5 -> "Try one lower" + 41, 43 -> "So close" + else if guess < 41 -> "Too low" + else -> "Too high" + } +} \ No newline at end of file diff --git a/exercises/concept/guessing-game/build.gradle.kts b/exercises/concept/guessing-game/build.gradle.kts new file mode 100644 index 00000000..534c6ca6 --- /dev/null +++ b/exercises/concept/guessing-game/build.gradle.kts @@ -0,0 +1,20 @@ +import org.gradle.api.tasks.testing.logging.TestExceptionFormat + +plugins { + kotlin("jvm") version "2.4.0" +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation(kotlin("test")) +} + +tasks.withType { + testLogging { + exceptionFormat = TestExceptionFormat.FULL + events("passed", "failed", "skipped") + } +} diff --git a/exercises/concept/guessing-game/gradle/wrapper/gradle-wrapper.jar b/exercises/concept/guessing-game/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..b1b8ef56 Binary files /dev/null and b/exercises/concept/guessing-game/gradle/wrapper/gradle-wrapper.jar differ diff --git a/exercises/concept/guessing-game/gradle/wrapper/gradle-wrapper.properties b/exercises/concept/guessing-game/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..83672cc2 --- /dev/null +++ b/exercises/concept/guessing-game/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/exercises/concept/guessing-game/gradlew b/exercises/concept/guessing-game/gradlew new file mode 100755 index 00000000..b9bb139f --- /dev/null +++ b/exercises/concept/guessing-game/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/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 -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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 + + + +# 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" ) + + 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, 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" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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/guessing-game/gradlew.bat b/exercises/concept/guessing-game/gradlew.bat new file mode 100755 index 00000000..aa5f10b0 --- /dev/null +++ b/exercises/concept/guessing-game/gradlew.bat @@ -0,0 +1,82 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +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 + +"%COMSPEC%" /c exit 1 + +: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 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/exercises/concept/guessing-game/settings.gradle.kts b/exercises/concept/guessing-game/settings.gradle.kts new file mode 100644 index 00000000..e69de29b diff --git a/exercises/concept/guessing-game/src/main/kotlin/GuessingGame.kt b/exercises/concept/guessing-game/src/main/kotlin/GuessingGame.kt new file mode 100644 index 00000000..9a75059b --- /dev/null +++ b/exercises/concept/guessing-game/src/main/kotlin/GuessingGame.kt @@ -0,0 +1,3 @@ +fun reply(guess : Int, guessCount : Int) : String { + TODO("Please implement the reply function") +} \ No newline at end of file diff --git a/exercises/concept/guessing-game/src/test/kotlin/GuessingGameTest.kt b/exercises/concept/guessing-game/src/test/kotlin/GuessingGameTest.kt new file mode 100644 index 00000000..09eaf173 --- /dev/null +++ b/exercises/concept/guessing-game/src/test/kotlin/GuessingGameTest.kt @@ -0,0 +1,50 @@ +import kotlin.test.Test +import kotlin.test.assertEquals + +class GuessingGameTest { + @Test + fun `give hint for 42`() { + assertEquals("Correct", reply(42, 1)) + } + + @Test + fun `give hint for 41 on 5th guess`() { + assertEquals("So close", reply(41, 5)) + } + + @Test + fun `give hint for 43 on 5th guess`() { + assertEquals("So close", reply(43, 5)) + } + + @Test + fun `give hint for 40`() { + assertEquals("Too low", reply(40, 1)) + } + + @Test + fun `give hint for 1`() { + assertEquals("Too low", reply(1, 1)) + } + + @Test + fun `give hint for 44`() { + assertEquals("Too high", reply(44, 1)) + } + + @Test + fun `give hint for 100`() { + assertEquals("Too high", reply(100, 1)) + } + + @Test + fun `give hint for 41 on 6th guess`() { + assertEquals("Try one higher", reply(41, 6)) + } + + @Test + fun `give hint for 43 on 6th guess`() { + assertEquals("Try one lower", reply(43, 6)) + } + +} \ No newline at end of file diff --git a/exercises/settings.gradle.kts b/exercises/settings.gradle.kts index 9994cb25..b34a8e6b 100644 --- a/exercises/settings.gradle.kts +++ b/exercises/settings.gradle.kts @@ -1,5 +1,6 @@ include( "concept:annalyns-infiltration", + "concept:guessing-game", "concept:log-levels", "concept:lucians-luscious-lasagna", "concept:secret-agent",