diff --git a/config.json b/config.json index 9805391b2..fa08384ff 100644 --- a/config.json +++ b/config.json @@ -842,6 +842,17 @@ ], "difficulty": 4 }, + { + "slug": "split-second-stopwatch", + "name": "Split-Second Stopwatch", + "uuid": "9510c0ae-9977-4260-8991-0e8e849094b0", + "practices": [], + "prerequisites": [ + "exceptions", + "if-else-statements" + ], + "difficulty": 4 + }, { "slug": "sum-of-multiples", "name": "Sum of Multiples", diff --git a/exercises/practice/split-second-stopwatch/.docs/instructions.md b/exercises/practice/split-second-stopwatch/.docs/instructions.md new file mode 100644 index 000000000..30bdc988d --- /dev/null +++ b/exercises/practice/split-second-stopwatch/.docs/instructions.md @@ -0,0 +1,22 @@ +# Instructions + +Your task is to build a stopwatch to keep precise track of lap times. + +The stopwatch uses four commands (start, stop, lap, and reset) to keep track of: + +1. The current lap's tracked time +2. Previously recorded lap times + +What commands can be used depends on which state the stopwatch is in: + +1. Ready: initial state +2. Running: tracking time +3. Stopped: not tracking time + +| Command | Begin state | End state | Effect | +| ------- | ----------- | --------- | -------------------------------------------------------- | +| Start | Ready | Running | Start tracking time | +| Start | Stopped | Running | Resume tracking time | +| Stop | Running | Stopped | Stop tracking time | +| Lap | Running | Running | Add current lap to previous laps, then reset current lap | +| Reset | Stopped | Ready | Reset current lap and clear previous laps | diff --git a/exercises/practice/split-second-stopwatch/.docs/introduction.md b/exercises/practice/split-second-stopwatch/.docs/introduction.md new file mode 100644 index 000000000..a84322477 --- /dev/null +++ b/exercises/practice/split-second-stopwatch/.docs/introduction.md @@ -0,0 +1,6 @@ +# Introduction + +You've always run for the thrill of it — no schedules, no timers, just the sound of your feet on the pavement. +But now that you've joined a competitive running crew, things are getting serious. +Training sessions are timed to the second, and every split second counts. +To keep pace, you've picked up the _Split-Second Stopwatch_ — a sleek, high-tech gadget that's about to become your new best friend. diff --git a/exercises/practice/split-second-stopwatch/.meta/config.json b/exercises/practice/split-second-stopwatch/.meta/config.json new file mode 100644 index 000000000..cde93a410 --- /dev/null +++ b/exercises/practice/split-second-stopwatch/.meta/config.json @@ -0,0 +1,19 @@ +{ + "authors": [ + "EmmanuelBerkowicz" + ], + "files": { + "solution": [ + "src/main/java/SplitSecondStopwatch.java" + ], + "test": [ + "src/test/java/SplitSecondStopwatchTest.java" + ], + "example": [ + ".meta/src/reference/java/SplitSecondStopwatch.java" + ] + }, + "blurb": "Keep track of time through a digital stopwatch.", + "source": "Erik Schierboom", + "source_url": "https://github.com/exercism/problem-specifications/pull/2547" +} diff --git a/exercises/practice/split-second-stopwatch/.meta/src/reference/java/SplitSecondStopwatch.java b/exercises/practice/split-second-stopwatch/.meta/src/reference/java/SplitSecondStopwatch.java new file mode 100644 index 000000000..c00a58cea --- /dev/null +++ b/exercises/practice/split-second-stopwatch/.meta/src/reference/java/SplitSecondStopwatch.java @@ -0,0 +1,125 @@ +import java.util.ArrayList; +import java.util.List; + +public class SplitSecondStopwatch { + + /** + * A split-second stopwatch that tracks elapsed time with lap functionality. + * Supports start, stop, reset, and lap operations with precise time tracking. + * Times are formatted in HH:MM:SS format with two-digit precision. + * + * @see + * Problem Specifications + * + */ + + private enum State { READY, RUNNING, STOPPED } + + private State state; + private long totalCompletedLaps; // Total time from completed laps + private long currentLapStart; // When current lap started + private long accumulated; // Accumulated time for current lap when stopped + private List previousLaps; + private long mockTime; + + public SplitSecondStopwatch() { + this.state = State.READY; + this.totalCompletedLaps = 0; + this.currentLapStart = 0; + this.accumulated = 0; + this.previousLaps = new ArrayList<>(); + this.mockTime = 0; + } + + public void start() { + if (state == State.RUNNING) { + throw new IllegalStateException("cannot start an already running stopwatch"); + } + + currentLapStart = mockTime; + state = State.RUNNING; + } + + public void stop() { + if (state != State.RUNNING) { + throw new IllegalStateException("cannot stop a stopwatch that is not running"); + } + + accumulated += mockTime - currentLapStart; + state = State.STOPPED; + } + + public void reset() { + if (state != State.STOPPED) { + throw new IllegalStateException("cannot reset a stopwatch that is not stopped"); + } + + state = State.READY; + totalCompletedLaps = 0; + currentLapStart = 0; + accumulated = 0; + previousLaps.clear(); + } + + public void lap() { + if (state != State.RUNNING) { + throw new IllegalStateException("cannot lap a stopwatch that is not running"); + } + + long currentLapTime = getCurrentLapTime(); + totalCompletedLaps += currentLapTime; + previousLaps.add(formatTime(currentLapTime)); + + // Reset current lap and restart + accumulated = 0; + currentLapStart = mockTime; + } + + public String state() { + return state.name().toLowerCase(); + } + + public String currentLap() { + return formatTime(getCurrentLapTime()); + } + + public String total() { + return formatTime(totalCompletedLaps + getCurrentLapTime()); + } + + public List previousLaps() { + return new ArrayList<>(previousLaps); + } + + public void advanceTime(String timeString) { + String[] parts = timeString.split(":"); + long hours = Long.parseLong(parts[0]); + long minutes = Long.parseLong(parts[1]); + long seconds = Long.parseLong(parts[2]); + + long milliseconds = (hours * 3600 + minutes * 60 + seconds) * 1000; + mockTime += milliseconds; + } + + private long getCurrentLapTime() { + switch (state) { + case READY: + return 0; + case RUNNING: + return accumulated + (mockTime - currentLapStart); + case STOPPED: + return accumulated; + default: + throw new IllegalStateException("Invalid state"); + } + } + + private String formatTime(long milliseconds) { + long totalSeconds = milliseconds / 1000; + long hours = totalSeconds / 3600; + long minutes = (totalSeconds % 3600) / 60; + long seconds = totalSeconds % 60; + + return String.format("%02d:%02d:%02d", hours, minutes, seconds); + } +} diff --git a/exercises/practice/split-second-stopwatch/.meta/tests.toml b/exercises/practice/split-second-stopwatch/.meta/tests.toml new file mode 100644 index 000000000..323cb7ae8 --- /dev/null +++ b/exercises/practice/split-second-stopwatch/.meta/tests.toml @@ -0,0 +1,97 @@ +# This is an auto-generated file. +# +# Regenerating this file via `configlet sync` will: +# - Recreate every `description` key/value pair +# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications +# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion) +# - Preserve any other key/value pair +# +# As user-added comments (using the # character) will be removed when this file +# is regenerated, comments can be added via a `comment` key. + +[ddb238ea-99d4-4eaa-a81d-3c917a525a23] +description = "new stopwatch starts in ready state" + +[b19635d4-08ad-4ac3-b87f-aca10e844071] +description = "new stopwatch's current lap has no elapsed time" + +[492eb532-268d-43ea-8a19-2a032067d335] +description = "new stopwatch's total has no elapsed time" + +[8a892c1e-9ef7-4690-894e-e155a1fe4484] +description = "new stopwatch does not have previous laps" + +[5b2705b6-a584-4042-ba3a-4ab8d0ab0281] +description = "start from ready state changes state to running" + +[748235ce-1109-440b-9898-0a431ea179b6] +description = "start does not change previous laps" + +[491487b1-593d-423e-a075-aa78d449ff1f] +description = "start initiates time tracking for current lap" + +[a0a7ba2c-8db6-412c-b1b6-cb890e9b72ed] +description = "start initiates time tracking for total" + +[7f558a17-ef6d-4a5b-803a-f313af7c41d3] +description = "start cannot be called from running state" + +[32466eef-b2be-4d60-a927-e24fce52dab9] +description = "stop from running state changes state to stopped" + +[621eac4c-8f43-4d99-919c-4cad776d93df] +description = "stop pauses time tracking for current lap" + +[465bcc82-7643-41f2-97ff-5e817cef8db4] +description = "stop pauses time tracking for total" + +[b1ba7454-d627-41ee-a078-891b2ed266fc] +description = "stop cannot be called from ready state" + +[5c041078-0898-44dc-9d5b-8ebb5352626c] +description = "stop cannot be called from stopped state" + +[3f32171d-8fbf-46b6-bc2b-0810e1ec53b7] +description = "start from stopped state changes state to running" + +[626997cb-78d5-4fe8-b501-29fdef804799] +description = "start from stopped state resumes time tracking for current lap" + +[58487c53-ab26-471c-a171-807ef6363319] +description = "start from stopped state resumes time tracking for total" + +[091966e3-ed25-4397-908b-8bb0330118f8] +description = "lap adds current lap to previous laps" + +[1aa4c5ee-a7d5-4d59-9679-419deef3c88f] +description = "lap resets current lap and resumes time tracking" + +[4b46b92e-1b3f-46f6-97d2-0082caf56e80] +description = "lap continues time tracking for total" + +[ea75d36e-63eb-4f34-97ce-8c70e620bdba] +description = "lap cannot be called from ready state" + +[63731154-a23a-412d-a13f-c562f208eb1e] +description = "lap cannot be called from stopped state" + +[e585ee15-3b3f-4785-976b-dd96e7cc978b] +description = "stop does not change previous laps" + +[fc3645e2-86cf-4d11-97c6-489f031103f6] +description = "reset from stopped state changes state to ready" + +[20fbfbf7-68ad-4310-975a-f5f132886c4e] +description = "reset resets current lap" + +[00a8f7bb-dd5c-43e5-8705-3ef124007662] +description = "reset clears previous laps" + +[76cea936-6214-4e95-b6d1-4d4edcf90499] +description = "reset cannot be called from ready state" + +[ba4d8e69-f200-4721-b59e-90d8cf615153] +description = "reset cannot be called from running state" + +[0b01751a-cb57-493f-bb86-409de6e84306] +description = "supports very long laps" diff --git a/exercises/practice/split-second-stopwatch/build.gradle b/exercises/practice/split-second-stopwatch/build.gradle new file mode 100644 index 000000000..d28f35dee --- /dev/null +++ b/exercises/practice/split-second-stopwatch/build.gradle @@ -0,0 +1,25 @@ +plugins { + id "java" +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation platform("org.junit:junit-bom:5.10.0") + testImplementation "org.junit.jupiter:junit-jupiter" + testImplementation "org.assertj:assertj-core:3.25.1" + + testRuntimeOnly "org.junit.platform:junit-platform-launcher" +} + +test { + useJUnitPlatform() + + testLogging { + exceptionFormat = "full" + showStandardStreams = true + events = ["passed", "failed", "skipped"] + } +} diff --git a/exercises/practice/split-second-stopwatch/gradle/wrapper/gradle-wrapper.jar b/exercises/practice/split-second-stopwatch/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e6441136f Binary files /dev/null and b/exercises/practice/split-second-stopwatch/gradle/wrapper/gradle-wrapper.jar differ diff --git a/exercises/practice/split-second-stopwatch/gradle/wrapper/gradle-wrapper.properties b/exercises/practice/split-second-stopwatch/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..2deab89d5 --- /dev/null +++ b/exercises/practice/split-second-stopwatch/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/practice/split-second-stopwatch/gradlew b/exercises/practice/split-second-stopwatch/gradlew new file mode 100644 index 000000000..1aa94a426 --- /dev/null +++ b/exercises/practice/split-second-stopwatch/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/practice/split-second-stopwatch/gradlew.bat b/exercises/practice/split-second-stopwatch/gradlew.bat new file mode 100644 index 000000000..25da30dbd --- /dev/null +++ b/exercises/practice/split-second-stopwatch/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/practice/split-second-stopwatch/src/main/java/SplitSecondStopwatch.java b/exercises/practice/split-second-stopwatch/src/main/java/SplitSecondStopwatch.java new file mode 100644 index 000000000..36847004c --- /dev/null +++ b/exercises/practice/split-second-stopwatch/src/main/java/SplitSecondStopwatch.java @@ -0,0 +1,37 @@ +public class SplitSecondStopwatch { + public void start() { + throw new UnsupportedOperationException("Please implement the SplitSecondStopwatch.start method."); + } + + public void stop() { + throw new UnsupportedOperationException("Please implement the SplitSecondStopwatch.stop method."); + } + + public void reset() { + throw new UnsupportedOperationException("Please implement the SplitSecondStopwatch.reset method."); + } + + public void lap() { + throw new UnsupportedOperationException("Please implement the SplitSecondStopwatch.lap method."); + } + + public String state() { + throw new UnsupportedOperationException("Please implement the SplitSecondStopwatch.state method."); + } + + public String currentLap() { + throw new UnsupportedOperationException("Please implement the SplitSecondStopwatch.currentLap method."); + } + + public String total() { + throw new UnsupportedOperationException("Please implement the SplitSecondStopwatch.total method."); + } + + public java.util.List previousLaps() { + throw new UnsupportedOperationException("Please implement the SplitSecondStopwatch.previousLaps method."); + } + + public void advanceTime(String timeString) { + throw new UnsupportedOperationException("Please implement the SplitSecondStopwatch.advanceTime method."); + } +} \ No newline at end of file diff --git a/exercises/practice/split-second-stopwatch/src/test/java/SplitSecondStopwatchTest.java b/exercises/practice/split-second-stopwatch/src/test/java/SplitSecondStopwatchTest.java new file mode 100644 index 000000000..1f54a9907 --- /dev/null +++ b/exercises/practice/split-second-stopwatch/src/test/java/SplitSecondStopwatchTest.java @@ -0,0 +1,339 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class SplitSecondStopwatchTest { + @Test + @DisplayName("new stopwatch starts in ready state") + public void newStopwatchStartsInReadyState() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + assertThat(stopwatch.state()).isEqualTo("ready"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("new stopwatch's current lap has no elapsed time") + public void newStopwatchCurrentLapHasNoElapsedTime() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + assertThat(stopwatch.currentLap()).isEqualTo("00:00:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("new stopwatch's total has no elapsed time") + public void newStopwatchTotalHasNoElapsedTime() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + assertThat(stopwatch.total()).isEqualTo("00:00:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("new stopwatch does not have previous laps") + public void newStopwatchDoesNotHavePreviousLaps() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + assertThat(stopwatch.previousLaps()).isEmpty(); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("start from ready state changes state to running") + public void startFromReadyStateChangesStateToRunning() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + assertThat(stopwatch.state()).isEqualTo("running"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("start does not change previous laps") + public void startDoesNotChangePreviousLaps() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + assertThat(stopwatch.previousLaps()).isEmpty(); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("start initiates time tracking for current lap") + public void startInitiatesTimeTrackingForCurrentLap() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:00:05"); + assertThat(stopwatch.currentLap()).isEqualTo("00:00:05"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("start initiates time tracking for total") + public void startInitiatesTimeTrackingForTotal() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:00:23"); + assertThat(stopwatch.total()).isEqualTo("00:00:23"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("start cannot be called from running state") + public void startCannotBeCalledFromRunningState() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(stopwatch::start) + .withMessage("cannot start an already running stopwatch"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("stop from running state changes state to stopped") + public void stopFromRunningStateChangesStateToStopped() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.stop(); + assertThat(stopwatch.state()).isEqualTo("stopped"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("stop pauses time tracking for current lap") + public void stopPausesTimeTrackingForCurrentLap() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:00:05"); + stopwatch.stop(); + stopwatch.advanceTime("00:00:08"); + assertThat(stopwatch.currentLap()).isEqualTo("00:00:05"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("stop pauses time tracking for total") + public void stopPausesTimeTrackingForTotal() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:00:13"); + stopwatch.stop(); + stopwatch.advanceTime("00:00:44"); + assertThat(stopwatch.total()).isEqualTo("00:00:13"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("stop cannot be called from ready state") + public void stopCannotBeCalledFromReadyState() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(stopwatch::stop) + .withMessage("cannot stop a stopwatch that is not running"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("stop cannot be called from stopped state") + public void stopCannotBeCalledFromStoppedState() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.stop(); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(stopwatch::stop) + .withMessage("cannot stop a stopwatch that is not running"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("start from stopped state changes state to running") + public void startFromStoppedStateChangesStateToRunning() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.stop(); + stopwatch.start(); + assertThat(stopwatch.state()).isEqualTo("running"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("start from stopped state resumes time tracking for current lap") + public void startFromStoppedStateResumesTimeTrackingForCurrentLap() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:01:20"); + stopwatch.stop(); + stopwatch.advanceTime("00:00:20"); + stopwatch.start(); + stopwatch.advanceTime("00:00:08"); + assertThat(stopwatch.currentLap()).isEqualTo("00:01:28"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("start from stopped state resumes time tracking for total") + public void startFromStoppedStateResumesTimeTrackingForTotal() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:00:23"); + stopwatch.stop(); + stopwatch.advanceTime("00:00:44"); + stopwatch.start(); + stopwatch.advanceTime("00:00:09"); + assertThat(stopwatch.total()).isEqualTo("00:00:32"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("lap adds current lap to previous laps") + public void lapAddsCurrentLapToPreviousLaps() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:01:38"); + stopwatch.lap(); + assertThat(stopwatch.previousLaps()).containsExactly("00:01:38"); + stopwatch.advanceTime("00:00:44"); + stopwatch.lap(); + assertThat(stopwatch.previousLaps()).containsExactly("00:01:38", "00:00:44"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("lap resets current lap and resumes time tracking") + public void lapResetsCurrentLapAndResumesTimeTracking() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:08:22"); + stopwatch.lap(); + assertThat(stopwatch.currentLap()).isEqualTo("00:00:00"); + stopwatch.advanceTime("00:00:15"); + assertThat(stopwatch.currentLap()).isEqualTo("00:00:15"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("lap continues time tracking for total") + public void lapContinuesTimeTrackingForTotal() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:00:22"); + stopwatch.lap(); + stopwatch.advanceTime("00:00:33"); + assertThat(stopwatch.total()).isEqualTo("00:00:55"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("lap cannot be called from ready state") + public void lapCannotBeCalledFromReadyState() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(stopwatch::lap) + .withMessage("cannot lap a stopwatch that is not running"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("lap cannot be called from stopped state") + public void lapCannotBeCalledFromStoppedState() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.stop(); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(stopwatch::lap) + .withMessage("cannot lap a stopwatch that is not running"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("stop does not change previous laps") + public void stopDoesNotChangePreviousLaps() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:11:22"); + stopwatch.lap(); + assertThat(stopwatch.previousLaps()).containsExactly("00:11:22"); + stopwatch.stop(); + assertThat(stopwatch.previousLaps()).containsExactly("00:11:22"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("reset from stopped state changes state to ready") + public void resetFromStoppedStateChangesStateToReady() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.stop(); + stopwatch.reset(); + assertThat(stopwatch.state()).isEqualTo("ready"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("reset resets current lap") + public void resetResetsCurrentLap() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:00:10"); + stopwatch.stop(); + stopwatch.reset(); + assertThat(stopwatch.currentLap()).isEqualTo("00:00:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("reset clears previous laps") + public void resetClearsPreviousLaps() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("00:00:10"); + stopwatch.lap(); + stopwatch.advanceTime("00:00:20"); + stopwatch.lap(); + assertThat(stopwatch.previousLaps()).containsExactly("00:00:10", "00:00:20"); + stopwatch.stop(); + stopwatch.reset(); + assertThat(stopwatch.previousLaps()).isEmpty(); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("reset cannot be called from ready state") + public void resetCannotBeCalledFromReadyState() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(stopwatch::reset) + .withMessage("cannot reset a stopwatch that is not stopped"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("reset cannot be called from running state") + public void resetCannotBeCalledFromRunningState() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + assertThatExceptionOfType(IllegalStateException.class) + .isThrownBy(stopwatch::reset) + .withMessage("cannot reset a stopwatch that is not stopped"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("supports very long laps") + public void supportsVeryLongLaps() { + SplitSecondStopwatch stopwatch = new SplitSecondStopwatch(); + stopwatch.start(); + stopwatch.advanceTime("01:23:45"); + assertThat(stopwatch.currentLap()).isEqualTo("01:23:45"); + stopwatch.lap(); + assertThat(stopwatch.previousLaps()).containsExactly("01:23:45"); + stopwatch.advanceTime("04:01:40"); + assertThat(stopwatch.currentLap()).isEqualTo("04:01:40"); + assertThat(stopwatch.total()).isEqualTo("05:25:25"); + stopwatch.lap(); + assertThat(stopwatch.previousLaps()).containsExactly("01:23:45", "04:01:40"); + stopwatch.advanceTime("08:43:05"); + assertThat(stopwatch.currentLap()).isEqualTo("08:43:05"); + assertThat(stopwatch.total()).isEqualTo("14:08:30"); + stopwatch.lap(); + assertThat(stopwatch.previousLaps()).containsExactly("01:23:45", "04:01:40", "08:43:05"); + } +} diff --git a/exercises/settings.gradle b/exercises/settings.gradle index c46f79877..e17e28e81 100644 --- a/exercises/settings.gradle +++ b/exercises/settings.gradle @@ -145,6 +145,7 @@ include 'practice:simple-linked-list' include 'practice:sgf-parsing' include 'practice:space-age' include 'practice:spiral-matrix' +include 'practice:split-second-stopwatch' include 'practice:square-root' include 'practice:state-of-tic-tac-toe' // include 'practice:strain' // deprecated