Files
jack/change/ChangeCalculatorMain.java
T

252 lines
10 KiB
Java

/**
* MIT License
*
* Copyright (c) 2021 Exercism
* Copyright (c) 2026 Networked Embedded Systems, University of Duisburg-Essen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import static java.util.Arrays.asList;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
public class ChangeCalculatorMain {
@Test(name = "change for 1 cent")
public void testChangeForOneCent() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 5, 10, 25));
assertListEquals(List.of(1), changeCalculator.computeMostEfficientChange(1));
});
}
@Test(name = "single coin change")
@Disabled
public void testChangeThatCanBeGivenInASingleCoin() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 5, 10, 25, 100));
assertListEquals(List.of(25), changeCalculator.computeMostEfficientChange(25));
});
}
@Test(name = "multiple coin change")
@Disabled
public void testChangeThatMustBeGivenInMultipleCoins() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 5, 10, 25, 100));
assertListEquals(List.of(5, 10), changeCalculator.computeMostEfficientChange(15));
});
}
@Test(name = "change with Lilliputian Coins")
@Disabled
public void testLilliputianCurrency() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 4, 15, 20, 50));
assertListEquals(List.of(4, 4, 15), changeCalculator.computeMostEfficientChange(23));
});
}
@Test(name = "change with Lower Elbonia Coins")
@Disabled
public void testLowerElbonianCurrency() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 5, 10, 21, 25));
assertListEquals(List.of(21, 21, 21), changeCalculator.computeMostEfficientChange(63));
});
}
@Test(name = "large target values")
@Disabled
public void testLargeAmountOfChange() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 2, 5, 10, 20, 50, 100));
assertListEquals(List.of(2, 2, 5, 20, 20, 50, 100, 100, 100, 100, 100, 100, 100, 100, 100),
changeCalculator.computeMostEfficientChange(999));
});
}
@Test(name = "possible change without unit coins available")
@Disabled
public void testPossibleChangeWithoutUnitCoinAvailable() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(2, 5, 10, 20, 50));
assertListEquals(List.of(2, 2, 2, 5, 10), changeCalculator.computeMostEfficientChange(21));
});
}
@Test(name = "another possible change without unit coins available")
@Disabled
public void testAnotherPossibleChangeWithoutUnitCoinAvailable() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(4, 5));
assertListEquals(List.of(4, 4, 4, 5, 5, 5), changeCalculator.computeMostEfficientChange(27));
});
}
@Test(name = "a greedy approach is not optimal")
@Disabled
public void testAGreedyApproachIsNotOptimal() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 10, 11));
assertListEquals(List.of(10, 10), changeCalculator.computeMostEfficientChange(20));
});
}
@Test(name = "no coins make 0 change")
@Disabled
public void testZeroChange() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 5, 10, 21, 25));
assertListEquals(List.of(), changeCalculator.computeMostEfficientChange(0));
});
}
@Test(name = "error testing for change smaller than the smallest of coins")
@Disabled
public void testChangeLessThanSmallestCoinInCurrencyCannotBeRepresented() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(5, 10));
assertThrows(IllegalArgumentException.class, () -> changeCalculator.computeMostEfficientChange(3),
"The total 3 cannot be represented in the given currency.");
});
}
@Test(name = "error if no combination can add up to target")
@Disabled
public void testChangeLargerThanAllCoinsInCurrencyThatCannotBeRepresented() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(5, 10));
assertThrows(IllegalArgumentException.class, () -> changeCalculator.computeMostEfficientChange(94),
"The total 94 cannot be represented in the given currency.");
});
}
@Test(name = "cannot find negative change values")
@Disabled
public void testNegativeChangeIsRejected() {
runTest(() -> {
ChangeCalculator changeCalculator = new ChangeCalculator(asList(1, 2, 5));
assertThrows(IllegalArgumentException.class, () -> changeCalculator.computeMostEfficientChange(-5),
"Negative totals are not allowed.");
});
}
private void runTest(Runnable body) {
try {
body.run();
System.out.println("TEST PASSED");
} catch (Exception | AssertionError t) {
System.out.println("TEST FAILED: " + t.getMessage());
}
}
private void assertListEquals(List<Integer> expected, List<Integer> actual) {
if (expected == null && actual == null)
return;
if (expected == null || actual == null)
throw new AssertionError("Expected: " + expected + ", but got: " + actual);
if (expected.size() != actual.size())
throw new AssertionError("Expected list size " + expected.size() + " but was " + actual.size());
for (int i = 0; i < expected.size(); i++) {
if (!expected.get(i).equals(actual.get(i))) {
throw new AssertionError(
"Expected element at " + i + " to be " + expected.get(i) + " but was " + actual.get(i));
}
}
}
private void assertThrows(Class<? extends Throwable> expectedType, Runnable runnable, String expectedMessage) {
try {
runnable.run();
throw new AssertionError("Expected exception of type: " + expectedType.getName());
} catch (Throwable t) {
if (!expectedType.isInstance(t)) {
throw new AssertionError(
"Expected exception type: " + expectedType.getName() + ", but got: " + t.getClass().getName());
}
if (expectedMessage != null && !expectedMessage.equals(t.getMessage())) {
throw new AssertionError("Expected message: " + expectedMessage + " but was: " + t.getMessage());
}
}
}
public static void main(String[] args) {
new ChangeCalculatorMain().runTests();
}
/**
* Annotation to mark test methods. The name parameter is used to identify the
* test in the output.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
private @interface Test {
String name();
}
/**
* Annotation to mark test methods as disabled. Disabled tests will not be
* executed when running the tests.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
private @interface Disabled {
}
private void runTests() {
Method[] methods = this.getClass().getDeclaredMethods();
List<Method> allTestMethods = Arrays.asList(methods).stream().filter(m -> m.isAnnotationPresent(Test.class))
.collect(Collectors.toList());
List<Method> enabledTestMethods = allTestMethods.stream().filter(m -> !m.isAnnotationPresent(Disabled.class))
.collect(Collectors.toList());
System.out
.println("Running " + enabledTestMethods.size() + " out of " + allTestMethods.size() + " tests... \n");
for (Method method : enabledTestMethods) {
try {
System.out.println("Running test: " + method.getAnnotation(Test.class).name());
method.invoke(this);
} catch (Exception e) {
System.out.println("Test " + method.getAnnotation(Test.class).name()
+ " failed with an unexpected exception: " + e.getCause());
}
}
System.out.println("Finished running tests.");
if (allTestMethods.size() != enabledTestMethods.size()) {
System.out.println("\nThe following tests are disabled and were not executed:");
for (Method method : allTestMethods) {
if (method.isAnnotationPresent(Disabled.class)) {
System.out.println("- " + method.getAnnotation(Test.class).name());
}
}
System.out.println(
"To enable these tests, remove the @Disabled annotation from the corresponding test methods.");
}
}
}