diff --git a/concepts/higher-order-functions/.meta/config.json b/concepts/higher-order-functions/.meta/config.json new file mode 100644 index 00000000..4070de02 --- /dev/null +++ b/concepts/higher-order-functions/.meta/config.json @@ -0,0 +1,7 @@ +{ + "authors": [ + "kahgoh" + ], + "contributors": [], + "blurb": "Functions are first class citizens in Kotlin and can be assigned to variables or passed to other functions." +} diff --git a/concepts/higher-order-functions/about.md b/concepts/higher-order-functions/about.md new file mode 100644 index 00000000..ceaa58a1 --- /dev/null +++ b/concepts/higher-order-functions/about.md @@ -0,0 +1,101 @@ +# About Higher Order Functions + +Functions in Kotlin are first class citizens. +This means they can be stored in variables, passed as arguments and even returned by other functions. +For example, assigning a function to the variable `addOne`: + +```kotlin +val addOne = fun (num : Int) : Int { + return num + 1 +} +``` + +A function can also return another function: + +```kotlin +fun makeAddOne() : (Int) -> Int { + return fun(num : Int) : Int { + return num + 1 + } +} +``` + +Once assigned, the function can be called through the variable as if it was just another function: +```kotlin +addOne(3) +// => 4 +``` + +## Declaring function types + +A variable or parameter type can be declared using the syntax `(parameter types) -> return type`. +For example, declaring a variable: + +```kotlin +val addOne : (Int) -> Int = fun (num : Int) : Int { + return num + 1 +} +``` + +And for a function parameter: + +```kotlin +fun perform(operation : (Int) -> Int) { + operation(3) +} +``` + +## Lambda expressions + +A lambda expression is a shorter way of defining a function. +They are written in the form `{ parameters -> body }`. +The expression returns the last value from the last statement in the body. +For example: + +```kotlin +// Assigning to a variable +val addOne = { num : Int -> num + 1} + +// In a function call +perform({ num : Int -> num + 1 }) +``` + +Kotlin can infer types when there is enough information. +For example, the above examples can also be written as: + +```kotlin +// Assigning to a variable +val addOne : (Int) -> Int = { num -> num + 1 } + +// Or ... +val addOne = { num : Int -> num + 1 } + +// Using in a function +perform({ num -> num + 1 }) +``` + +## `it` for single parameter lambdas + +When the expression has just one parameter, the parameter can be omitted. +Kotlin will then make a parameter called `it` available in the body. +For example: + +```kotlin +val addOne : (Int) -> Int = { it + 1 } +``` + +## Passing trailing lambdas + +When the last argument to a function is a lambda, the lambda expression is written directly _after_ the parentheses. +For example: + +```kotlin +// Function that takes a function as last argument +fun calculateFrom(from : Int, operation : (Int) -> Int) : Int { + return operation(from) +} + +// Call the calculateFrom function +calculateFrom(2) { it * 3 } +// => 6 +``` diff --git a/concepts/higher-order-functions/introduction.md b/concepts/higher-order-functions/introduction.md new file mode 100644 index 00000000..ceaa58a1 --- /dev/null +++ b/concepts/higher-order-functions/introduction.md @@ -0,0 +1,101 @@ +# About Higher Order Functions + +Functions in Kotlin are first class citizens. +This means they can be stored in variables, passed as arguments and even returned by other functions. +For example, assigning a function to the variable `addOne`: + +```kotlin +val addOne = fun (num : Int) : Int { + return num + 1 +} +``` + +A function can also return another function: + +```kotlin +fun makeAddOne() : (Int) -> Int { + return fun(num : Int) : Int { + return num + 1 + } +} +``` + +Once assigned, the function can be called through the variable as if it was just another function: +```kotlin +addOne(3) +// => 4 +``` + +## Declaring function types + +A variable or parameter type can be declared using the syntax `(parameter types) -> return type`. +For example, declaring a variable: + +```kotlin +val addOne : (Int) -> Int = fun (num : Int) : Int { + return num + 1 +} +``` + +And for a function parameter: + +```kotlin +fun perform(operation : (Int) -> Int) { + operation(3) +} +``` + +## Lambda expressions + +A lambda expression is a shorter way of defining a function. +They are written in the form `{ parameters -> body }`. +The expression returns the last value from the last statement in the body. +For example: + +```kotlin +// Assigning to a variable +val addOne = { num : Int -> num + 1} + +// In a function call +perform({ num : Int -> num + 1 }) +``` + +Kotlin can infer types when there is enough information. +For example, the above examples can also be written as: + +```kotlin +// Assigning to a variable +val addOne : (Int) -> Int = { num -> num + 1 } + +// Or ... +val addOne = { num : Int -> num + 1 } + +// Using in a function +perform({ num -> num + 1 }) +``` + +## `it` for single parameter lambdas + +When the expression has just one parameter, the parameter can be omitted. +Kotlin will then make a parameter called `it` available in the body. +For example: + +```kotlin +val addOne : (Int) -> Int = { it + 1 } +``` + +## Passing trailing lambdas + +When the last argument to a function is a lambda, the lambda expression is written directly _after_ the parentheses. +For example: + +```kotlin +// Function that takes a function as last argument +fun calculateFrom(from : Int, operation : (Int) -> Int) : Int { + return operation(from) +} + +// Call the calculateFrom function +calculateFrom(2) { it * 3 } +// => 6 +``` diff --git a/concepts/higher-order-functions/links.json b/concepts/higher-order-functions/links.json new file mode 100644 index 00000000..71cf9cc0 --- /dev/null +++ b/concepts/higher-order-functions/links.json @@ -0,0 +1,10 @@ +[ + { + "url": "https://kotlinlang.org/docs/functions.html", + "description": "Kotlin Functions documentation" + }, + { + "url": "https://kotlinlang.org/docs/lambdas.html", + "description": "Kotlin Lambdas documentation" + } +] diff --git a/config.json b/config.json index 0f44a742..b16671ef 100644 --- a/config.json +++ b/config.json @@ -55,6 +55,19 @@ "basics" ], "status": "wip" + }, + { + "slug": "secret-agent", + "name": "secret-agent", + "uuid": "96553db0-5b98-4dcd-8a1c-882e42c3751a", + "concepts": [ + "higher-order-functions" + ], + "prerequisites": [ + "numbers", + "strings" + ], + "status": "wip" } ], "practice": [ @@ -1196,6 +1209,7 @@ "practices": [], "prerequisites": [], "difficulty": 6, + "status": "deprecated", "topics": [ "conditionals", "games", @@ -1203,8 +1217,7 @@ "lists", "matrices", "strings" - ], - "status": "deprecated" + ] }, { "slug": "rail-fence-cipher", diff --git a/exercises/concept/secret-agent/.docs/instructions.md b/exercises/concept/secret-agent/.docs/instructions.md new file mode 100644 index 00000000..1fc683ff --- /dev/null +++ b/exercises/concept/secret-agent/.docs/instructions.md @@ -0,0 +1,64 @@ +# Instructions + +Hello, Agent Double-Null0111. + +Your mission, should you choose to accept it, is to write a pair of tools to help you infiltrate UMBRA (United Minions Being Really Awful) headquarters and retrieve the plans for their latest really awful scheme. +There are three tools you will need to carry out this mission. + +## 1. Generate an id number + +Each minion has a unique identifier that changes each day and depends on the number of secrets they hold and the number of hours they sleep. +You will need to write a function that takes the day (as an `Int`) and creates an identifier generating function for the day. +The identifier is calculated by: + +1. Multiply the number of secrets held by the number of hours they sleep +2. Add the day (represented as an `Int`) to the result + +```kotlin +val idGenerator = makeIdGenerator(4) +idGenerator(3, 6) +// => 22 + +idGenerator(11, 5) +// => 59 +``` + +## 2. Protect the recovered secret plans with a secret password + +Once you have the secret plans, you will need to protect it so that only those who know the password can recover them. +In order to do this, you will need to implement the function `protectSecret(secret: String, password: String) : (String) -> String`. +This function will return another function that takes possible password strings as input. +If the entered password is correct the new function returns the hidden secret, but if the password is incorrect, the function returns "Sorry. No hidden secrets here." + +```kotlin +val secretFunction = protectSecret("Steal the world's supply of french fries!", "5up3r53cr37") + +secretFunction("Open sesame") +// Returns "Sorry. No hidden secrets here." + +secretFunction("5up3r53cr37") +// Returns "Steal the world's supply of french fries!" +``` + +## 3. Find the secret password + +The UMBRA base has a number of rooms guarded by a security guard who will ask you for the secret password. +The secret password depends on the room'sS number. +Unfortunately, we have know only half of the algorithm for working out the password. +The other half can be found by asking one of the minions. + +Implement the `getPassword` function that takes in the room number and the minion's function and returns the secret password. +The secret number is obtained by calling the minion's function with another function representing the algorithm known by us. +Our part of the algorithm: + +1. Takes two numbers and adds them together +2. Multiplies the result by the room id + +```kotlin +val minionFunction = { yourFunc : (Int, Int) -> Int -> + "Password=${yourFunc(1, 3)}" +} + +getPassword(5, minionFunction) +// Returns "Password=20" +``` diff --git a/exercises/concept/secret-agent/.docs/introduction.md b/exercises/concept/secret-agent/.docs/introduction.md new file mode 100644 index 00000000..f37f43a1 --- /dev/null +++ b/exercises/concept/secret-agent/.docs/introduction.md @@ -0,0 +1,101 @@ +# Introduction + +Functions in Kotlin are first class citizens. +This means they can be stored in variables, passed as arguments and even returned by other functions. +For example, assigning a function to the variable `addOne`: + +```kotlin +val addOne = fun (num : Int) : Int { + return num + 1 +} +``` + +A function can also return another function: + +```kotlin +fun makeAddOne() : (Int) -> Int { + return fun(num : Int) : Int { + return num + 1 + } +} +``` + +Once assigned, the function can be called through the variable as if it was just another function: +```kotlin +addOne(3) +// => 4 +``` + +## Declaring function types + +A variable or parameter type can be declared using the syntax `(parameter types) -> return type`. +For example, declaring a variable: + +```kotlin +val addOne : (Int) -> Int = fun (num : Int) : Int { + return num + 1 +} +``` + +And for a function parameter: + +```kotlin +fun perform(operation : (Int) -> Int) { + operation(3) +} +``` + +## Lambda expressions + +A lambda expression is a shorter way of defining a function. +They are written in the form `{ parameters -> body }`. +The expression returns the last value from the last statement in the body. +For example: + +```kotlin +// Assigning to a variable +val addOne = { num : Int -> num + 1} + +// In a function call +perform({ num : Int -> num + 1 }) +``` + +Kotlin can infer types when there is enough information. +For example, the above examples can also be written as: + +```kotlin +// Assigning to a variable +val addOne : (Int) -> Int = { num -> num + 1 } + +// Or ... +val addOne = { num : Int -> num + 1 } + +// Using in a function +perform({ num -> num + 1 }) +``` + +## `it` for single parameter lambdas + +When the expression has just one parameter, the parameter can be omitted. +Kotlin will then make a parameter called `it` available in the body. +For example: + +```kotlin +val addOne : (Int) -> Int = { it + 1 } +``` + +## Passing trailing lambdas + +When the last argument to a function is a lambda, the lambda expression is written directly _after_ the parentheses. +For example: + +```kotlin +// Function that takes a function as last argument +fun calculateFrom(from : Int, operation : (Int) -> Int) : Int { + return operation(from) +} + +// Call the calculateFrom function +calculateFrom(2) { it * 3 } +// => 6 +``` diff --git a/exercises/concept/secret-agent/.meta/config.json b/exercises/concept/secret-agent/.meta/config.json new file mode 100644 index 00000000..02e13ac5 --- /dev/null +++ b/exercises/concept/secret-agent/.meta/config.json @@ -0,0 +1,20 @@ +{ + "authors": [ + "kahgoh" + ], + "files": { + "solution": [ + "src/main/kotlin/SecretAgent.kt" + ], + "test": [ + "src/test/kotlin/SecretAgentTest.kt" + ], + "exemplar": [ + ".meta/src/reference/kotlin/SecretAgent.kt" + ] + }, + "forked_from": [ + "swift/secret-agent" + ], + "blurb": "Learn about higher-order functions by becoming a spy and infiltrate the secret UMBRA headquarters" +} diff --git a/exercises/concept/secret-agent/.meta/design.md b/exercises/concept/secret-agent/.meta/design.md new file mode 100644 index 00000000..0b559d97 --- /dev/null +++ b/exercises/concept/secret-agent/.meta/design.md @@ -0,0 +1,21 @@ +# Design + +## Goal + +The goal of this exercise is to teach students about higher order functions and lambda expressions in Kotlin. + +## Learning objectives + +- How to write lambda expressions +- How to pass a function to another function +- How to call a function from a variable or function parameter + +## Out of scope + +## Concepts + +- `higher-order-functions`: Know about lambda expressions in Kotlin and how to assign them to variables; how to pass them to other functions; how to return them; how to invoke them + +## Prerequisites + +Strings and numbers are used in the exercise. \ No newline at end of file diff --git a/exercises/concept/secret-agent/.meta/src/reference/kotlin/SecretAgent.kt b/exercises/concept/secret-agent/.meta/src/reference/kotlin/SecretAgent.kt new file mode 100644 index 00000000..e684638c --- /dev/null +++ b/exercises/concept/secret-agent/.meta/src/reference/kotlin/SecretAgent.kt @@ -0,0 +1,17 @@ +fun makeIdGenerator(day : Int) : (Int, Int) -> Int { + return {num1 : Int, num2 : Int -> num1 * num2 + day} +} + +fun protectSecret(secret : String, password : String) : (String) -> String { + return { + if (it == password) { + secret + } else { + "Sorry. No hidden secrets here." + } + } +} + +fun getPassword(room : Int, minionFunction : ((Int, Int) -> Int) -> String) : String { + return minionFunction {num1 : Int, num2 : Int -> (num1 + num2) * room} +} diff --git a/exercises/concept/secret-agent/build.gradle.kts b/exercises/concept/secret-agent/build.gradle.kts new file mode 100644 index 00000000..3db5dc4f --- /dev/null +++ b/exercises/concept/secret-agent/build.gradle.kts @@ -0,0 +1,23 @@ +import org.gradle.api.tasks.testing.logging.TestExceptionFormat + +plugins { + kotlin("jvm") +} + +repositories { + mavenCentral() +} + +dependencies { + implementation(kotlin("stdlib-jdk8")) + + testImplementation("junit:junit:4.13.2") + testImplementation(kotlin("test-junit")) +} + +tasks.withType { + testLogging { + exceptionFormat = TestExceptionFormat.FULL + events("passed", "failed", "skipped") + } +} diff --git a/exercises/concept/secret-agent/gradle/wrapper/gradle-wrapper.jar b/exercises/concept/secret-agent/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..7f93135c Binary files /dev/null and b/exercises/concept/secret-agent/gradle/wrapper/gradle-wrapper.jar differ diff --git a/exercises/concept/secret-agent/gradle/wrapper/gradle-wrapper.properties b/exercises/concept/secret-agent/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..3fa8f862 --- /dev/null +++ b/exercises/concept/secret-agent/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/exercises/concept/secret-agent/gradlew b/exercises/concept/secret-agent/gradlew new file mode 100755 index 00000000..1aa94a42 --- /dev/null +++ b/exercises/concept/secret-agent/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/secret-agent/gradlew.bat b/exercises/concept/secret-agent/gradlew.bat new file mode 100644 index 00000000..93e3f59f --- /dev/null +++ b/exercises/concept/secret-agent/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. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +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/secret-agent/settings.gradle.kts b/exercises/concept/secret-agent/settings.gradle.kts new file mode 100644 index 00000000..054e2f7e --- /dev/null +++ b/exercises/concept/secret-agent/settings.gradle.kts @@ -0,0 +1,13 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + } + resolutionStrategy { + eachPlugin { + when (requested.id.id) { + "org.jetbrains.kotlin.jvm" -> useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0") + } + } + } +} diff --git a/exercises/concept/secret-agent/src/main/kotlin/SecretAgent.kt b/exercises/concept/secret-agent/src/main/kotlin/SecretAgent.kt new file mode 100644 index 00000000..6f03c1fa --- /dev/null +++ b/exercises/concept/secret-agent/src/main/kotlin/SecretAgent.kt @@ -0,0 +1,11 @@ +fun makeIdGenerator(day : Int) : (Int, Int) -> Int { + TODO("Please implement the makeIdGenerator() function") +} + +fun protectSecret(secret : String, password : String) : (String) -> String { + TODO("Please implement the protectSecret() function") +} + +fun getPassword(room : Int, minionFunction : ((Int, Int) -> Int) -> String) : String { + TODO("Please implement the getPassword() function") +} diff --git a/exercises/concept/secret-agent/src/test/kotlin/SecretAgentTest.kt b/exercises/concept/secret-agent/src/test/kotlin/SecretAgentTest.kt new file mode 100644 index 00000000..68875fe5 --- /dev/null +++ b/exercises/concept/secret-agent/src/test/kotlin/SecretAgentTest.kt @@ -0,0 +1,56 @@ +import org.junit.Assert.assertEquals +import kotlin.test.Test + +class SecretAgentTest() { + val protectedSecret = protectSecret("UMBRA will fill everyone's sugar bowls with salt!", "P455w0rd") + + val minionFunction1 = { yourFunc : (Int, Int) -> Int -> + "Password=${yourFunc(1, 3)}" + } + + val minionFunction2 = { yourFunc : (Int, Int) -> Int -> + "UMBRA's favourite number is ${yourFunc(7, 11)}" + } + + @Test + fun `id generator make id for day 1`() { + val idGenerator = makeIdGenerator(1) + assertEquals(29, idGenerator(4, 7)) + } + + @Test + fun `id generator make id for day 4`() { + val idGenerator = makeIdGenerator(4) + assertEquals(22, idGenerator(3, 6)) + } + + @Test + fun `protected secret returns secret with correct password`() { + assertEquals("UMBRA will fill everyone's sugar bowls with salt!", protectedSecret("P455w0rd")) + } + + @Test + fun `protected secret returns fail message with incorrect password`() { + assertEquals("Sorry. No hidden secrets here.", protectedSecret("password")) + } + + @Test + fun `get password for room 5`() { + assertEquals("Password=20", getPassword(5, minionFunction1)) + } + + @Test + fun `get password for room 17`() { + assertEquals("Password=68", getPassword(17, minionFunction1)) + } + + @Test + fun `get password for room 5 with second function`() { + assertEquals("UMBRA's favourite number is 90", getPassword(5, minionFunction2)) + } + + @Test + fun `get password for room 17 with second function`() { + assertEquals("UMBRA's favourite number is 306", getPassword(17, minionFunction2)) + } +} \ No newline at end of file diff --git a/exercises/settings.gradle.kts b/exercises/settings.gradle.kts index bc770812..f001d236 100644 --- a/exercises/settings.gradle.kts +++ b/exercises/settings.gradle.kts @@ -1,4 +1,5 @@ include( + "concept:secret-agent", "practice:accumulate", "practice:acronym", "practice:all-your-base",