diff --git a/config.json b/config.json index 3d1ff49af..1623d2b25 100644 --- a/config.json +++ b/config.json @@ -1307,6 +1307,18 @@ ], "difficulty": 6 }, + { + "slug": "piecing-it-together", + "name": "Piecing It Together", + "uuid": "be303729-ad8a-4f4c-a235-6828a6734f05", + "practices": [], + "prerequisites": [ + "exceptions", + "for-loops", + "if-else-statements" + ], + "difficulty": 6 + }, { "slug": "queen-attack", "name": "Queen Attack", diff --git a/exercises/practice/piecing-it-together/.docs/instructions.md b/exercises/practice/piecing-it-together/.docs/instructions.md new file mode 100644 index 000000000..c0c966592 --- /dev/null +++ b/exercises/practice/piecing-it-together/.docs/instructions.md @@ -0,0 +1,41 @@ +# Instructions + +Given partial information about a jigsaw puzzle, add the missing pieces. + +If the information is insufficient to complete the details, or if given parts are in contradiction, the user should be notified. + +The full information about the jigsaw puzzle contains the following parts: + +- `pieces`: Total number of pieces +- `border`: Number of border pieces +- `inside`: Number of inside (non-border) pieces +- `rows`: Number of rows +- `columns`: Number of columns +- `aspectRatio`: Aspect ratio of columns to rows +- `format`: Puzzle format, which can be `portrait`, `square`, or `landscape` + +For this exercise, you may assume square pieces, so that the format can be derived from the aspect ratio: + +- If the aspect ratio is less than 1, it's `portrait` +- If it is equal to 1, it's `square` +- If it is greater than 1, it's `landscape` + +## Three examples + +### Portrait + +A portrait jigsaw puzzle with 6 pieces, all of which are border pieces and none are inside pieces. It has 3 rows and 2 columns. The aspect ratio is 1.5 (3/2). + +![A 2 by 3 jigsaw puzzle](https://assets.exercism.org/images/exercises/piecing-it-together/jigsaw-puzzle-2x3.svg) + +### Square + +A square jigsaw puzzle with 9 pieces, all of which are border pieces except for the one in the center, which is an inside piece. It has 3 rows and 3 columns. The aspect ratio is 1 (3/3). + +![A 3 by 3 jigsaw puzzle](https://assets.exercism.org/images/exercises/piecing-it-together/jigsaw-puzzle-3x3.svg) + +### Landscape + +A landscape jigsaw puzzle with 12 pieces, 10 of which are border pieces and 2 are inside pieces. It has 3 rows and 4 columns. The aspect ratio is 1.333333... (4/3). + +![A 4 by 3 jigsaw puzzle](https://assets.exercism.org/images/exercises/piecing-it-together/jigsaw-puzzle-4x3.svg) diff --git a/exercises/practice/piecing-it-together/.docs/introduction.md b/exercises/practice/piecing-it-together/.docs/introduction.md new file mode 100644 index 000000000..2fa20f6c5 --- /dev/null +++ b/exercises/practice/piecing-it-together/.docs/introduction.md @@ -0,0 +1,6 @@ +# Introduction + +Your best friend has started collecting jigsaw puzzles and wants to build a detailed catalog of their collection — recording information such as the total number of pieces, the number of rows and columns, the number of border and inside pieces, aspect ratio, and puzzle format. +Even with your powers combined, it takes multiple hours to solve a single jigsaw puzzle with one thousand pieces — and then you still need to count the rows and columns and calculate the remaining numbers manually. +The even larger puzzles with thousands of pieces look quite daunting now. +"There has to be a better way!" you exclaim and sit down in front of your computer to solve the problem. diff --git a/exercises/practice/piecing-it-together/.meta/config.json b/exercises/practice/piecing-it-together/.meta/config.json new file mode 100644 index 000000000..76e6e6cbf --- /dev/null +++ b/exercises/practice/piecing-it-together/.meta/config.json @@ -0,0 +1,22 @@ +{ + "authors": [ + "zamora-carlos" + ], + "files": { + "solution": [ + "src/main/java/PiecingItTogether.java" + ], + "test": [ + "src/test/java/PiecingItTogetherTest.java" + ], + "example": [ + ".meta/src/reference/java/PiecingItTogether.java" + ], + "editor": [ + "src/main/java/JigsawInfo.java" + ] + }, + "blurb": "Fill in missing jigsaw puzzle details from partial data", + "source": "atk just started another 1000-pieces jigsaw puzzle when this idea hit him", + "source_url": "https://github.com/exercism/problem-specifications/pull/2554" +} diff --git a/exercises/practice/piecing-it-together/.meta/src/reference/java/JigsawInfo.java b/exercises/practice/piecing-it-together/.meta/src/reference/java/JigsawInfo.java new file mode 100644 index 000000000..e08eb8909 --- /dev/null +++ b/exercises/practice/piecing-it-together/.meta/src/reference/java/JigsawInfo.java @@ -0,0 +1,140 @@ +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; + +/** + * Represents partial or complete information about a jigsaw puzzle, + * + * NOTE: There is no need to change this file and is treated as read only by the Exercism test runners. + */ +public class JigsawInfo { + private final OptionalInt pieces; + private final OptionalInt border; + private final OptionalInt inside; + private final OptionalInt rows; + private final OptionalInt columns; + private final OptionalDouble aspectRatio; + private final Optional format; + + private JigsawInfo(Builder builder) { + this.pieces = builder.pieces; + this.border = builder.border; + this.inside = builder.inside; + this.rows = builder.rows; + this.columns = builder.columns; + this.aspectRatio = builder.aspectRatio; + this.format = builder.format; + } + + public static class Builder { + private OptionalInt pieces = OptionalInt.empty(); + private OptionalInt border = OptionalInt.empty(); + private OptionalInt inside = OptionalInt.empty(); + private OptionalInt rows = OptionalInt.empty(); + private OptionalInt columns = OptionalInt.empty(); + private OptionalDouble aspectRatio = OptionalDouble.empty(); + private Optional format = Optional.empty(); + + public Builder pieces(int pieces) { + this.pieces = OptionalInt.of(pieces); + return this; + } + + public Builder border(int border) { + this.border = OptionalInt.of(border); + return this; + } + + public Builder inside(int inside) { + this.inside = OptionalInt.of(inside); + return this; + } + + public Builder rows(int rows) { + this.rows = OptionalInt.of(rows); + return this; + } + + public Builder columns(int columns) { + this.columns = OptionalInt.of(columns); + return this; + } + + public Builder aspectRatio(double aspectRatio) { + this.aspectRatio = OptionalDouble.of(aspectRatio); + return this; + } + + public Builder format(String format) { + this.format = Optional.of(format); + return this; + } + + public JigsawInfo build() { + return new JigsawInfo(this); + } + } + + public OptionalInt getPieces() { + return pieces; + } + + public OptionalInt getBorder() { + return border; + } + + public OptionalInt getInside() { + return inside; + } + + public OptionalInt getRows() { + return rows; + } + + public OptionalInt getColumns() { + return columns; + } + + public OptionalDouble getAspectRatio() { + return aspectRatio; + } + + public Optional getFormat() { + return format; + } + + @Override + public boolean equals(Object o) { + if (o == null || getClass() != o.getClass()) { + return false; + } + + JigsawInfo that = (JigsawInfo) o; + return Objects.equals(pieces, that.pieces) + && Objects.equals(border, that.border) + && Objects.equals(inside, that.inside) + && Objects.equals(rows, that.rows) + && Objects.equals(columns, that.columns) + && Objects.equals(aspectRatio, that.aspectRatio) + && Objects.equals(format, that.format); + } + + @Override + public int hashCode() { + return Objects.hash(pieces, border, inside, rows, columns, aspectRatio, format); + } + + @Override + public String toString() { + return "JigsawInfo{" + + "pieces=" + pieces + + ", border=" + border + + ", inside=" + inside + + ", rows=" + rows + + ", columns=" + columns + + ", aspectRatio=" + aspectRatio + + ", format=" + format + + '}'; + } +} diff --git a/exercises/practice/piecing-it-together/.meta/src/reference/java/PiecingItTogether.java b/exercises/practice/piecing-it-together/.meta/src/reference/java/PiecingItTogether.java new file mode 100644 index 000000000..ddbb91dc8 --- /dev/null +++ b/exercises/practice/piecing-it-together/.meta/src/reference/java/PiecingItTogether.java @@ -0,0 +1,135 @@ +import java.util.*; + +public class PiecingItTogether { + private static final double DOUBLE_EQUALITY_TOLERANCE = 1e-9; + private static final int MAX_DIMENSION = 1000; + + public static JigsawInfo getCompleteInformation(JigsawInfo input) { + List validGuesses = new ArrayList<>(); + + if (input.getPieces().isPresent()) { + // If pieces is known, we only test divisors of pieces + int pieces = input.getPieces().getAsInt(); + for (int rows = 1; rows <= pieces; rows++) { + if (pieces % rows != 0) { + continue; + } + int columns = pieces / rows; + createValidJigsaw(rows, columns, input).ifPresent(validGuesses::add); + } + } else if (input.getInside().isPresent() && input.getInside().getAsInt() > 0) { + // If inside pieces is non-zero, we only test divisors of inside + int inside = input.getInside().getAsInt(); + for (int innerRows = 1; innerRows <= inside; innerRows++) { + if (inside % innerRows != 0) { + continue; + } + int innerColumns = inside / innerRows; + createValidJigsaw(innerRows + 2, innerColumns + 2, input).ifPresent(validGuesses::add); + } + } else { + // Brute force using border constraint if available + int maxDimension = input.getBorder().isPresent() + ? Math.min(input.getBorder().getAsInt(), MAX_DIMENSION) + : MAX_DIMENSION; + + for (int rows = 1; rows <= maxDimension; rows++) { + for (int columns = 1; columns <= maxDimension; columns++) { + createValidJigsaw(rows, columns, input).ifPresent(validGuesses::add); + } + } + } + + if (validGuesses.size() == 1) { + return validGuesses.get(0); + } else if (validGuesses.size() > 1) { + throw new IllegalArgumentException("Insufficient data"); + } else { + throw new IllegalArgumentException("Contradictory data"); + } + } + + private static String getFormatFromAspect(double aspectRatio) { + if (Math.abs(aspectRatio - 1.0) < DOUBLE_EQUALITY_TOLERANCE) { + return "square"; + } else if (aspectRatio < 1.0) { + return "portrait"; + } else { + return "landscape"; + } + } + + private static JigsawInfo fromRowsAndCols(int rows, int columns) { + int pieces = rows * columns; + int border = (rows == 1 || columns == 1) ? pieces : 2 * (rows + columns - 2); + int inside = pieces - border; + double aspectRatio = (double) columns / rows; + String format = getFormatFromAspect(aspectRatio); + + return new JigsawInfo.Builder() + .pieces(pieces) + .border(border) + .inside(inside) + .rows(rows) + .columns(columns) + .aspectRatio(aspectRatio) + .format(format) + .build(); + } + + /** + * Verifies that all known values in the input match those in the computed result. + * Returns false if any known value conflicts, true if all values are consistent. + * + * @param computed the fully inferred jigsaw information + * @param input the original partial input with possibly empty values + * @return true if all values are consistent, false if any conflict exists + */ + private static boolean isConsistent(JigsawInfo computed, JigsawInfo input) { + return valuesMatch(computed.getPieces(), input.getPieces()) && + valuesMatch(computed.getBorder(), input.getBorder()) && + valuesMatch(computed.getInside(), input.getInside()) && + valuesMatch(computed.getRows(), input.getRows()) && + valuesMatch(computed.getColumns(), input.getColumns()) && + valuesMatch(computed.getAspectRatio(), input.getAspectRatio()) && + valuesMatch(computed.getFormat(), input.getFormat()); + } + + /** + * Attempts to construct a valid jigsaw configuration using the specified number of rows and columns. + * Returns a valid result only if the configuration is consistent with the input. + * + * @param rows number of rows to try + * @param columns number of columns to try + * @param input the original input to check for consistency + * @return an Optional containing a valid configuration, or empty if inconsistent + */ + private static Optional createValidJigsaw(int rows, int columns, JigsawInfo input) { + JigsawInfo candidate = fromRowsAndCols(rows, columns); + return isConsistent(candidate, input) ? Optional.of(candidate) : Optional.empty(); + } + + private static boolean valuesMatch(Optional a, Optional b) { + if (a.isPresent() && b.isPresent()) { + return Objects.equals(a.get(), b.get()); + } + + return true; + } + + private static boolean valuesMatch(OptionalInt a, OptionalInt b) { + if (a.isPresent() && b.isPresent()) { + return a.getAsInt() == b.getAsInt(); + } + + return true; + } + + private static boolean valuesMatch(OptionalDouble a, OptionalDouble b) { + if (a.isPresent() && b.isPresent()) { + return Double.compare(a.getAsDouble(), b.getAsDouble()) == 0; + } + + return true; + } +} diff --git a/exercises/practice/piecing-it-together/.meta/tests.toml b/exercises/practice/piecing-it-together/.meta/tests.toml new file mode 100644 index 000000000..f462c15a3 --- /dev/null +++ b/exercises/practice/piecing-it-together/.meta/tests.toml @@ -0,0 +1,31 @@ +# 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. + +[ad626f23-09a2-4f5f-ba22-eec0671fa2a9] +description = "1000 pieces puzzle with 1.6 aspect ratio" + +[3e0c5919-3561-42f5-b9ed-26d70c20214e] +description = "square puzzle with 32 rows" + +[1126f160-b094-4dc2-bf37-13e36e394867] +description = "400 pieces square puzzle with only inside pieces and aspect ratio" + +[a9743178-5642-4cc0-8fdb-00d6b031c3a0] +description = "1500 pieces landscape puzzle with 30 rows and 1.6 aspect ratio" + +[f6378369-989c-497f-a6e2-f30b1fa76cba] +description = "300 pieces portrait puzzle with 70 border pieces" + +[f53f82ba-5663-4c7e-9e86-57fdbb3e53d2] +description = "puzzle with insufficient data" + +[a3d5c31a-cc74-44bf-b4fc-9e4d65f1ac1a] +description = "puzzle with contradictory data" diff --git a/exercises/practice/piecing-it-together/build.gradle b/exercises/practice/piecing-it-together/build.gradle new file mode 100644 index 000000000..dd3862eb9 --- /dev/null +++ b/exercises/practice/piecing-it-together/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/piecing-it-together/gradle/wrapper/gradle-wrapper.jar b/exercises/practice/piecing-it-together/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e6441136f Binary files /dev/null and b/exercises/practice/piecing-it-together/gradle/wrapper/gradle-wrapper.jar differ diff --git a/exercises/practice/piecing-it-together/gradle/wrapper/gradle-wrapper.properties b/exercises/practice/piecing-it-together/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..2deab89d5 --- /dev/null +++ b/exercises/practice/piecing-it-together/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/piecing-it-together/gradlew b/exercises/practice/piecing-it-together/gradlew new file mode 100755 index 000000000..1aa94a426 --- /dev/null +++ b/exercises/practice/piecing-it-together/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/piecing-it-together/gradlew.bat b/exercises/practice/piecing-it-together/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/exercises/practice/piecing-it-together/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/practice/piecing-it-together/src/main/java/JigsawInfo.java b/exercises/practice/piecing-it-together/src/main/java/JigsawInfo.java new file mode 100644 index 000000000..e08eb8909 --- /dev/null +++ b/exercises/practice/piecing-it-together/src/main/java/JigsawInfo.java @@ -0,0 +1,140 @@ +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalDouble; +import java.util.OptionalInt; + +/** + * Represents partial or complete information about a jigsaw puzzle, + * + * NOTE: There is no need to change this file and is treated as read only by the Exercism test runners. + */ +public class JigsawInfo { + private final OptionalInt pieces; + private final OptionalInt border; + private final OptionalInt inside; + private final OptionalInt rows; + private final OptionalInt columns; + private final OptionalDouble aspectRatio; + private final Optional format; + + private JigsawInfo(Builder builder) { + this.pieces = builder.pieces; + this.border = builder.border; + this.inside = builder.inside; + this.rows = builder.rows; + this.columns = builder.columns; + this.aspectRatio = builder.aspectRatio; + this.format = builder.format; + } + + public static class Builder { + private OptionalInt pieces = OptionalInt.empty(); + private OptionalInt border = OptionalInt.empty(); + private OptionalInt inside = OptionalInt.empty(); + private OptionalInt rows = OptionalInt.empty(); + private OptionalInt columns = OptionalInt.empty(); + private OptionalDouble aspectRatio = OptionalDouble.empty(); + private Optional format = Optional.empty(); + + public Builder pieces(int pieces) { + this.pieces = OptionalInt.of(pieces); + return this; + } + + public Builder border(int border) { + this.border = OptionalInt.of(border); + return this; + } + + public Builder inside(int inside) { + this.inside = OptionalInt.of(inside); + return this; + } + + public Builder rows(int rows) { + this.rows = OptionalInt.of(rows); + return this; + } + + public Builder columns(int columns) { + this.columns = OptionalInt.of(columns); + return this; + } + + public Builder aspectRatio(double aspectRatio) { + this.aspectRatio = OptionalDouble.of(aspectRatio); + return this; + } + + public Builder format(String format) { + this.format = Optional.of(format); + return this; + } + + public JigsawInfo build() { + return new JigsawInfo(this); + } + } + + public OptionalInt getPieces() { + return pieces; + } + + public OptionalInt getBorder() { + return border; + } + + public OptionalInt getInside() { + return inside; + } + + public OptionalInt getRows() { + return rows; + } + + public OptionalInt getColumns() { + return columns; + } + + public OptionalDouble getAspectRatio() { + return aspectRatio; + } + + public Optional getFormat() { + return format; + } + + @Override + public boolean equals(Object o) { + if (o == null || getClass() != o.getClass()) { + return false; + } + + JigsawInfo that = (JigsawInfo) o; + return Objects.equals(pieces, that.pieces) + && Objects.equals(border, that.border) + && Objects.equals(inside, that.inside) + && Objects.equals(rows, that.rows) + && Objects.equals(columns, that.columns) + && Objects.equals(aspectRatio, that.aspectRatio) + && Objects.equals(format, that.format); + } + + @Override + public int hashCode() { + return Objects.hash(pieces, border, inside, rows, columns, aspectRatio, format); + } + + @Override + public String toString() { + return "JigsawInfo{" + + "pieces=" + pieces + + ", border=" + border + + ", inside=" + inside + + ", rows=" + rows + + ", columns=" + columns + + ", aspectRatio=" + aspectRatio + + ", format=" + format + + '}'; + } +} diff --git a/exercises/practice/piecing-it-together/src/main/java/PiecingItTogether.java b/exercises/practice/piecing-it-together/src/main/java/PiecingItTogether.java new file mode 100644 index 000000000..d0ba9fa81 --- /dev/null +++ b/exercises/practice/piecing-it-together/src/main/java/PiecingItTogether.java @@ -0,0 +1,5 @@ +public class PiecingItTogether { + public static JigsawInfo getCompleteInformation(JigsawInfo input) { + throw new UnsupportedOperationException("Delete this statement and write your own implementation."); + } +} diff --git a/exercises/practice/piecing-it-together/src/test/java/PiecingItTogetherTest.java b/exercises/practice/piecing-it-together/src/test/java/PiecingItTogetherTest.java new file mode 100644 index 000000000..b07648c0a --- /dev/null +++ b/exercises/practice/piecing-it-together/src/test/java/PiecingItTogetherTest.java @@ -0,0 +1,167 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class PiecingItTogetherTest { + private static final double DOUBLE_EQUALITY_TOLERANCE = 1e-9; + + @Test + public void test1000PiecesWithAspectRatio() { + JigsawInfo input = new JigsawInfo.Builder() + .pieces(1000) + .aspectRatio(1.6) + .build(); + + JigsawInfo expected = new JigsawInfo.Builder() + .pieces(1000) + .border(126) + .inside(874) + .rows(25) + .columns(40) + .aspectRatio(1.6) + .format("landscape") + .build(); + + JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); + assertJigsawInfoEquals(actual, expected); + } + + @Disabled("Remove to run test") + @Test + public void testSquarePuzzleWith32Rows() { + JigsawInfo input = new JigsawInfo.Builder() + .rows(32) + .format("square") + .build(); + + JigsawInfo expected = new JigsawInfo.Builder() + .pieces(1024) + .border(124) + .inside(900) + .rows(32) + .columns(32) + .aspectRatio(1.0) + .format("square") + .build(); + + JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); + assertJigsawInfoEquals(actual, expected); + } + + @Disabled("Remove to run test") + @Test + public void testInsideAndAspectRatioOnly() { + JigsawInfo input = new JigsawInfo.Builder() + .inside(324) + .aspectRatio(1.0) + .build(); + + JigsawInfo expected = new JigsawInfo.Builder() + .pieces(400) + .border(76) + .inside(324) + .rows(20) + .columns(20) + .aspectRatio(1.0) + .format("square") + .build(); + + JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); + assertJigsawInfoEquals(actual, expected); + } + + @Disabled("Remove to run test") + @Test + public void testLandscape1500WithRowsAndAspect() { + JigsawInfo input = new JigsawInfo.Builder() + .rows(30) + .aspectRatio(1.6666666666666667) + .build(); + + JigsawInfo expected = new JigsawInfo.Builder() + .pieces(1500) + .border(156) + .inside(1344) + .rows(30) + .columns(50) + .aspectRatio(1.6666666666666667) + .format("landscape") + .build(); + + JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); + assertJigsawInfoEquals(actual, expected); + } + + @Disabled("Remove to run test") + @Test + public void test300PiecesPortraitWithBorder() { + JigsawInfo input = new JigsawInfo.Builder() + .pieces(300) + .border(70) + .format("portrait") + .build(); + + JigsawInfo expected = new JigsawInfo.Builder() + .pieces(300) + .border(70) + .inside(230) + .rows(25) + .columns(12) + .aspectRatio(0.48) + .format("portrait") + .build(); + + JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); + assertJigsawInfoEquals(actual, expected); + } + + @Disabled("Remove to run test") + @Test + public void testInsufficientData() { + JigsawInfo input = new JigsawInfo.Builder() + .pieces(1500) + .format("landscape") + .build(); + + assertThatThrownBy(() -> PiecingItTogether.getCompleteInformation(input)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Insufficient data"); + } + + @Disabled("Remove to run test") + @Test + public void testContradictoryData() { + JigsawInfo input = new JigsawInfo.Builder() + .rows(100) + .columns(1000) + .format("square") + .build(); + + assertThatThrownBy(() -> PiecingItTogether.getCompleteInformation(input)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Contradictory data"); + } + + /** + * Helper to compare two JigsawInfo objects, + * allowing a small tolerance when comparing aspect ratio doubles. + */ + private void assertJigsawInfoEquals(JigsawInfo actual, JigsawInfo expected) { + assertThat(actual.getPieces()).isEqualTo(expected.getPieces()); + assertThat(actual.getBorder()).isEqualTo(expected.getBorder()); + assertThat(actual.getInside()).isEqualTo(expected.getInside()); + assertThat(actual.getRows()).isEqualTo(expected.getRows()); + assertThat(actual.getColumns()).isEqualTo(expected.getColumns()); + assertThat(actual.getFormat()).isEqualTo(expected.getFormat()); + + Double actualAspect = actual.getAspectRatio() + .orElseThrow(() -> new AssertionError("Missing aspect ratio in actual result")); + Double expectedAspect = expected.getAspectRatio() + .orElseThrow(() -> new AssertionError("Missing aspect ratio in expected result")); + + assertThat(actualAspect).isCloseTo(expectedAspect, + org.assertj.core.api.Assertions.within(DOUBLE_EQUALITY_TOLERANCE)); + } +} diff --git a/exercises/settings.gradle b/exercises/settings.gradle index 713a0c583..38c04e59a 100644 --- a/exercises/settings.gradle +++ b/exercises/settings.gradle @@ -104,6 +104,7 @@ include 'practice:parallel-letter-frequency' include 'practice:pascals-triangle' include 'practice:perfect-numbers' include 'practice:phone-number' +include 'practice:piecing-it-together' include 'practice:pig-latin' include 'practice:poker' include 'practice:eliuds-eggs'