Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
41 changes: 41 additions & 0 deletions exercises/practice/piecing-it-together/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -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)
6 changes: 6 additions & 0 deletions exercises/practice/piecing-it-together/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -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.
22 changes: 22 additions & 0 deletions exercises/practice/piecing-it-together/.meta/config.json
Original file line number Diff line number Diff line change
@@ -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": [
".meta/src/reference/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"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
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<String> format;

private JigsawInfo(Builder builder) {
this.pieces = builder.pieces != null ? OptionalInt.of(builder.pieces) : OptionalInt.empty();
this.border = builder.border != null ? OptionalInt.of(builder.border) : OptionalInt.empty();
this.inside = builder.inside != null ? OptionalInt.of(builder.inside) : OptionalInt.empty();
this.rows = builder.rows != null ? OptionalInt.of(builder.rows) : OptionalInt.empty();
this.columns = builder.columns != null ? OptionalInt.of(builder.columns) : OptionalInt.empty();
this.aspectRatio = builder.aspectRatio != null ? OptionalDouble.of(builder.aspectRatio) : OptionalDouble.empty();
this.format = Optional.ofNullable(builder.format);
}

public static class Builder {
private Integer pieces;
private Integer border;
private Integer inside;
private Integer rows;
private Integer columns;
private Double aspectRatio;
private String format;

public Builder pieces(Integer pieces) {
this.pieces = pieces;
return this;
}

public Builder border(Integer border) {
this.border = border;
return this;
}

public Builder inside(Integer inside) {
this.inside = inside;
return this;
}

public Builder rows(Integer rows) {
this.rows = rows;
return this;
}

public Builder columns(Integer columns) {
this.columns = columns;
return this;
}

public Builder aspectRatio(Double aspectRatio) {
this.aspectRatio = aspectRatio;
return this;
}

public Builder format(String format) {
this.format = 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<String> 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 +
'}';
}
}
Original file line number Diff line number Diff line change
@@ -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<JigsawInfo> 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.getFirst();
} 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<JigsawInfo> createValidJigsaw(int rows, int columns, JigsawInfo input) {
JigsawInfo candidate = fromRowsAndCols(rows, columns);
return isConsistent(candidate, input) ? Optional.of(candidate) : Optional.empty();
}

private static <T> boolean valuesMatch(Optional<T> a, Optional<T> 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;
}
}
31 changes: 31 additions & 0 deletions exercises/practice/piecing-it-together/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -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"
Loading
Loading