Repository: TheAlgorithms/Java
Pull request #5315 (2024-08-10 12:57:43)

feat: add temperature unit conversions
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

This PR adds a _framework_ to work with unit conversions. I did not want to make the things too complicated so I only handle the case, when relation between units is _linear_.

Please review this very carefully, because probably many people would like to add more types of unit conversions in the future. Please pay special attention to:
- `UnitConversionsTest` - I did not want to make it too complicated. It is not perfect, because adding a new _quantity_ (like mass, length, time etc.) requiters adding 3 methods. But I think that it is still reasonable,
- `UnitConversions` - my idea is to have `static` members like `TEMPERATURE`, `LENGTH`, `MASS`, `TIME` etc. there. Feels a bit weird to me, but nothing else comes to my mind,
- `UnitsConverter.computeAllConversions` - probably it not the most efficient way, but there are not that many units in general. I guess it can be optimized in the _future_ without changing the API,
- is it fine to represent units as `String`s?

Please let's do not rush here.

This PR is partially inspired by #5048.

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5315?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `98.27586%` with `1 line` in your changes missing coverage. Please review.
> Project coverage is 42.31%. Comparing base [(`1977188`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/197718842f382ff83deb5d8f24fe541e0afd1025?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`c297ed8`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/c297ed8c741e08aaae9b8ae304ba3edb52e152e1?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5315?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...com/thealgorithms/conversions/AffineConverter.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5315?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fconversions%2FAffineConverter.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9jb252ZXJzaW9ucy9BZmZpbmVDb252ZXJ0ZXIuamF2YQ==) | 88.88% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5315?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5315      +/-   ##
============================================
+ Coverage     42.09%   42.31%   +0.22%     
- Complexity     2618     2643      +25     
============================================
  Files           522      525       +3     
  Lines         15565    15623      +58     
  Branches       2964     2971       +7     
============================================
+ Hits           6552     6611      +59     
+ Misses         8716     8715       -1     
  Partials        297      297              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5315?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/conversions/AffineConverter.java b/src/main/java/com/thealgorithms/conversions/AffineConverter.java
new file mode 100644
index 00000000..a580b23f
--- /dev/null
+++ b/src/main/java/com/thealgorithms/conversions/AffineConverter.java
@@ -0,0 +1,23 @@
+package com.thealgorithms.conversions;
+
+public final class AffineConverter {
+    private final double slope;
+    private final double intercept;
+    public AffineConverter(final double inSlope, final double inIntercept) {
+        slope = inSlope;
+        intercept = inIntercept;
+    }
+
+    public double convert(final double inValue) {
+        return slope * inValue + intercept;
+    }
+
+    public AffineConverter invert() {
+        assert slope != 0.0;
+        return new AffineConverter(1.0 / slope, -intercept / slope);
+    }
+
+    public AffineConverter compose(final AffineConverter other) {
+        return new AffineConverter(slope * other.slope, slope * other.intercept + intercept);
+    }
+}
diff --git a/src/main/java/com/thealgorithms/conversions/UnitConversions.java b/src/main/java/com/thealgorithms/conversions/UnitConversions.java
new file mode 100644
index 00000000..abc06a0f
--- /dev/null
+++ b/src/main/java/com/thealgorithms/conversions/UnitConversions.java
@@ -0,0 +1,14 @@
+package com.thealgorithms.conversions;
+
+import static java.util.Map.entry;
+
+import java.util.Map;
+import org.apache.commons.lang3.tuple.Pair;
+
+public final class UnitConversions {
+    private UnitConversions() {
+    }
+
+    public static final UnitsConverter TEMPERATURE = new UnitsConverter(Map.ofEntries(entry(Pair.of("Kelvin", "Celsius"), new AffineConverter(1.0, -273.15)), entry(Pair.of("Celsius", "Fahrenheit"), new AffineConverter(9.0 / 5.0, 32.0)),
+        entry(Pair.of("Réaumur", "Celsius"), new AffineConverter(5.0 / 4.0, 0.0)), entry(Pair.of("Delisle", "Celsius"), new AffineConverter(-2.0 / 3.0, 100.0)), entry(Pair.of("Rankine", "Kelvin"), new AffineConverter(5.0 / 9.0, 0.0))));
+}
diff --git a/src/main/java/com/thealgorithms/conversions/UnitsConverter.java b/src/main/java/com/thealgorithms/conversions/UnitsConverter.java
new file mode 100644
index 00000000..a19d4028
--- /dev/null
+++ b/src/main/java/com/thealgorithms/conversions/UnitsConverter.java
@@ -0,0 +1,86 @@
+package com.thealgorithms.conversions;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import org.apache.commons.lang3.tuple.Pair;
+
+public final class UnitsConverter {
+    private final Map<Pair<String, String>, AffineConverter> conversions;
+    private final Set<String> units;
+
+    private static void putIfNeeded(Map<Pair<String, String>, AffineConverter> conversions, final String inputUnit, final String outputUnit, final AffineConverter converter) {
+        if (!inputUnit.equals(outputUnit)) {
+            final var key = Pair.of(inputUnit, outputUnit);
+            conversions.putIfAbsent(key, converter);
+        }
+    }
+
+    private static Map<Pair<String, String>, AffineConverter> addInversions(final Map<Pair<String, String>, AffineConverter> knownConversions) {
+        Map<Pair<String, String>, AffineConverter> res = new HashMap<Pair<String, String>, AffineConverter>();
+        for (final var curConversion : knownConversions.entrySet()) {
+            final var inputUnit = curConversion.getKey().getKey();
+            final var outputUnit = curConversion.getKey().getValue();
+            putIfNeeded(res, inputUnit, outputUnit, curConversion.getValue());
+            putIfNeeded(res, outputUnit, inputUnit, curConversion.getValue().invert());
+        }
+        return res;
+    }
+
+    private static Map<Pair<String, String>, AffineConverter> addCompositions(final Map<Pair<String, String>, AffineConverter> knownConversions) {
+        Map<Pair<String, String>, AffineConverter> res = new HashMap<Pair<String, String>, AffineConverter>();
+        for (final var first : knownConversions.entrySet()) {
+            final var firstKey = first.getKey();
+            putIfNeeded(res, firstKey.getKey(), firstKey.getValue(), first.getValue());
+            for (final var second : knownConversions.entrySet()) {
+                final var secondKey = second.getKey();
+                if (firstKey.getValue().equals(secondKey.getKey())) {
+                    final var newConversion = second.getValue().compose(first.getValue());
+                    putIfNeeded(res, firstKey.getKey(), secondKey.getValue(), newConversion);
+                }
+            }
+        }
+        return res;
+    }
+
+    private static Map<Pair<String, String>, AffineConverter> addAll(final Map<Pair<String, String>, AffineConverter> knownConversions) {
+        final var res = addInversions(knownConversions);
+        return addCompositions(res);
+    }
+
+    private static Map<Pair<String, String>, AffineConverter> computeAllConversions(final Map<Pair<String, String>, AffineConverter> basicConversions) {
+        var tmp = basicConversions;
+        var res = addAll(tmp);
+        while (res.size() != tmp.size()) {
+            tmp = res;
+            res = addAll(tmp);
+        }
+        return res;
+    }
+
+    private static Set<String> extractUnits(final Map<Pair<String, String>, AffineConverter> conversions) {
+        Set<String> res = new HashSet<>();
+        for (final var conversion : conversions.entrySet()) {
+            res.add(conversion.getKey().getKey());
+        }
+        return res;
+    }
+
+    public UnitsConverter(final Map<Pair<String, String>, AffineConverter> basicConversions) {
+        conversions = computeAllConversions(basicConversions);
+        units = extractUnits(conversions);
+    }
+
+    public double convert(final String inputUnit, final String outputUnit, final double value) {
+        if (inputUnit.equals(outputUnit)) {
+            throw new IllegalArgumentException("inputUnit must be different from outputUnit.");
+        }
+        final var conversionKey = Pair.of(inputUnit, outputUnit);
+        return conversions.get(conversionKey).convert(value);
+    }
+
+    public Set<String> availableUnits() {
+        return units;
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/conversions/UnitConversionsTest.java b/src/test/java/com/thealgorithms/conversions/UnitConversionsTest.java
new file mode 100644
index 00000000..073e7d6d
--- /dev/null
+++ b/src/test/java/com/thealgorithms/conversions/UnitConversionsTest.java
@@ -0,0 +1,48 @@
+package com.thealgorithms.conversions;
+
+import static java.util.Map.entry;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class UnitConversionsTest {
+    private static void addData(Stream.Builder<Arguments> builder, Map<String, Double> values) {
+        for (final var first : values.entrySet()) {
+            for (final var second : values.entrySet()) {
+                if (!first.getKey().equals(second.getKey())) {
+                    builder.add(Arguments.of(first.getKey(), second.getKey(), first.getValue(), second.getValue()));
+                }
+            }
+        }
+    }
+
+    private static Stream<Arguments> temperatureData() {
+        final Map<String, Double> boilingPointOfWater = Map.ofEntries(entry("Celsius", 99.9839), entry("Fahrenheit", 211.97102), entry("Kelvin", 373.1339), entry("Réaumur", 79.98712), entry("Delisle", 0.02415), entry("Rankine", 671.64102));
+
+        final Map<String, Double> freezingPointOfWater = Map.ofEntries(entry("Celsius", 0.0), entry("Fahrenheit", 32.0), entry("Kelvin", 273.15), entry("Réaumur", 0.0), entry("Delisle", 150.0), entry("Rankine", 491.67));
+
+        Stream.Builder<Arguments> builder = Stream.builder();
+        addData(builder, boilingPointOfWater);
+        addData(builder, freezingPointOfWater);
+        return builder.build();
+    }
+
+    @ParameterizedTest
+    @MethodSource("temperatureData")
+    void testTemperature(String inputUnit, String outputUnit, double value, double expected) {
+        final double result = UnitConversions.TEMPERATURE.convert(inputUnit, outputUnit, value);
+        assertEquals(expected, result, 0.00001);
+    }
+
+    @Test
+    void testTemperatureUnits() {
+        final Set<String> expectedUnits = Set.of("Celsius", "Fahrenheit", "Kelvin", "Réaumur", "Rankine", "Delisle");
+        assertEquals(expectedUnits, UnitConversions.TEMPERATURE.availableUnits());
+    }
+}
diff --git a/src/test/java/com/thealgorithms/conversions/UnitsConverterTest.java b/src/test/java/com/thealgorithms/conversions/UnitsConverterTest.java
new file mode 100644
index 00000000..76e48f14
--- /dev/null
+++ b/src/test/java/com/thealgorithms/conversions/UnitsConverterTest.java
@@ -0,0 +1,18 @@
+package com.thealgorithms.conversions;
+
+import static java.util.Map.entry;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.Map;
+import org.apache.commons.lang3.tuple.Pair;
+import org.junit.jupiter.api.Test;
+
+public class UnitsConverterTest {
+
+    @Test
+    void testConvertThrowsForSameUnits() {
+        final UnitsConverter someConverter = new UnitsConverter(Map.ofEntries(entry(Pair.of("A", "B"), new AffineConverter(10.0, -20.0))));
+        assertThrows(IllegalArgumentException.class, () -> someConverter.convert("A", "A", 20.0));
+        assertThrows(IllegalArgumentException.class, () -> someConverter.convert("B", "B", 20.0));
+    }
+}