From e3cbf382d7f54bc6ceecdfcd9495b648645ada6b Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 22:53:33 +0530 Subject: [PATCH 01/49] Adding approach change --- .../practice/change/.approaches/config,json | 21 +++++ .../dynamic-programming/content.md | 82 +++++++++++++++++++ .../dynamic-programming/snippet.txt | 36 ++++++++ .../change/.approaches/intrduction.md | 25 ++++++ 4 files changed, 164 insertions(+) create mode 100644 exercises/practice/change/.approaches/config,json create mode 100644 exercises/practice/change/.approaches/dynamic-programming/content.md create mode 100644 exercises/practice/change/.approaches/dynamic-programming/snippet.txt create mode 100644 exercises/practice/change/.approaches/intrduction.md diff --git a/exercises/practice/change/.approaches/config,json b/exercises/practice/change/.approaches/config,json new file mode 100644 index 000000000..78950cae5 --- /dev/null +++ b/exercises/practice/change/.approaches/config,json @@ -0,0 +1,21 @@ +{ + "introduction": { + "authors": [ + "jagdish-15" + ] + }, + "approaches": [ + { + "uuid": "", + "slug": "dynamic-programming", + "title": "Dynamic Programming Approach", + "blurb": "Use dynamic programming to find the most efficient change combination.", + "authors": [ + "jagdish-15" + ], + "contributors": [ + "kagoh" + ] + } + ] +} diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md new file mode 100644 index 000000000..38e8376f5 --- /dev/null +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -0,0 +1,82 @@ +# Dynamic Programming Approach + +The **Dynamic Programming (DP)** approach is an efficient way to solve the problem of making change for a given total using a list of available coin denominations. It minimizes the number of coins needed by breaking down the problem into smaller subproblems and solving them progressively. + +This approach ensures that we find the most efficient way to make change and handles edge cases where no solution exists. + +## Explanation + +1. **Initialize Coins Usage Tracker**: + - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. + - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. + +2. **Iterative Dynamic Programming**: + - For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. + - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). + - If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. + +3. **Result**: + - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. + - If no valid combination exists for `grandTotal`, an exception is thrown. + + +```java +import java.util.List; +import java.util.ArrayList; + +class ChangeCalculator { + private final List currencyCoins; + + ChangeCalculator(List currencyCoins) { + this.currencyCoins = currencyCoins; + } + + List computeMostEfficientChange(int grandTotal) { + if (grandTotal < 0) + throw new IllegalArgumentException("Negative totals are not allowed."); + + List> coinsUsed = new ArrayList<>(grandTotal + 1); + coinsUsed.add(new ArrayList()); + + for (int i = 1; i <= grandTotal; i++) { + List bestCombination = null; + for (int coin: currencyCoins) { + if (coin <= i && coinsUsed.get(i - coin) != null) { + List currentCombination = new ArrayList<>(coinsUsed.get(i - coin)); + currentCombination.add(0, coin); + if (bestCombination == null || currentCombination.size() < bestCombination.size()) + bestCombination = currentCombination; + } + } + coinsUsed.add(bestCombination); + } + + if (coinsUsed.get(grandTotal) == null) + throw new IllegalArgumentException("The total " + grandTotal + " cannot be represented in the given currency."); + + return coinsUsed.get(grandTotal); + } +} +``` + +## Key Points + +- **Time Complexity**: The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. + +- **Space Complexity**: The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. + +- **Edge Cases**: + - If the `grandTotal` is negative, an exception is thrown immediately. + - If there is no way to make the exact total with the given denominations, an exception is thrown with a descriptive message. + +## Trade-offs and Considerations + +- **Efficiency**: This approach is highly efficient in terms of minimizing the number of coins, but it might require significant memory for larger `grandTotal` values, as the space complexity grows linearly with `grandTotal`. + +- **Alternative Approaches**: + - A **Greedy Approach** could be faster for some cases but does not always guarantee the minimum number of coins. + - This dynamic programming approach is best when the goal is to guarantee the fewest coins possible, especially when no simple greedy solution exists. + +## Conclusion + +The dynamic programming approach provides an optimal solution for the change-making problem, ensuring that we minimize the number of coins used while efficiently solving the problem for any `grandTotal`. However, it’s essential to consider the trade-offs in terms of memory usage and the time complexity when dealing with very large inputs. diff --git a/exercises/practice/change/.approaches/dynamic-programming/snippet.txt b/exercises/practice/change/.approaches/dynamic-programming/snippet.txt new file mode 100644 index 000000000..3bbc3ad8c --- /dev/null +++ b/exercises/practice/change/.approaches/dynamic-programming/snippet.txt @@ -0,0 +1,36 @@ +import java.util.List; +import java.util.ArrayList; + +class ChangeCalculator { + private final List currencyCoins; + + ChangeCalculator(List currencyCoins) { + this.currencyCoins = currencyCoins; + } + + List computeMostEfficientChange(int grandTotal) { + if (grandTotal < 0) + throw new IllegalArgumentException("Negative totals are not allowed."); + + List> coinsUsed = new ArrayList<>(grandTotal + 1); + coinsUsed.add(new ArrayList()); + + for (int i = 1; i <= grandTotal; i++) { + List bestCombination = null; + for (int coin: currencyCoins) { + if (coin <= i && coinsUsed.get(i - coin) != null) { + List currentCombination = new ArrayList<>(coinsUsed.get(i - coin)); + currentCombination.add(0, coin); + if (bestCombination == null || currentCombination.size() < bestCombination.size()) + bestCombination = currentCombination; + } + } + coinsUsed.add(bestCombination); + } + + if (coinsUsed.get(grandTotal) == null) + throw new IllegalArgumentException("The total " + grandTotal + " cannot be represented in the given currency."); + + return coinsUsed.get(grandTotal); + } +} \ No newline at end of file diff --git a/exercises/practice/change/.approaches/intrduction.md b/exercises/practice/change/.approaches/intrduction.md new file mode 100644 index 000000000..27aaef140 --- /dev/null +++ b/exercises/practice/change/.approaches/intrduction.md @@ -0,0 +1,25 @@ +## Introduction to Change Calculation + +In the "Change Calculator" exercise, the goal is to determine the minimum number of coins needed to reach a given total using a specific set of coin denominations. This is a classic problem in dynamic programming, where efficient change-making is essential, especially when there are constraints on coin types or large totals. + +### Problem Overview + +Given: +- A list of coin denominations, each representing an available currency unit. +- A total amount (`grandTotal`) we want to reach using the fewest possible coins from the given denominations. + +The solution should find the optimal combination of coins to match the total. If it's impossible to match the total exactly, the solution should indicate this by throwing an exception. + +### Approach Overview + +Our solution uses a **dynamic programming approach**, where we systematically build up the optimal combinations for all totals from `0` up to the target amount (`grandTotal`). For each total, we track the fewest coins needed to make that total, reusing previous results to make the solution efficient. + +This approach ensures that we find the minimum number of coins required in a structured, repeatable way, avoiding the need for complex recursive calls or excessive backtracking. + +### Key Features of the Approach + +- **Efficiency**: By building solutions for each increment up to `grandTotal`, this approach minimizes redundant calculations. +- **Flexibility**: Handles cases where exact change is impossible by checking at each step. +- **Scalability**: Works for various coin denominations and totals, though large inputs may impact performance. + +For a detailed look at the code and logic, see the full explanation in the [approach file](https://exercism.org/tracks/java/exercises/change/approaches/dynamic-programming). From 4a7811f81f30eb1a1f4f43fe2ccf313214817876 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 23:05:15 +0530 Subject: [PATCH 02/49] Fixing typo in filename --- .../practice/change/.approaches/{config,json => config.json} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename exercises/practice/change/.approaches/{config,json => config.json} (100%) diff --git a/exercises/practice/change/.approaches/config,json b/exercises/practice/change/.approaches/config.json similarity index 100% rename from exercises/practice/change/.approaches/config,json rename to exercises/practice/change/.approaches/config.json From e8d2787928d2c320d3f16a564c0e67502b3b22ba Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 23:13:50 +0530 Subject: [PATCH 03/49] Fixing style errors --- .../change/.approaches/dynamic-programming/content.md | 4 +++- exercises/practice/change/.approaches/intrduction.md | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index 38e8376f5..2f283a312 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -7,7 +7,7 @@ This approach ensures that we find the most efficient way to make change and han ## Explanation 1. **Initialize Coins Usage Tracker**: - - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. + - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. 2. **Iterative Dynamic Programming**: @@ -66,6 +66,7 @@ class ChangeCalculator { - **Space Complexity**: The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. - **Edge Cases**: + - If the `grandTotal` is negative, an exception is thrown immediately. - If there is no way to make the exact total with the given denominations, an exception is thrown with a descriptive message. @@ -74,6 +75,7 @@ class ChangeCalculator { - **Efficiency**: This approach is highly efficient in terms of minimizing the number of coins, but it might require significant memory for larger `grandTotal` values, as the space complexity grows linearly with `grandTotal`. - **Alternative Approaches**: + - A **Greedy Approach** could be faster for some cases but does not always guarantee the minimum number of coins. - This dynamic programming approach is best when the goal is to guarantee the fewest coins possible, especially when no simple greedy solution exists. diff --git a/exercises/practice/change/.approaches/intrduction.md b/exercises/practice/change/.approaches/intrduction.md index 27aaef140..84531fad3 100644 --- a/exercises/practice/change/.approaches/intrduction.md +++ b/exercises/practice/change/.approaches/intrduction.md @@ -1,10 +1,11 @@ -## Introduction to Change Calculation +# Introduction to Change Calculator In the "Change Calculator" exercise, the goal is to determine the minimum number of coins needed to reach a given total using a specific set of coin denominations. This is a classic problem in dynamic programming, where efficient change-making is essential, especially when there are constraints on coin types or large totals. ### Problem Overview Given: + - A list of coin denominations, each representing an available currency unit. - A total amount (`grandTotal`) we want to reach using the fewest possible coins from the given denominations. From 6152c100a88f280066afd36ae745f39e03b38dee Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 23:19:55 +0530 Subject: [PATCH 04/49] Fixing style errors --- .../change/.approaches/dynamic-programming/content.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index 2f283a312..260e52e77 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -6,16 +6,19 @@ This approach ensures that we find the most efficient way to make change and han ## Explanation -1. **Initialize Coins Usage Tracker**: +1. **Initialize Coins Usage Tracker**: + - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. -2. **Iterative Dynamic Programming**: +2. **Iterative Dynamic Programming**: + - For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). - If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. -3. **Result**: +3. **Result**: + - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. - If no valid combination exists for `grandTotal`, an exception is thrown. From 5d398d014afa7b223a92f12044b7dd929c0307e3 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 23:29:29 +0530 Subject: [PATCH 05/49] Fixing stle errors --- .../change/.approaches/dynamic-programming/content.md | 5 ++--- exercises/practice/change/.approaches/intrduction.md | 6 +++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index 260e52e77..cce152a0b 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -14,7 +14,7 @@ This approach ensures that we find the most efficient way to make change and han 2. **Iterative Dynamic Programming**: - For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. - - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). + - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). - If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. 3. **Result**: @@ -22,7 +22,6 @@ This approach ensures that we find the most efficient way to make change and han - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. - If no valid combination exists for `grandTotal`, an exception is thrown. - ```java import java.util.List; import java.util.ArrayList; @@ -77,7 +76,7 @@ class ChangeCalculator { - **Efficiency**: This approach is highly efficient in terms of minimizing the number of coins, but it might require significant memory for larger `grandTotal` values, as the space complexity grows linearly with `grandTotal`. -- **Alternative Approaches**: +- **Alternative Approaches**: - A **Greedy Approach** could be faster for some cases but does not always guarantee the minimum number of coins. - This dynamic programming approach is best when the goal is to guarantee the fewest coins possible, especially when no simple greedy solution exists. diff --git a/exercises/practice/change/.approaches/intrduction.md b/exercises/practice/change/.approaches/intrduction.md index 84531fad3..3834d706d 100644 --- a/exercises/practice/change/.approaches/intrduction.md +++ b/exercises/practice/change/.approaches/intrduction.md @@ -2,7 +2,7 @@ In the "Change Calculator" exercise, the goal is to determine the minimum number of coins needed to reach a given total using a specific set of coin denominations. This is a classic problem in dynamic programming, where efficient change-making is essential, especially when there are constraints on coin types or large totals. -### Problem Overview +## Problem Overview Given: @@ -11,13 +11,13 @@ Given: The solution should find the optimal combination of coins to match the total. If it's impossible to match the total exactly, the solution should indicate this by throwing an exception. -### Approach Overview +## Approach Overview Our solution uses a **dynamic programming approach**, where we systematically build up the optimal combinations for all totals from `0` up to the target amount (`grandTotal`). For each total, we track the fewest coins needed to make that total, reusing previous results to make the solution efficient. This approach ensures that we find the minimum number of coins required in a structured, repeatable way, avoiding the need for complex recursive calls or excessive backtracking. -### Key Features of the Approach +## Key Features of the Approach - **Efficiency**: By building solutions for each increment up to `grandTotal`, this approach minimizes redundant calculations. - **Flexibility**: Handles cases where exact change is impossible by checking at each step. From 115a331e23500913ec0afafd2460bbad3cc25384 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 23:31:46 +0530 Subject: [PATCH 06/49] Fixing file names --- .../dynamic-programming/snippet.txt | 36 ------------------- .../{intrduction.md => introduction.md} | 0 2 files changed, 36 deletions(-) delete mode 100644 exercises/practice/change/.approaches/dynamic-programming/snippet.txt rename exercises/practice/change/.approaches/{intrduction.md => introduction.md} (100%) diff --git a/exercises/practice/change/.approaches/dynamic-programming/snippet.txt b/exercises/practice/change/.approaches/dynamic-programming/snippet.txt deleted file mode 100644 index 3bbc3ad8c..000000000 --- a/exercises/practice/change/.approaches/dynamic-programming/snippet.txt +++ /dev/null @@ -1,36 +0,0 @@ -import java.util.List; -import java.util.ArrayList; - -class ChangeCalculator { - private final List currencyCoins; - - ChangeCalculator(List currencyCoins) { - this.currencyCoins = currencyCoins; - } - - List computeMostEfficientChange(int grandTotal) { - if (grandTotal < 0) - throw new IllegalArgumentException("Negative totals are not allowed."); - - List> coinsUsed = new ArrayList<>(grandTotal + 1); - coinsUsed.add(new ArrayList()); - - for (int i = 1; i <= grandTotal; i++) { - List bestCombination = null; - for (int coin: currencyCoins) { - if (coin <= i && coinsUsed.get(i - coin) != null) { - List currentCombination = new ArrayList<>(coinsUsed.get(i - coin)); - currentCombination.add(0, coin); - if (bestCombination == null || currentCombination.size() < bestCombination.size()) - bestCombination = currentCombination; - } - } - coinsUsed.add(bestCombination); - } - - if (coinsUsed.get(grandTotal) == null) - throw new IllegalArgumentException("The total " + grandTotal + " cannot be represented in the given currency."); - - return coinsUsed.get(grandTotal); - } -} \ No newline at end of file diff --git a/exercises/practice/change/.approaches/intrduction.md b/exercises/practice/change/.approaches/introduction.md similarity index 100% rename from exercises/practice/change/.approaches/intrduction.md rename to exercises/practice/change/.approaches/introduction.md From 303523eb47cc4cfeb8ac4e5b14fe175942fbd314 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sun, 10 Nov 2024 00:21:35 +0530 Subject: [PATCH 07/49] Adding approache to Queen-Attack --- .../queen-attack/.approaches/config.json | 19 +++++ .../queen-attack/.approaches/introduction.md | 18 +++++ .../.approaches/simple-comparison/content.md | 78 +++++++++++++++++++ 3 files changed, 115 insertions(+) create mode 100644 exercises/practice/queen-attack/.approaches/config.json create mode 100644 exercises/practice/queen-attack/.approaches/introduction.md create mode 100644 exercises/practice/queen-attack/.approaches/simple-comparison/content.md diff --git a/exercises/practice/queen-attack/.approaches/config.json b/exercises/practice/queen-attack/.approaches/config.json new file mode 100644 index 000000000..20b951ff8 --- /dev/null +++ b/exercises/practice/queen-attack/.approaches/config.json @@ -0,0 +1,19 @@ +{ + "introduction": { + "authors": [ + "jagdish-15" + ] + }, + "approaches": [ + { + "uuid": "", + "slug": "simple-comparison", + "title": "Simple Comparison Approach", + "blurb": "Use basic comparison checks to determine if queens can attack each other.", + "authors": [ + "jagdish-15" + ] + } + ] + } + \ No newline at end of file diff --git a/exercises/practice/queen-attack/.approaches/introduction.md b/exercises/practice/queen-attack/.approaches/introduction.md new file mode 100644 index 000000000..06ab7be07 --- /dev/null +++ b/exercises/practice/queen-attack/.approaches/introduction.md @@ -0,0 +1,18 @@ +# Queen Attack Exercise + +In this exercise, we determine if two queens on a chessboard can attack each other based on their positions. A queen in chess can move any number of squares horizontally, vertically, or diagonally. The task is to check if two queens, placed on specific coordinates, can attack each other. + +The problem boils down to checking three conditions: +1. **Same Row**: If the queens are on the same row. +2. **Same Column**: If the queens are on the same column. +3. **Same Diagonal**: If the queens are on the same diagonal, i.e., the absolute difference between their row and column positions is equal. + +## Approach Overview + +This exercise is solved using a **Simple Comparison Approach**. By comparing the row, column, and diagonal positions of the two queens, we can easily determine if they can attack each other. + +### Why This Approach? + +The Simple Comparison Approach is chosen for its clarity and simplicity. It uses basic comparison checks to determine if two queens are in attacking positions. This method works well for small scenarios like this one, where performance isn't a major concern. + +For more details on the implementation of this approach, check out the [Simple Comparison Approach](https://exercism.org/tracks/java/exercises/queen-attack/approaches/simple-comparison). diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md new file mode 100644 index 000000000..bc5a5c5b6 --- /dev/null +++ b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md @@ -0,0 +1,78 @@ +# Queen Attack Approach + +In this exercise, we determine if two queens on a chessboard can attack each other based on their positions. A queen can attack another queen if they are on the same row, column, or diagonal. + +## Approach Steps + +1. **Check if Queens are on the Same Row**: + - If both queens are on the same row, they can attack each other. This is checked by comparing their row values: + ```java + if (queen1.getRow() == queen2.getRow()) { + return true; + } + ``` + +2. **Check if Queens are on the Same Column**: + - If both queens are on the same column, they can attack each other. This is checked by comparing their column values: + ```java + if (queen1.getColumn() == queen2.getColumn()) { + return true; + } + ``` + +3. **Check if Queens are on the Same Diagonal**: + - If both queens are on the same diagonal, they can attack each other. This is checked by comparing the absolute difference between their row and column values: + ```java + if (Math.abs(queen1.getRow() - queen2.getRow()) == Math.abs(queen1.getColumn() - queen2.getColumn())) { + return true; + } + ``` + +4. **Return the Result**: + - If any of the above checks return `true`, the queens can attack each other. Otherwise, they cannot. + +## Explanation + +- **Row Check**: We first check if the queens are in the same row. If they are, they can attack each other. +- **Column Check**: Next, we check if the queens are in the same column. If they are, they can attack each other. +- **Diagonal Check**: Lastly, we check if the queens are positioned on the same diagonal. This is determined by comparing the absolute differences in their row and column positions. +- **Final Decision**: If any of these checks return `true`, the queens can attack each other. If none of these conditions are met, they cannot attack each other. + +## Full Code Implementation + +```java +class QueenAttackCalculator { + private final Queen queen1; + private final Queen queen2; + + QueenAttackCalculator(Queen queen1, Queen queen2) { + if (queen1 == null || queen2 == null) { + throw new IllegalArgumentException("You must supply valid positions for both Queens."); + } + if (queen1.getRow() == queen2.getRow() && queen1.getColumn() == queen2.getColumn()) { + throw new IllegalArgumentException("Queens cannot occupy the same position."); + } + this.queen1 = queen1; + this.queen2 = queen2; + } + + boolean canQueensAttackOneAnother() { + int rowDifference = Math.abs(queen1.getRow() - queen2.getRow()); + int columnDifference = Math.abs(queen1.getColumn() - queen2.getColumn()); + return rowDifference == 0 || columnDifference == 0 || rowDifference == columnDifference; + } +} +``` + +## Additional Explanation for Code: + +1. **Constructor**: + In the constructor of `QueenAttackCalculator`, we check if the queens are positioned at valid places. If either queen is `null`, or if both queens occupy the same position, an exception is thrown. The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables. + +2. **Method (`canQueensAttackOneAnother`)**: + + - This method computes the row and column differences between the two queens and then checks: + - If the row difference is zero (queens are on the same row). + - If the column difference is zero (queens are on the same column). + - If the row and column differences are equal (queens are on the same diagonal). + - If any of these checks are true, the method returns `true`, indicating that the queens can attack each other. From 80c4de01f687e8299fe0599e3af1dbc3c9f36a40 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sun, 10 Nov 2024 00:29:25 +0530 Subject: [PATCH 08/49] Fixing style errors --- exercises/practice/queen-attack/.approaches/introduction.md | 1 + .../queen-attack/.approaches/simple-comparison/content.md | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/exercises/practice/queen-attack/.approaches/introduction.md b/exercises/practice/queen-attack/.approaches/introduction.md index 06ab7be07..0f1eb1983 100644 --- a/exercises/practice/queen-attack/.approaches/introduction.md +++ b/exercises/practice/queen-attack/.approaches/introduction.md @@ -3,6 +3,7 @@ In this exercise, we determine if two queens on a chessboard can attack each other based on their positions. A queen in chess can move any number of squares horizontally, vertically, or diagonally. The task is to check if two queens, placed on specific coordinates, can attack each other. The problem boils down to checking three conditions: + 1. **Same Row**: If the queens are on the same row. 2. **Same Column**: If the queens are on the same column. 3. **Same Diagonal**: If the queens are on the same diagonal, i.e., the absolute difference between their row and column positions is equal. diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md index bc5a5c5b6..fa9fcb1a4 100644 --- a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md +++ b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md @@ -6,6 +6,7 @@ In this exercise, we determine if two queens on a chessboard can attack each oth 1. **Check if Queens are on the Same Row**: - If both queens are on the same row, they can attack each other. This is checked by comparing their row values: + ```java if (queen1.getRow() == queen2.getRow()) { return true; @@ -14,6 +15,7 @@ In this exercise, we determine if two queens on a chessboard can attack each oth 2. **Check if Queens are on the Same Column**: - If both queens are on the same column, they can attack each other. This is checked by comparing their column values: + ```java if (queen1.getColumn() == queen2.getColumn()) { return true; @@ -22,6 +24,7 @@ In this exercise, we determine if two queens on a chessboard can attack each oth 3. **Check if Queens are on the Same Diagonal**: - If both queens are on the same diagonal, they can attack each other. This is checked by comparing the absolute difference between their row and column values: + ```java if (Math.abs(queen1.getRow() - queen2.getRow()) == Math.abs(queen1.getColumn() - queen2.getColumn())) { return true; @@ -64,7 +67,7 @@ class QueenAttackCalculator { } ``` -## Additional Explanation for Code: +## Additional Explanation for Code 1. **Constructor**: In the constructor of `QueenAttackCalculator`, we check if the queens are positioned at valid places. If either queen is `null`, or if both queens occupy the same position, an exception is thrown. The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables. From db874386b4be0147b35da579748341a805fb450a Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sun, 10 Nov 2024 00:30:59 +0530 Subject: [PATCH 09/49] Fixing style errors --- .../queen-attack/.approaches/simple-comparison/content.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md index fa9fcb1a4..efc3dbe00 100644 --- a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md +++ b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md @@ -69,7 +69,7 @@ class QueenAttackCalculator { ## Additional Explanation for Code -1. **Constructor**: +1. **Constructor**: In the constructor of `QueenAttackCalculator`, we check if the queens are positioned at valid places. If either queen is `null`, or if both queens occupy the same position, an exception is thrown. The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables. 2. **Method (`canQueensAttackOneAnother`)**: From e0f7eb53db7b8581314958e20398d469da450d92 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Thu, 14 Nov 2024 23:20:40 +0530 Subject: [PATCH 10/49] Adding uuid for approach of queen-attack exercise --- .../queen-attack/.approaches/config.json | 29 +++++++++---------- .../.approaches/simple-comparison/snippet.txt | 5 ++++ 2 files changed, 19 insertions(+), 15 deletions(-) create mode 100644 exercises/practice/queen-attack/.approaches/simple-comparison/snippet.txt diff --git a/exercises/practice/queen-attack/.approaches/config.json b/exercises/practice/queen-attack/.approaches/config.json index 20b951ff8..fbfa109a1 100644 --- a/exercises/practice/queen-attack/.approaches/config.json +++ b/exercises/practice/queen-attack/.approaches/config.json @@ -1,19 +1,18 @@ { - "introduction": { + "introduction": { + "authors": [ + "jagdish-15" + ] + }, + "approaches": [ + { + "uuid": "b2e474c8-b778-41e7-83c0-8e41cc84af9e", + "slug": "simple-comparison", + "title": "Simple Comparison Approach", + "blurb": "Use basic comparison checks to determine if queens can attack each other.", "authors": [ "jagdish-15" ] - }, - "approaches": [ - { - "uuid": "", - "slug": "simple-comparison", - "title": "Simple Comparison Approach", - "blurb": "Use basic comparison checks to determine if queens can attack each other.", - "authors": [ - "jagdish-15" - ] - } - ] - } - \ No newline at end of file + } + ] +} diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/snippet.txt b/exercises/practice/queen-attack/.approaches/simple-comparison/snippet.txt new file mode 100644 index 000000000..90f224025 --- /dev/null +++ b/exercises/practice/queen-attack/.approaches/simple-comparison/snippet.txt @@ -0,0 +1,5 @@ +boolean canQueensAttackOneAnother() { + int rowDifference = Math.abs(queen1.getRow() - queen2.getRow()); + int columnDifference = Math.abs(queen1.getColumn() - queen2.getColumn()); + return rowDifference == 0 || columnDifference == 0 || rowDifference == columnDifference; +} \ No newline at end of file From d2c24511394e6dd4f2be9cbf1adfabf86aedadf7 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Thu, 14 Nov 2024 23:25:31 +0530 Subject: [PATCH 11/49] Adding uuid for approach of change --- exercises/practice/change/.approaches/config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/change/.approaches/config.json b/exercises/practice/change/.approaches/config.json index 78950cae5..f9b602eb2 100644 --- a/exercises/practice/change/.approaches/config.json +++ b/exercises/practice/change/.approaches/config.json @@ -6,7 +6,7 @@ }, "approaches": [ { - "uuid": "", + "uuid": "d0b615ca-3a02-4d66-ad10-e0c513062189", "slug": "dynamic-programming", "title": "Dynamic Programming Approach", "blurb": "Use dynamic programming to find the most efficient change combination.", From b3a98dfc6021b4313ed330daf288471b7fc3bcca Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Thu, 14 Nov 2024 23:27:08 +0530 Subject: [PATCH 12/49] Adding snippet for approach of change --- .../change/.approaches/dynamic-programming/snippet.txt | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 exercises/practice/change/.approaches/dynamic-programming/snippet.txt diff --git a/exercises/practice/change/.approaches/dynamic-programming/snippet.txt b/exercises/practice/change/.approaches/dynamic-programming/snippet.txt new file mode 100644 index 000000000..25f90e6f5 --- /dev/null +++ b/exercises/practice/change/.approaches/dynamic-programming/snippet.txt @@ -0,0 +1,8 @@ +class ChangeCalculator { + private final List currencyCoins; + + ChangeCalculator(List currencyCoins) { + this.currencyCoins = currencyCoins; + } + // computeMostEfficientChange method +} From 2d683d86f80669446498d60cf328942bee6f2fec Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sun, 10 Nov 2024 00:21:35 +0530 Subject: [PATCH 13/49] Adding approache to Queen-Attack --- .../queen-attack/.approaches/config.json | 19 +++++ .../queen-attack/.approaches/introduction.md | 18 +++++ .../.approaches/simple-comparison/content.md | 78 +++++++++++++++++++ 3 files changed, 115 insertions(+) create mode 100644 exercises/practice/queen-attack/.approaches/config.json create mode 100644 exercises/practice/queen-attack/.approaches/introduction.md create mode 100644 exercises/practice/queen-attack/.approaches/simple-comparison/content.md diff --git a/exercises/practice/queen-attack/.approaches/config.json b/exercises/practice/queen-attack/.approaches/config.json new file mode 100644 index 000000000..20b951ff8 --- /dev/null +++ b/exercises/practice/queen-attack/.approaches/config.json @@ -0,0 +1,19 @@ +{ + "introduction": { + "authors": [ + "jagdish-15" + ] + }, + "approaches": [ + { + "uuid": "", + "slug": "simple-comparison", + "title": "Simple Comparison Approach", + "blurb": "Use basic comparison checks to determine if queens can attack each other.", + "authors": [ + "jagdish-15" + ] + } + ] + } + \ No newline at end of file diff --git a/exercises/practice/queen-attack/.approaches/introduction.md b/exercises/practice/queen-attack/.approaches/introduction.md new file mode 100644 index 000000000..06ab7be07 --- /dev/null +++ b/exercises/practice/queen-attack/.approaches/introduction.md @@ -0,0 +1,18 @@ +# Queen Attack Exercise + +In this exercise, we determine if two queens on a chessboard can attack each other based on their positions. A queen in chess can move any number of squares horizontally, vertically, or diagonally. The task is to check if two queens, placed on specific coordinates, can attack each other. + +The problem boils down to checking three conditions: +1. **Same Row**: If the queens are on the same row. +2. **Same Column**: If the queens are on the same column. +3. **Same Diagonal**: If the queens are on the same diagonal, i.e., the absolute difference between their row and column positions is equal. + +## Approach Overview + +This exercise is solved using a **Simple Comparison Approach**. By comparing the row, column, and diagonal positions of the two queens, we can easily determine if they can attack each other. + +### Why This Approach? + +The Simple Comparison Approach is chosen for its clarity and simplicity. It uses basic comparison checks to determine if two queens are in attacking positions. This method works well for small scenarios like this one, where performance isn't a major concern. + +For more details on the implementation of this approach, check out the [Simple Comparison Approach](https://exercism.org/tracks/java/exercises/queen-attack/approaches/simple-comparison). diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md new file mode 100644 index 000000000..bc5a5c5b6 --- /dev/null +++ b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md @@ -0,0 +1,78 @@ +# Queen Attack Approach + +In this exercise, we determine if two queens on a chessboard can attack each other based on their positions. A queen can attack another queen if they are on the same row, column, or diagonal. + +## Approach Steps + +1. **Check if Queens are on the Same Row**: + - If both queens are on the same row, they can attack each other. This is checked by comparing their row values: + ```java + if (queen1.getRow() == queen2.getRow()) { + return true; + } + ``` + +2. **Check if Queens are on the Same Column**: + - If both queens are on the same column, they can attack each other. This is checked by comparing their column values: + ```java + if (queen1.getColumn() == queen2.getColumn()) { + return true; + } + ``` + +3. **Check if Queens are on the Same Diagonal**: + - If both queens are on the same diagonal, they can attack each other. This is checked by comparing the absolute difference between their row and column values: + ```java + if (Math.abs(queen1.getRow() - queen2.getRow()) == Math.abs(queen1.getColumn() - queen2.getColumn())) { + return true; + } + ``` + +4. **Return the Result**: + - If any of the above checks return `true`, the queens can attack each other. Otherwise, they cannot. + +## Explanation + +- **Row Check**: We first check if the queens are in the same row. If they are, they can attack each other. +- **Column Check**: Next, we check if the queens are in the same column. If they are, they can attack each other. +- **Diagonal Check**: Lastly, we check if the queens are positioned on the same diagonal. This is determined by comparing the absolute differences in their row and column positions. +- **Final Decision**: If any of these checks return `true`, the queens can attack each other. If none of these conditions are met, they cannot attack each other. + +## Full Code Implementation + +```java +class QueenAttackCalculator { + private final Queen queen1; + private final Queen queen2; + + QueenAttackCalculator(Queen queen1, Queen queen2) { + if (queen1 == null || queen2 == null) { + throw new IllegalArgumentException("You must supply valid positions for both Queens."); + } + if (queen1.getRow() == queen2.getRow() && queen1.getColumn() == queen2.getColumn()) { + throw new IllegalArgumentException("Queens cannot occupy the same position."); + } + this.queen1 = queen1; + this.queen2 = queen2; + } + + boolean canQueensAttackOneAnother() { + int rowDifference = Math.abs(queen1.getRow() - queen2.getRow()); + int columnDifference = Math.abs(queen1.getColumn() - queen2.getColumn()); + return rowDifference == 0 || columnDifference == 0 || rowDifference == columnDifference; + } +} +``` + +## Additional Explanation for Code: + +1. **Constructor**: + In the constructor of `QueenAttackCalculator`, we check if the queens are positioned at valid places. If either queen is `null`, or if both queens occupy the same position, an exception is thrown. The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables. + +2. **Method (`canQueensAttackOneAnother`)**: + + - This method computes the row and column differences between the two queens and then checks: + - If the row difference is zero (queens are on the same row). + - If the column difference is zero (queens are on the same column). + - If the row and column differences are equal (queens are on the same diagonal). + - If any of these checks are true, the method returns `true`, indicating that the queens can attack each other. From d19f7bf1a518d5986ccc957bc192b269de537fdc Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sun, 10 Nov 2024 00:29:25 +0530 Subject: [PATCH 14/49] Fixing style errors --- exercises/practice/queen-attack/.approaches/introduction.md | 1 + .../queen-attack/.approaches/simple-comparison/content.md | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/exercises/practice/queen-attack/.approaches/introduction.md b/exercises/practice/queen-attack/.approaches/introduction.md index 06ab7be07..0f1eb1983 100644 --- a/exercises/practice/queen-attack/.approaches/introduction.md +++ b/exercises/practice/queen-attack/.approaches/introduction.md @@ -3,6 +3,7 @@ In this exercise, we determine if two queens on a chessboard can attack each other based on their positions. A queen in chess can move any number of squares horizontally, vertically, or diagonally. The task is to check if two queens, placed on specific coordinates, can attack each other. The problem boils down to checking three conditions: + 1. **Same Row**: If the queens are on the same row. 2. **Same Column**: If the queens are on the same column. 3. **Same Diagonal**: If the queens are on the same diagonal, i.e., the absolute difference between their row and column positions is equal. diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md index bc5a5c5b6..fa9fcb1a4 100644 --- a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md +++ b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md @@ -6,6 +6,7 @@ In this exercise, we determine if two queens on a chessboard can attack each oth 1. **Check if Queens are on the Same Row**: - If both queens are on the same row, they can attack each other. This is checked by comparing their row values: + ```java if (queen1.getRow() == queen2.getRow()) { return true; @@ -14,6 +15,7 @@ In this exercise, we determine if two queens on a chessboard can attack each oth 2. **Check if Queens are on the Same Column**: - If both queens are on the same column, they can attack each other. This is checked by comparing their column values: + ```java if (queen1.getColumn() == queen2.getColumn()) { return true; @@ -22,6 +24,7 @@ In this exercise, we determine if two queens on a chessboard can attack each oth 3. **Check if Queens are on the Same Diagonal**: - If both queens are on the same diagonal, they can attack each other. This is checked by comparing the absolute difference between their row and column values: + ```java if (Math.abs(queen1.getRow() - queen2.getRow()) == Math.abs(queen1.getColumn() - queen2.getColumn())) { return true; @@ -64,7 +67,7 @@ class QueenAttackCalculator { } ``` -## Additional Explanation for Code: +## Additional Explanation for Code 1. **Constructor**: In the constructor of `QueenAttackCalculator`, we check if the queens are positioned at valid places. If either queen is `null`, or if both queens occupy the same position, an exception is thrown. The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables. From 418ddb57a4e531724b1511b7d960287864769ee1 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sun, 10 Nov 2024 00:30:59 +0530 Subject: [PATCH 15/49] Fixing style errors --- .../queen-attack/.approaches/simple-comparison/content.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md index fa9fcb1a4..efc3dbe00 100644 --- a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md +++ b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md @@ -69,7 +69,7 @@ class QueenAttackCalculator { ## Additional Explanation for Code -1. **Constructor**: +1. **Constructor**: In the constructor of `QueenAttackCalculator`, we check if the queens are positioned at valid places. If either queen is `null`, or if both queens occupy the same position, an exception is thrown. The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables. 2. **Method (`canQueensAttackOneAnother`)**: From c8acf184511ae4d7e1be1f02a71d92ca10060149 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Thu, 14 Nov 2024 23:20:40 +0530 Subject: [PATCH 16/49] Adding uuid for approach of queen-attack exercise --- .../queen-attack/.approaches/config.json | 29 +++++++++---------- .../.approaches/simple-comparison/snippet.txt | 5 ++++ 2 files changed, 19 insertions(+), 15 deletions(-) create mode 100644 exercises/practice/queen-attack/.approaches/simple-comparison/snippet.txt diff --git a/exercises/practice/queen-attack/.approaches/config.json b/exercises/practice/queen-attack/.approaches/config.json index 20b951ff8..fbfa109a1 100644 --- a/exercises/practice/queen-attack/.approaches/config.json +++ b/exercises/practice/queen-attack/.approaches/config.json @@ -1,19 +1,18 @@ { - "introduction": { + "introduction": { + "authors": [ + "jagdish-15" + ] + }, + "approaches": [ + { + "uuid": "b2e474c8-b778-41e7-83c0-8e41cc84af9e", + "slug": "simple-comparison", + "title": "Simple Comparison Approach", + "blurb": "Use basic comparison checks to determine if queens can attack each other.", "authors": [ "jagdish-15" ] - }, - "approaches": [ - { - "uuid": "", - "slug": "simple-comparison", - "title": "Simple Comparison Approach", - "blurb": "Use basic comparison checks to determine if queens can attack each other.", - "authors": [ - "jagdish-15" - ] - } - ] - } - \ No newline at end of file + } + ] +} diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/snippet.txt b/exercises/practice/queen-attack/.approaches/simple-comparison/snippet.txt new file mode 100644 index 000000000..90f224025 --- /dev/null +++ b/exercises/practice/queen-attack/.approaches/simple-comparison/snippet.txt @@ -0,0 +1,5 @@ +boolean canQueensAttackOneAnother() { + int rowDifference = Math.abs(queen1.getRow() - queen2.getRow()); + int columnDifference = Math.abs(queen1.getColumn() - queen2.getColumn()); + return rowDifference == 0 || columnDifference == 0 || rowDifference == columnDifference; +} \ No newline at end of file From 94383250b3de52c49fd4b5d06d760331ac6a8ebd Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Fri, 15 Nov 2024 21:42:42 +0530 Subject: [PATCH 17/49] Updating approach files --- .../practice/change/.approaches/config.json | 2 +- .../dynamic-programming/content.md | 57 ++++++++----------- .../change/.approaches/introduction.md | 25 ++++---- 3 files changed, 39 insertions(+), 45 deletions(-) diff --git a/exercises/practice/change/.approaches/config.json b/exercises/practice/change/.approaches/config.json index f9b602eb2..00716db81 100644 --- a/exercises/practice/change/.approaches/config.json +++ b/exercises/practice/change/.approaches/config.json @@ -14,7 +14,7 @@ "jagdish-15" ], "contributors": [ - "kagoh" + "kahgoh" ] } ] diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index cce152a0b..4277c61ff 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -1,27 +1,5 @@ # Dynamic Programming Approach -The **Dynamic Programming (DP)** approach is an efficient way to solve the problem of making change for a given total using a list of available coin denominations. It minimizes the number of coins needed by breaking down the problem into smaller subproblems and solving them progressively. - -This approach ensures that we find the most efficient way to make change and handles edge cases where no solution exists. - -## Explanation - -1. **Initialize Coins Usage Tracker**: - - - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. - - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. - -2. **Iterative Dynamic Programming**: - - - For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. - - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). - - If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. - -3. **Result**: - - - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. - - If no valid combination exists for `grandTotal`, an exception is thrown. - ```java import java.util.List; import java.util.ArrayList; @@ -61,6 +39,29 @@ class ChangeCalculator { } ``` +The **Dynamic Programming (DP)** approach is an efficient way to solve the problem of making change for a given total using a list of available coin denominations. +It minimizes the number of coins needed by breaking down the problem into smaller subproblems and solving them progressively. + +This approach ensures that we find the most efficient way to make change and handles edge cases where no solution exists. + +## Explanation + +1. **Initialize Coins Usage Tracker**: + + - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. + - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. + +2. **Iterative Dynamic Programming**: + + - For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. + - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). + - If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. + +3. **Result**: + + - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. + - If no valid combination exists for `grandTotal`, an exception is thrown. + ## Key Points - **Time Complexity**: The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. @@ -72,15 +73,7 @@ class ChangeCalculator { - If the `grandTotal` is negative, an exception is thrown immediately. - If there is no way to make the exact total with the given denominations, an exception is thrown with a descriptive message. -## Trade-offs and Considerations - -- **Efficiency**: This approach is highly efficient in terms of minimizing the number of coins, but it might require significant memory for larger `grandTotal` values, as the space complexity grows linearly with `grandTotal`. - -- **Alternative Approaches**: - - - A **Greedy Approach** could be faster for some cases but does not always guarantee the minimum number of coins. - - This dynamic programming approach is best when the goal is to guarantee the fewest coins possible, especially when no simple greedy solution exists. - ## Conclusion -The dynamic programming approach provides an optimal solution for the change-making problem, ensuring that we minimize the number of coins used while efficiently solving the problem for any `grandTotal`. However, it’s essential to consider the trade-offs in terms of memory usage and the time complexity when dealing with very large inputs. +The dynamic programming approach provides an optimal solution for the change-making problem, ensuring that we minimize the number of coins used while efficiently solving the problem for any `grandTotal`. +However, it’s essential to consider the trade-offs in terms of memory usage and the time complexity when dealing with very large inputs. diff --git a/exercises/practice/change/.approaches/introduction.md b/exercises/practice/change/.approaches/introduction.md index 3834d706d..713e5070f 100644 --- a/exercises/practice/change/.approaches/introduction.md +++ b/exercises/practice/change/.approaches/introduction.md @@ -1,19 +1,17 @@ -# Introduction to Change Calculator +# Introduction -In the "Change Calculator" exercise, the goal is to determine the minimum number of coins needed to reach a given total using a specific set of coin denominations. This is a classic problem in dynamic programming, where efficient change-making is essential, especially when there are constraints on coin types or large totals. +There is an idiomatic approach to solving "Change." +You can use [dynamic programming][dynamic-programming] to calculate the minimum number of coins required for a given total. -## Problem Overview +## General guidance -Given: +The key to solving "Change" is understanding that not all totals can be reached with the available coin denominations. +The solution needs to figure out which totals can be achieved and how to combine the coins optimally. -- A list of coin denominations, each representing an available currency unit. -- A total amount (`grandTotal`) we want to reach using the fewest possible coins from the given denominations. +## Approach: Dynamic Programming -The solution should find the optimal combination of coins to match the total. If it's impossible to match the total exactly, the solution should indicate this by throwing an exception. - -## Approach Overview - -Our solution uses a **dynamic programming approach**, where we systematically build up the optimal combinations for all totals from `0` up to the target amount (`grandTotal`). For each total, we track the fewest coins needed to make that total, reusing previous results to make the solution efficient. +Our solution uses a **dynamic programming approach**, where we systematically build up the optimal combinations for all totals from `0` up to the target amount (`grandTotal`). +For each total, we track the fewest coins needed to make that total, reusing previous results to make the solution efficient. This approach ensures that we find the minimum number of coins required in a structured, repeatable way, avoiding the need for complex recursive calls or excessive backtracking. @@ -23,4 +21,7 @@ This approach ensures that we find the minimum number of coins required in a str - **Flexibility**: Handles cases where exact change is impossible by checking at each step. - **Scalability**: Works for various coin denominations and totals, though large inputs may impact performance. -For a detailed look at the code and logic, see the full explanation in the [approach file](https://exercism.org/tracks/java/exercises/change/approaches/dynamic-programming). +For a detailed look at the code and logic, see the full explanation in the [Dynamic Programming Approach][approach-dynamic-programming]. + +[approach-dynamic-programming]: https://exercism.org/tracks/java/exercises/change/approaches/dynamic-programming +[dynamic-programming]: https://en.wikipedia.org/wiki/Dynamic_programming \ No newline at end of file From fde837b7eb8b5a1c835b2563a259e1d4b0f71ead Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Fri, 15 Nov 2024 21:45:08 +0530 Subject: [PATCH 18/49] Fixing styling errors --- exercises/practice/change/.approaches/introduction.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/change/.approaches/introduction.md b/exercises/practice/change/.approaches/introduction.md index 713e5070f..49100bf51 100644 --- a/exercises/practice/change/.approaches/introduction.md +++ b/exercises/practice/change/.approaches/introduction.md @@ -24,4 +24,4 @@ This approach ensures that we find the minimum number of coins required in a str For a detailed look at the code and logic, see the full explanation in the [Dynamic Programming Approach][approach-dynamic-programming]. [approach-dynamic-programming]: https://exercism.org/tracks/java/exercises/change/approaches/dynamic-programming -[dynamic-programming]: https://en.wikipedia.org/wiki/Dynamic_programming \ No newline at end of file +[dynamic-programming]: https://en.wikipedia.org/wiki/Dynamic_programming From dd94b36ce5cce1e4016d3dba6f97fddff294bbcb Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Fri, 15 Nov 2024 23:14:09 +0530 Subject: [PATCH 19/49] Fixing minor issues --- .../queen-attack/.approaches/introduction.md | 19 +++++-- .../.approaches/simple-comparison/content.md | 55 +++++++++---------- 2 files changed, 41 insertions(+), 33 deletions(-) diff --git a/exercises/practice/queen-attack/.approaches/introduction.md b/exercises/practice/queen-attack/.approaches/introduction.md index 0f1eb1983..48cede57a 100644 --- a/exercises/practice/queen-attack/.approaches/introduction.md +++ b/exercises/practice/queen-attack/.approaches/introduction.md @@ -1,6 +1,10 @@ # Queen Attack Exercise -In this exercise, we determine if two queens on a chessboard can attack each other based on their positions. A queen in chess can move any number of squares horizontally, vertically, or diagonally. The task is to check if two queens, placed on specific coordinates, can attack each other. +In this exercise, we determine if two queens on a chessboard can attack each other based on their positions. +A queen in chess can move any number of squares horizontally, vertically, or diagonally. +The task is to check if two queens, placed on specific coordinates, can attack each other. + +## Genral Advice The problem boils down to checking three conditions: @@ -8,12 +12,17 @@ The problem boils down to checking three conditions: 2. **Same Column**: If the queens are on the same column. 3. **Same Diagonal**: If the queens are on the same diagonal, i.e., the absolute difference between their row and column positions is equal. -## Approach Overview +## Approach: Simple Comparison Approach -This exercise is solved using a **Simple Comparison Approach**. By comparing the row, column, and diagonal positions of the two queens, we can easily determine if they can attack each other. +This exercise is solved using a **Simple Comparison Approach**. +By comparing the row, column, and diagonal positions of the two queens, we can easily determine if they can attack each other. ### Why This Approach? -The Simple Comparison Approach is chosen for its clarity and simplicity. It uses basic comparison checks to determine if two queens are in attacking positions. This method works well for small scenarios like this one, where performance isn't a major concern. +The Simple Comparison Approach is chosen for its clarity and simplicity. +It uses basic comparison checks to determine if two queens are in attacking positions. +This method works well for small scenarios like this one, where performance isn't a major concern. + +For more details on the implementation of this approach, check out the [Simple Comparison Approach][simple-comparison-approach]. -For more details on the implementation of this approach, check out the [Simple Comparison Approach](https://exercism.org/tracks/java/exercises/queen-attack/approaches/simple-comparison). +[simple-comparison-approach]: https://exercism.org/tracks/java/exercises/queen-attack/approaches/simple-comparison diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md index efc3dbe00..a29d18e92 100644 --- a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md +++ b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md @@ -1,6 +1,28 @@ # Queen Attack Approach -In this exercise, we determine if two queens on a chessboard can attack each other based on their positions. A queen can attack another queen if they are on the same row, column, or diagonal. +```java +class QueenAttackCalculator { + private final Queen queen1; + private final Queen queen2; + + QueenAttackCalculator(Queen queen1, Queen queen2) { + if (queen1 == null || queen2 == null) { + throw new IllegalArgumentException("You must supply valid positions for both Queens."); + } + if (queen1.getRow() == queen2.getRow() && queen1.getColumn() == queen2.getColumn()) { + throw new IllegalArgumentException("Queens cannot occupy the same position."); + } + this.queen1 = queen1; + this.queen2 = queen2; + } + + boolean canQueensAttackOneAnother() { + int rowDifference = Math.abs(queen1.getRow() - queen2.getRow()); + int columnDifference = Math.abs(queen1.getColumn() - queen2.getColumn()); + return rowDifference == 0 || columnDifference == 0 || rowDifference == columnDifference; + } +} +``` ## Approach Steps @@ -41,36 +63,13 @@ In this exercise, we determine if two queens on a chessboard can attack each oth - **Diagonal Check**: Lastly, we check if the queens are positioned on the same diagonal. This is determined by comparing the absolute differences in their row and column positions. - **Final Decision**: If any of these checks return `true`, the queens can attack each other. If none of these conditions are met, they cannot attack each other. -## Full Code Implementation - -```java -class QueenAttackCalculator { - private final Queen queen1; - private final Queen queen2; - - QueenAttackCalculator(Queen queen1, Queen queen2) { - if (queen1 == null || queen2 == null) { - throw new IllegalArgumentException("You must supply valid positions for both Queens."); - } - if (queen1.getRow() == queen2.getRow() && queen1.getColumn() == queen2.getColumn()) { - throw new IllegalArgumentException("Queens cannot occupy the same position."); - } - this.queen1 = queen1; - this.queen2 = queen2; - } - - boolean canQueensAttackOneAnother() { - int rowDifference = Math.abs(queen1.getRow() - queen2.getRow()); - int columnDifference = Math.abs(queen1.getColumn() - queen2.getColumn()); - return rowDifference == 0 || columnDifference == 0 || rowDifference == columnDifference; - } -} -``` - ## Additional Explanation for Code 1. **Constructor**: - In the constructor of `QueenAttackCalculator`, we check if the queens are positioned at valid places. If either queen is `null`, or if both queens occupy the same position, an exception is thrown. The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables. + + In the constructor of `QueenAttackCalculator`, we check if the queens are positioned at valid places. + If either queen is `null`, or if both queens occupy the same position, an exception is thrown. + The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables. 2. **Method (`canQueensAttackOneAnother`)**: From 31ace8aecd9fc8720f97118628ad7cceed18c018 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Fri, 15 Nov 2024 23:20:56 +0530 Subject: [PATCH 20/49] Fixing styling issues --- exercises/practice/queen-attack/.approaches/introduction.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/queen-attack/.approaches/introduction.md b/exercises/practice/queen-attack/.approaches/introduction.md index 48cede57a..5fbfaefb9 100644 --- a/exercises/practice/queen-attack/.approaches/introduction.md +++ b/exercises/practice/queen-attack/.approaches/introduction.md @@ -4,7 +4,7 @@ In this exercise, we determine if two queens on a chessboard can attack each oth A queen in chess can move any number of squares horizontally, vertically, or diagonally. The task is to check if two queens, placed on specific coordinates, can attack each other. -## Genral Advice +## Genral Advice The problem boils down to checking three conditions: From 3a0a219da0f5a4b68ceda630fdef21110d2f5368 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 16 Nov 2024 00:52:48 +0530 Subject: [PATCH 21/49] Syncing with problem-specification --- exercises/practice/yacht/.meta/config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/yacht/.meta/config.json b/exercises/practice/yacht/.meta/config.json index 122b450c0..971e3587d 100644 --- a/exercises/practice/yacht/.meta/config.json +++ b/exercises/practice/yacht/.meta/config.json @@ -29,6 +29,6 @@ ] }, "blurb": "Score a single throw of dice in the game Yacht.", - "source": "James Kilfiger, using wikipedia", + "source": "James Kilfiger, using Wikipedia", "source_url": "https://en.wikipedia.org/wiki/Yacht_(dice_game)" } From 7ec29607ea117ec671e7840e41fa8e0f5d726461 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 22:53:33 +0530 Subject: [PATCH 22/49] Adding approach change --- .../practice/change/.approaches/config,json | 21 +++++ .../dynamic-programming/content.md | 82 +++++++++++++++++++ .../dynamic-programming/snippet.txt | 36 ++++++++ .../change/.approaches/intrduction.md | 25 ++++++ 4 files changed, 164 insertions(+) create mode 100644 exercises/practice/change/.approaches/config,json create mode 100644 exercises/practice/change/.approaches/dynamic-programming/content.md create mode 100644 exercises/practice/change/.approaches/dynamic-programming/snippet.txt create mode 100644 exercises/practice/change/.approaches/intrduction.md diff --git a/exercises/practice/change/.approaches/config,json b/exercises/practice/change/.approaches/config,json new file mode 100644 index 000000000..78950cae5 --- /dev/null +++ b/exercises/practice/change/.approaches/config,json @@ -0,0 +1,21 @@ +{ + "introduction": { + "authors": [ + "jagdish-15" + ] + }, + "approaches": [ + { + "uuid": "", + "slug": "dynamic-programming", + "title": "Dynamic Programming Approach", + "blurb": "Use dynamic programming to find the most efficient change combination.", + "authors": [ + "jagdish-15" + ], + "contributors": [ + "kagoh" + ] + } + ] +} diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md new file mode 100644 index 000000000..38e8376f5 --- /dev/null +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -0,0 +1,82 @@ +# Dynamic Programming Approach + +The **Dynamic Programming (DP)** approach is an efficient way to solve the problem of making change for a given total using a list of available coin denominations. It minimizes the number of coins needed by breaking down the problem into smaller subproblems and solving them progressively. + +This approach ensures that we find the most efficient way to make change and handles edge cases where no solution exists. + +## Explanation + +1. **Initialize Coins Usage Tracker**: + - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. + - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. + +2. **Iterative Dynamic Programming**: + - For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. + - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). + - If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. + +3. **Result**: + - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. + - If no valid combination exists for `grandTotal`, an exception is thrown. + + +```java +import java.util.List; +import java.util.ArrayList; + +class ChangeCalculator { + private final List currencyCoins; + + ChangeCalculator(List currencyCoins) { + this.currencyCoins = currencyCoins; + } + + List computeMostEfficientChange(int grandTotal) { + if (grandTotal < 0) + throw new IllegalArgumentException("Negative totals are not allowed."); + + List> coinsUsed = new ArrayList<>(grandTotal + 1); + coinsUsed.add(new ArrayList()); + + for (int i = 1; i <= grandTotal; i++) { + List bestCombination = null; + for (int coin: currencyCoins) { + if (coin <= i && coinsUsed.get(i - coin) != null) { + List currentCombination = new ArrayList<>(coinsUsed.get(i - coin)); + currentCombination.add(0, coin); + if (bestCombination == null || currentCombination.size() < bestCombination.size()) + bestCombination = currentCombination; + } + } + coinsUsed.add(bestCombination); + } + + if (coinsUsed.get(grandTotal) == null) + throw new IllegalArgumentException("The total " + grandTotal + " cannot be represented in the given currency."); + + return coinsUsed.get(grandTotal); + } +} +``` + +## Key Points + +- **Time Complexity**: The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. + +- **Space Complexity**: The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. + +- **Edge Cases**: + - If the `grandTotal` is negative, an exception is thrown immediately. + - If there is no way to make the exact total with the given denominations, an exception is thrown with a descriptive message. + +## Trade-offs and Considerations + +- **Efficiency**: This approach is highly efficient in terms of minimizing the number of coins, but it might require significant memory for larger `grandTotal` values, as the space complexity grows linearly with `grandTotal`. + +- **Alternative Approaches**: + - A **Greedy Approach** could be faster for some cases but does not always guarantee the minimum number of coins. + - This dynamic programming approach is best when the goal is to guarantee the fewest coins possible, especially when no simple greedy solution exists. + +## Conclusion + +The dynamic programming approach provides an optimal solution for the change-making problem, ensuring that we minimize the number of coins used while efficiently solving the problem for any `grandTotal`. However, it’s essential to consider the trade-offs in terms of memory usage and the time complexity when dealing with very large inputs. diff --git a/exercises/practice/change/.approaches/dynamic-programming/snippet.txt b/exercises/practice/change/.approaches/dynamic-programming/snippet.txt new file mode 100644 index 000000000..3bbc3ad8c --- /dev/null +++ b/exercises/practice/change/.approaches/dynamic-programming/snippet.txt @@ -0,0 +1,36 @@ +import java.util.List; +import java.util.ArrayList; + +class ChangeCalculator { + private final List currencyCoins; + + ChangeCalculator(List currencyCoins) { + this.currencyCoins = currencyCoins; + } + + List computeMostEfficientChange(int grandTotal) { + if (grandTotal < 0) + throw new IllegalArgumentException("Negative totals are not allowed."); + + List> coinsUsed = new ArrayList<>(grandTotal + 1); + coinsUsed.add(new ArrayList()); + + for (int i = 1; i <= grandTotal; i++) { + List bestCombination = null; + for (int coin: currencyCoins) { + if (coin <= i && coinsUsed.get(i - coin) != null) { + List currentCombination = new ArrayList<>(coinsUsed.get(i - coin)); + currentCombination.add(0, coin); + if (bestCombination == null || currentCombination.size() < bestCombination.size()) + bestCombination = currentCombination; + } + } + coinsUsed.add(bestCombination); + } + + if (coinsUsed.get(grandTotal) == null) + throw new IllegalArgumentException("The total " + grandTotal + " cannot be represented in the given currency."); + + return coinsUsed.get(grandTotal); + } +} \ No newline at end of file diff --git a/exercises/practice/change/.approaches/intrduction.md b/exercises/practice/change/.approaches/intrduction.md new file mode 100644 index 000000000..27aaef140 --- /dev/null +++ b/exercises/practice/change/.approaches/intrduction.md @@ -0,0 +1,25 @@ +## Introduction to Change Calculation + +In the "Change Calculator" exercise, the goal is to determine the minimum number of coins needed to reach a given total using a specific set of coin denominations. This is a classic problem in dynamic programming, where efficient change-making is essential, especially when there are constraints on coin types or large totals. + +### Problem Overview + +Given: +- A list of coin denominations, each representing an available currency unit. +- A total amount (`grandTotal`) we want to reach using the fewest possible coins from the given denominations. + +The solution should find the optimal combination of coins to match the total. If it's impossible to match the total exactly, the solution should indicate this by throwing an exception. + +### Approach Overview + +Our solution uses a **dynamic programming approach**, where we systematically build up the optimal combinations for all totals from `0` up to the target amount (`grandTotal`). For each total, we track the fewest coins needed to make that total, reusing previous results to make the solution efficient. + +This approach ensures that we find the minimum number of coins required in a structured, repeatable way, avoiding the need for complex recursive calls or excessive backtracking. + +### Key Features of the Approach + +- **Efficiency**: By building solutions for each increment up to `grandTotal`, this approach minimizes redundant calculations. +- **Flexibility**: Handles cases where exact change is impossible by checking at each step. +- **Scalability**: Works for various coin denominations and totals, though large inputs may impact performance. + +For a detailed look at the code and logic, see the full explanation in the [approach file](https://exercism.org/tracks/java/exercises/change/approaches/dynamic-programming). From 404de05c450e885cd94316ed8c119a2fc20dd77a Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 23:05:15 +0530 Subject: [PATCH 23/49] Fixing typo in filename --- .../practice/change/.approaches/{config,json => config.json} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename exercises/practice/change/.approaches/{config,json => config.json} (100%) diff --git a/exercises/practice/change/.approaches/config,json b/exercises/practice/change/.approaches/config.json similarity index 100% rename from exercises/practice/change/.approaches/config,json rename to exercises/practice/change/.approaches/config.json From 1aa6d9c62356a7038cedaaedaf4906eb2b50cd55 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 23:13:50 +0530 Subject: [PATCH 24/49] Fixing style errors --- .../change/.approaches/dynamic-programming/content.md | 4 +++- exercises/practice/change/.approaches/intrduction.md | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index 38e8376f5..2f283a312 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -7,7 +7,7 @@ This approach ensures that we find the most efficient way to make change and han ## Explanation 1. **Initialize Coins Usage Tracker**: - - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. + - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. 2. **Iterative Dynamic Programming**: @@ -66,6 +66,7 @@ class ChangeCalculator { - **Space Complexity**: The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. - **Edge Cases**: + - If the `grandTotal` is negative, an exception is thrown immediately. - If there is no way to make the exact total with the given denominations, an exception is thrown with a descriptive message. @@ -74,6 +75,7 @@ class ChangeCalculator { - **Efficiency**: This approach is highly efficient in terms of minimizing the number of coins, but it might require significant memory for larger `grandTotal` values, as the space complexity grows linearly with `grandTotal`. - **Alternative Approaches**: + - A **Greedy Approach** could be faster for some cases but does not always guarantee the minimum number of coins. - This dynamic programming approach is best when the goal is to guarantee the fewest coins possible, especially when no simple greedy solution exists. diff --git a/exercises/practice/change/.approaches/intrduction.md b/exercises/practice/change/.approaches/intrduction.md index 27aaef140..84531fad3 100644 --- a/exercises/practice/change/.approaches/intrduction.md +++ b/exercises/practice/change/.approaches/intrduction.md @@ -1,10 +1,11 @@ -## Introduction to Change Calculation +# Introduction to Change Calculator In the "Change Calculator" exercise, the goal is to determine the minimum number of coins needed to reach a given total using a specific set of coin denominations. This is a classic problem in dynamic programming, where efficient change-making is essential, especially when there are constraints on coin types or large totals. ### Problem Overview Given: + - A list of coin denominations, each representing an available currency unit. - A total amount (`grandTotal`) we want to reach using the fewest possible coins from the given denominations. From 2fbec2a3add6d3d08e9ee6be7191d3b1dcdb45af Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 23:19:55 +0530 Subject: [PATCH 25/49] Fixing style errors --- .../change/.approaches/dynamic-programming/content.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index 2f283a312..260e52e77 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -6,16 +6,19 @@ This approach ensures that we find the most efficient way to make change and han ## Explanation -1. **Initialize Coins Usage Tracker**: +1. **Initialize Coins Usage Tracker**: + - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. -2. **Iterative Dynamic Programming**: +2. **Iterative Dynamic Programming**: + - For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). - If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. -3. **Result**: +3. **Result**: + - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. - If no valid combination exists for `grandTotal`, an exception is thrown. From c1d07e591aea8b99bcee452bbcfb71ed407da227 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 23:29:29 +0530 Subject: [PATCH 26/49] Fixing stle errors --- .../change/.approaches/dynamic-programming/content.md | 5 ++--- exercises/practice/change/.approaches/intrduction.md | 6 +++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index 260e52e77..cce152a0b 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -14,7 +14,7 @@ This approach ensures that we find the most efficient way to make change and han 2. **Iterative Dynamic Programming**: - For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. - - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). + - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). - If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. 3. **Result**: @@ -22,7 +22,6 @@ This approach ensures that we find the most efficient way to make change and han - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. - If no valid combination exists for `grandTotal`, an exception is thrown. - ```java import java.util.List; import java.util.ArrayList; @@ -77,7 +76,7 @@ class ChangeCalculator { - **Efficiency**: This approach is highly efficient in terms of minimizing the number of coins, but it might require significant memory for larger `grandTotal` values, as the space complexity grows linearly with `grandTotal`. -- **Alternative Approaches**: +- **Alternative Approaches**: - A **Greedy Approach** could be faster for some cases but does not always guarantee the minimum number of coins. - This dynamic programming approach is best when the goal is to guarantee the fewest coins possible, especially when no simple greedy solution exists. diff --git a/exercises/practice/change/.approaches/intrduction.md b/exercises/practice/change/.approaches/intrduction.md index 84531fad3..3834d706d 100644 --- a/exercises/practice/change/.approaches/intrduction.md +++ b/exercises/practice/change/.approaches/intrduction.md @@ -2,7 +2,7 @@ In the "Change Calculator" exercise, the goal is to determine the minimum number of coins needed to reach a given total using a specific set of coin denominations. This is a classic problem in dynamic programming, where efficient change-making is essential, especially when there are constraints on coin types or large totals. -### Problem Overview +## Problem Overview Given: @@ -11,13 +11,13 @@ Given: The solution should find the optimal combination of coins to match the total. If it's impossible to match the total exactly, the solution should indicate this by throwing an exception. -### Approach Overview +## Approach Overview Our solution uses a **dynamic programming approach**, where we systematically build up the optimal combinations for all totals from `0` up to the target amount (`grandTotal`). For each total, we track the fewest coins needed to make that total, reusing previous results to make the solution efficient. This approach ensures that we find the minimum number of coins required in a structured, repeatable way, avoiding the need for complex recursive calls or excessive backtracking. -### Key Features of the Approach +## Key Features of the Approach - **Efficiency**: By building solutions for each increment up to `grandTotal`, this approach minimizes redundant calculations. - **Flexibility**: Handles cases where exact change is impossible by checking at each step. From afee45ab5bd4871a5903ec32da0c27b43cee0b5d Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 9 Nov 2024 23:31:46 +0530 Subject: [PATCH 27/49] Fixing file names --- .../dynamic-programming/snippet.txt | 36 ------------------- .../{intrduction.md => introduction.md} | 0 2 files changed, 36 deletions(-) delete mode 100644 exercises/practice/change/.approaches/dynamic-programming/snippet.txt rename exercises/practice/change/.approaches/{intrduction.md => introduction.md} (100%) diff --git a/exercises/practice/change/.approaches/dynamic-programming/snippet.txt b/exercises/practice/change/.approaches/dynamic-programming/snippet.txt deleted file mode 100644 index 3bbc3ad8c..000000000 --- a/exercises/practice/change/.approaches/dynamic-programming/snippet.txt +++ /dev/null @@ -1,36 +0,0 @@ -import java.util.List; -import java.util.ArrayList; - -class ChangeCalculator { - private final List currencyCoins; - - ChangeCalculator(List currencyCoins) { - this.currencyCoins = currencyCoins; - } - - List computeMostEfficientChange(int grandTotal) { - if (grandTotal < 0) - throw new IllegalArgumentException("Negative totals are not allowed."); - - List> coinsUsed = new ArrayList<>(grandTotal + 1); - coinsUsed.add(new ArrayList()); - - for (int i = 1; i <= grandTotal; i++) { - List bestCombination = null; - for (int coin: currencyCoins) { - if (coin <= i && coinsUsed.get(i - coin) != null) { - List currentCombination = new ArrayList<>(coinsUsed.get(i - coin)); - currentCombination.add(0, coin); - if (bestCombination == null || currentCombination.size() < bestCombination.size()) - bestCombination = currentCombination; - } - } - coinsUsed.add(bestCombination); - } - - if (coinsUsed.get(grandTotal) == null) - throw new IllegalArgumentException("The total " + grandTotal + " cannot be represented in the given currency."); - - return coinsUsed.get(grandTotal); - } -} \ No newline at end of file diff --git a/exercises/practice/change/.approaches/intrduction.md b/exercises/practice/change/.approaches/introduction.md similarity index 100% rename from exercises/practice/change/.approaches/intrduction.md rename to exercises/practice/change/.approaches/introduction.md From d9694faf8b91e0cfa5e76c1ac18fcc96f4123087 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Thu, 14 Nov 2024 23:25:31 +0530 Subject: [PATCH 28/49] Adding uuid for approach of change --- exercises/practice/change/.approaches/config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/change/.approaches/config.json b/exercises/practice/change/.approaches/config.json index 78950cae5..f9b602eb2 100644 --- a/exercises/practice/change/.approaches/config.json +++ b/exercises/practice/change/.approaches/config.json @@ -6,7 +6,7 @@ }, "approaches": [ { - "uuid": "", + "uuid": "d0b615ca-3a02-4d66-ad10-e0c513062189", "slug": "dynamic-programming", "title": "Dynamic Programming Approach", "blurb": "Use dynamic programming to find the most efficient change combination.", From 7aa412ef35d2b4b5a63a4a4a541bcd026eddf5cd Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Thu, 14 Nov 2024 23:27:08 +0530 Subject: [PATCH 29/49] Adding snippet for approach of change --- .../change/.approaches/dynamic-programming/snippet.txt | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 exercises/practice/change/.approaches/dynamic-programming/snippet.txt diff --git a/exercises/practice/change/.approaches/dynamic-programming/snippet.txt b/exercises/practice/change/.approaches/dynamic-programming/snippet.txt new file mode 100644 index 000000000..25f90e6f5 --- /dev/null +++ b/exercises/practice/change/.approaches/dynamic-programming/snippet.txt @@ -0,0 +1,8 @@ +class ChangeCalculator { + private final List currencyCoins; + + ChangeCalculator(List currencyCoins) { + this.currencyCoins = currencyCoins; + } + // computeMostEfficientChange method +} From f3eb007e0340e879aab4c93a8adaa151eefa487c Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Fri, 15 Nov 2024 21:42:42 +0530 Subject: [PATCH 30/49] Updating approach files --- .../practice/change/.approaches/config.json | 2 +- .../dynamic-programming/content.md | 57 ++++++++----------- .../change/.approaches/introduction.md | 25 ++++---- 3 files changed, 39 insertions(+), 45 deletions(-) diff --git a/exercises/practice/change/.approaches/config.json b/exercises/practice/change/.approaches/config.json index f9b602eb2..00716db81 100644 --- a/exercises/practice/change/.approaches/config.json +++ b/exercises/practice/change/.approaches/config.json @@ -14,7 +14,7 @@ "jagdish-15" ], "contributors": [ - "kagoh" + "kahgoh" ] } ] diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index cce152a0b..4277c61ff 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -1,27 +1,5 @@ # Dynamic Programming Approach -The **Dynamic Programming (DP)** approach is an efficient way to solve the problem of making change for a given total using a list of available coin denominations. It minimizes the number of coins needed by breaking down the problem into smaller subproblems and solving them progressively. - -This approach ensures that we find the most efficient way to make change and handles edge cases where no solution exists. - -## Explanation - -1. **Initialize Coins Usage Tracker**: - - - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. - - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. - -2. **Iterative Dynamic Programming**: - - - For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. - - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). - - If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. - -3. **Result**: - - - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. - - If no valid combination exists for `grandTotal`, an exception is thrown. - ```java import java.util.List; import java.util.ArrayList; @@ -61,6 +39,29 @@ class ChangeCalculator { } ``` +The **Dynamic Programming (DP)** approach is an efficient way to solve the problem of making change for a given total using a list of available coin denominations. +It minimizes the number of coins needed by breaking down the problem into smaller subproblems and solving them progressively. + +This approach ensures that we find the most efficient way to make change and handles edge cases where no solution exists. + +## Explanation + +1. **Initialize Coins Usage Tracker**: + + - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. + - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. + +2. **Iterative Dynamic Programming**: + + - For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. + - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). + - If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. + +3. **Result**: + + - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. + - If no valid combination exists for `grandTotal`, an exception is thrown. + ## Key Points - **Time Complexity**: The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. @@ -72,15 +73,7 @@ class ChangeCalculator { - If the `grandTotal` is negative, an exception is thrown immediately. - If there is no way to make the exact total with the given denominations, an exception is thrown with a descriptive message. -## Trade-offs and Considerations - -- **Efficiency**: This approach is highly efficient in terms of minimizing the number of coins, but it might require significant memory for larger `grandTotal` values, as the space complexity grows linearly with `grandTotal`. - -- **Alternative Approaches**: - - - A **Greedy Approach** could be faster for some cases but does not always guarantee the minimum number of coins. - - This dynamic programming approach is best when the goal is to guarantee the fewest coins possible, especially when no simple greedy solution exists. - ## Conclusion -The dynamic programming approach provides an optimal solution for the change-making problem, ensuring that we minimize the number of coins used while efficiently solving the problem for any `grandTotal`. However, it’s essential to consider the trade-offs in terms of memory usage and the time complexity when dealing with very large inputs. +The dynamic programming approach provides an optimal solution for the change-making problem, ensuring that we minimize the number of coins used while efficiently solving the problem for any `grandTotal`. +However, it’s essential to consider the trade-offs in terms of memory usage and the time complexity when dealing with very large inputs. diff --git a/exercises/practice/change/.approaches/introduction.md b/exercises/practice/change/.approaches/introduction.md index 3834d706d..713e5070f 100644 --- a/exercises/practice/change/.approaches/introduction.md +++ b/exercises/practice/change/.approaches/introduction.md @@ -1,19 +1,17 @@ -# Introduction to Change Calculator +# Introduction -In the "Change Calculator" exercise, the goal is to determine the minimum number of coins needed to reach a given total using a specific set of coin denominations. This is a classic problem in dynamic programming, where efficient change-making is essential, especially when there are constraints on coin types or large totals. +There is an idiomatic approach to solving "Change." +You can use [dynamic programming][dynamic-programming] to calculate the minimum number of coins required for a given total. -## Problem Overview +## General guidance -Given: +The key to solving "Change" is understanding that not all totals can be reached with the available coin denominations. +The solution needs to figure out which totals can be achieved and how to combine the coins optimally. -- A list of coin denominations, each representing an available currency unit. -- A total amount (`grandTotal`) we want to reach using the fewest possible coins from the given denominations. +## Approach: Dynamic Programming -The solution should find the optimal combination of coins to match the total. If it's impossible to match the total exactly, the solution should indicate this by throwing an exception. - -## Approach Overview - -Our solution uses a **dynamic programming approach**, where we systematically build up the optimal combinations for all totals from `0` up to the target amount (`grandTotal`). For each total, we track the fewest coins needed to make that total, reusing previous results to make the solution efficient. +Our solution uses a **dynamic programming approach**, where we systematically build up the optimal combinations for all totals from `0` up to the target amount (`grandTotal`). +For each total, we track the fewest coins needed to make that total, reusing previous results to make the solution efficient. This approach ensures that we find the minimum number of coins required in a structured, repeatable way, avoiding the need for complex recursive calls or excessive backtracking. @@ -23,4 +21,7 @@ This approach ensures that we find the minimum number of coins required in a str - **Flexibility**: Handles cases where exact change is impossible by checking at each step. - **Scalability**: Works for various coin denominations and totals, though large inputs may impact performance. -For a detailed look at the code and logic, see the full explanation in the [approach file](https://exercism.org/tracks/java/exercises/change/approaches/dynamic-programming). +For a detailed look at the code and logic, see the full explanation in the [Dynamic Programming Approach][approach-dynamic-programming]. + +[approach-dynamic-programming]: https://exercism.org/tracks/java/exercises/change/approaches/dynamic-programming +[dynamic-programming]: https://en.wikipedia.org/wiki/Dynamic_programming \ No newline at end of file From 0b5b6f26f1b8950d65e14a54b2b0af3a40b765c0 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Fri, 15 Nov 2024 21:45:08 +0530 Subject: [PATCH 31/49] Fixing styling errors --- exercises/practice/change/.approaches/introduction.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/change/.approaches/introduction.md b/exercises/practice/change/.approaches/introduction.md index 713e5070f..49100bf51 100644 --- a/exercises/practice/change/.approaches/introduction.md +++ b/exercises/practice/change/.approaches/introduction.md @@ -24,4 +24,4 @@ This approach ensures that we find the minimum number of coins required in a str For a detailed look at the code and logic, see the full explanation in the [Dynamic Programming Approach][approach-dynamic-programming]. [approach-dynamic-programming]: https://exercism.org/tracks/java/exercises/change/approaches/dynamic-programming -[dynamic-programming]: https://en.wikipedia.org/wiki/Dynamic_programming \ No newline at end of file +[dynamic-programming]: https://en.wikipedia.org/wiki/Dynamic_programming From 2758bc3737fb09d4b91f37b61ecf790f6f02c2ef Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Tue, 19 Nov 2024 00:22:45 +0530 Subject: [PATCH 32/49] Updating approaches for Change after feedback --- .../dynamic-programming/content.md | 14 +----- .../change/.approaches/introduction.md | 48 +++++++++++++++---- 2 files changed, 39 insertions(+), 23 deletions(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index 4277c61ff..c5801342c 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -42,12 +42,11 @@ class ChangeCalculator { The **Dynamic Programming (DP)** approach is an efficient way to solve the problem of making change for a given total using a list of available coin denominations. It minimizes the number of coins needed by breaking down the problem into smaller subproblems and solving them progressively. -This approach ensures that we find the most efficient way to make change and handles edge cases where no solution exists. - ## Explanation 1. **Initialize Coins Usage Tracker**: + - If the `grandTotal` is negative, an exception is thrown immediately. - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. @@ -62,18 +61,7 @@ This approach ensures that we find the most efficient way to make change and han - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. - If no valid combination exists for `grandTotal`, an exception is thrown. -## Key Points - **Time Complexity**: The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. - **Space Complexity**: The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. - -- **Edge Cases**: - - - If the `grandTotal` is negative, an exception is thrown immediately. - - If there is no way to make the exact total with the given denominations, an exception is thrown with a descriptive message. - -## Conclusion - -The dynamic programming approach provides an optimal solution for the change-making problem, ensuring that we minimize the number of coins used while efficiently solving the problem for any `grandTotal`. -However, it’s essential to consider the trade-offs in terms of memory usage and the time complexity when dealing with very large inputs. diff --git a/exercises/practice/change/.approaches/introduction.md b/exercises/practice/change/.approaches/introduction.md index 49100bf51..672aae038 100644 --- a/exercises/practice/change/.approaches/introduction.md +++ b/exercises/practice/change/.approaches/introduction.md @@ -10,16 +10,44 @@ The solution needs to figure out which totals can be achieved and how to combine ## Approach: Dynamic Programming -Our solution uses a **dynamic programming approach**, where we systematically build up the optimal combinations for all totals from `0` up to the target amount (`grandTotal`). -For each total, we track the fewest coins needed to make that total, reusing previous results to make the solution efficient. - -This approach ensures that we find the minimum number of coins required in a structured, repeatable way, avoiding the need for complex recursive calls or excessive backtracking. - -## Key Features of the Approach - -- **Efficiency**: By building solutions for each increment up to `grandTotal`, this approach minimizes redundant calculations. -- **Flexibility**: Handles cases where exact change is impossible by checking at each step. -- **Scalability**: Works for various coin denominations and totals, though large inputs may impact performance. +```java +import java.util.List; +import java.util.ArrayList; + +class ChangeCalculator { + private final List currencyCoins; + + ChangeCalculator(List currencyCoins) { + this.currencyCoins = currencyCoins; + } + + List computeMostEfficientChange(int grandTotal) { + if (grandTotal < 0) + throw new IllegalArgumentException("Negative totals are not allowed."); + + List> coinsUsed = new ArrayList<>(grandTotal + 1); + coinsUsed.add(new ArrayList()); + + for (int i = 1; i <= grandTotal; i++) { + List bestCombination = null; + for (int coin: currencyCoins) { + if (coin <= i && coinsUsed.get(i - coin) != null) { + List currentCombination = new ArrayList<>(coinsUsed.get(i - coin)); + currentCombination.add(0, coin); + if (bestCombination == null || currentCombination.size() < bestCombination.size()) + bestCombination = currentCombination; + } + } + coinsUsed.add(bestCombination); + } + + if (coinsUsed.get(grandTotal) == null) + throw new IllegalArgumentException("The total " + grandTotal + " cannot be represented in the given currency."); + + return coinsUsed.get(grandTotal); + } +} +``` For a detailed look at the code and logic, see the full explanation in the [Dynamic Programming Approach][approach-dynamic-programming]. From c0a46c607fadaa0f3c44a40f006f29fd57660534 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Tue, 19 Nov 2024 00:25:44 +0530 Subject: [PATCH 33/49] Fixing styling issues for approache for Change --- .../practice/change/.approaches/dynamic-programming/content.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index c5801342c..4c2ce7c1d 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -46,7 +46,7 @@ It minimizes the number of coins needed by breaking down the problem into smalle 1. **Initialize Coins Usage Tracker**: - - If the `grandTotal` is negative, an exception is thrown immediately. + - If the `grandTotal` is negative, an exception is thrown immediately. - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. @@ -61,7 +61,6 @@ It minimizes the number of coins needed by breaking down the problem into smalle - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. - If no valid combination exists for `grandTotal`, an exception is thrown. - - **Time Complexity**: The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. - **Space Complexity**: The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. From 5885dc83279e30a31db7e858c56b3d14e5c59806 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Tue, 19 Nov 2024 00:42:36 +0530 Subject: [PATCH 34/49] Chnaging the introduction.md for consistancy --- .../queen-attack/.approaches/introduction.md | 31 ++++++++++++++----- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/exercises/practice/queen-attack/.approaches/introduction.md b/exercises/practice/queen-attack/.approaches/introduction.md index 5fbfaefb9..bec2a4d29 100644 --- a/exercises/practice/queen-attack/.approaches/introduction.md +++ b/exercises/practice/queen-attack/.approaches/introduction.md @@ -14,14 +14,29 @@ The problem boils down to checking three conditions: ## Approach: Simple Comparison Approach -This exercise is solved using a **Simple Comparison Approach**. -By comparing the row, column, and diagonal positions of the two queens, we can easily determine if they can attack each other. - -### Why This Approach? - -The Simple Comparison Approach is chosen for its clarity and simplicity. -It uses basic comparison checks to determine if two queens are in attacking positions. -This method works well for small scenarios like this one, where performance isn't a major concern. +```java +class QueenAttackCalculator { + private final Queen queen1; + private final Queen queen2; + + QueenAttackCalculator(Queen queen1, Queen queen2) { + if (queen1 == null || queen2 == null) { + throw new IllegalArgumentException("You must supply valid positions for both Queens."); + } + if (queen1.getRow() == queen2.getRow() && queen1.getColumn() == queen2.getColumn()) { + throw new IllegalArgumentException("Queens cannot occupy the same position."); + } + this.queen1 = queen1; + this.queen2 = queen2; + } + + boolean canQueensAttackOneAnother() { + int rowDifference = Math.abs(queen1.getRow() - queen2.getRow()); + int columnDifference = Math.abs(queen1.getColumn() - queen2.getColumn()); + return rowDifference == 0 || columnDifference == 0 || rowDifference == columnDifference; + } +} +``` For more details on the implementation of this approach, check out the [Simple Comparison Approach][simple-comparison-approach]. From 239d916055f691fd8a6a10040a609bc91dfd77d5 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Tue, 19 Nov 2024 14:45:15 +0530 Subject: [PATCH 35/49] Updating tests for Zipper to sync with the problem-specifications repo --- exercises/practice/zipper/.meta/config.json | 1 + exercises/practice/zipper/.meta/tests.toml | 16 +++++++++++++--- .../zipper/src/test/java/ZipperTest.java | 7 +++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/exercises/practice/zipper/.meta/config.json b/exercises/practice/zipper/.meta/config.json index 17e31b240..d5d633cc3 100644 --- a/exercises/practice/zipper/.meta/config.json +++ b/exercises/practice/zipper/.meta/config.json @@ -4,6 +4,7 @@ ], "contributors": [ "FridaTveit", + "jagdish-15", "jmrunkle", "lemoncurry", "msomji", diff --git a/exercises/practice/zipper/.meta/tests.toml b/exercises/practice/zipper/.meta/tests.toml index d7b089816..e93932b17 100644 --- a/exercises/practice/zipper/.meta/tests.toml +++ b/exercises/practice/zipper/.meta/tests.toml @@ -1,6 +1,13 @@ -# This is an auto-generated file. Regular comments will be removed when this -# file is regenerated. Regenerating will not touch any manually added keys, -# so comments can be added in a "comment" key. +# 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. [771c652e-0754-4ef0-945c-0675d12ef1f5] description = "data is retained" @@ -20,6 +27,9 @@ description = "traversing up from top" [b8505f6a-aed4-4c2e-824f-a0ed8570d74b] description = "left, right, and up" +[b9aa8d54-07b7-4bfd-ab6b-7ff7f35930b6] +description = "test ability to descend multiple levels and return" + [47df1a27-b709-496e-b381-63a03b82ea5f] description = "set_value" diff --git a/exercises/practice/zipper/src/test/java/ZipperTest.java b/exercises/practice/zipper/src/test/java/ZipperTest.java index d9f6fd505..842ca8be2 100644 --- a/exercises/practice/zipper/src/test/java/ZipperTest.java +++ b/exercises/practice/zipper/src/test/java/ZipperTest.java @@ -60,6 +60,13 @@ public void testLeftRightAndUp() { assertThat(zipper.left.up.right.up.left.right.getValue()).isEqualTo(3); } + @Disabled("Remove to run test") + @Test + public void testAbilityToReturnAfterMultipleLevelDescend() { + zipper = binaryTree.getRoot(); + assertThat(zipper.left.right.up.up.getValue()).isEqualTo(1); + } + @Disabled("Remove to run test") @Test public void testSetValue() { From f76ad5de74e3c694acec962eddc7ada9b5c76143 Mon Sep 17 00:00:00 2001 From: jagdish-15 Date: Tue, 19 Nov 2024 21:38:08 +0530 Subject: [PATCH 36/49] Update exercises/practice/change/.approaches/dynamic-programming/content.md Co-authored-by: Kah Goh --- .../practice/change/.approaches/dynamic-programming/content.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index 4c2ce7c1d..29ff4ee8a 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -61,6 +61,6 @@ It minimizes the number of coins needed by breaking down the problem into smalle - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. - If no valid combination exists for `grandTotal`, an exception is thrown. -- **Time Complexity**: The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. +The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. - **Space Complexity**: The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. From 5db8204a406f8b4789192fc6e7ff152005e2be9b Mon Sep 17 00:00:00 2001 From: jagdish-15 Date: Tue, 19 Nov 2024 21:38:31 +0530 Subject: [PATCH 37/49] Update exercises/practice/change/.approaches/dynamic-programming/content.md Co-authored-by: Kah Goh --- .../practice/change/.approaches/dynamic-programming/content.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index 29ff4ee8a..0a5ccfddc 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -63,4 +63,4 @@ It minimizes the number of coins needed by breaking down the problem into smalle The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. -- **Space Complexity**: The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. +The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. From 505a92de0242c58c68f31817b576e12b82d70241 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Tue, 19 Nov 2024 22:14:04 +0530 Subject: [PATCH 38/49] Updating content for dynamic approach of change --- .../change/.approaches/dynamic-programming/content.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index 0a5ccfddc..7e264778f 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -61,6 +61,8 @@ It minimizes the number of coins needed by breaking down the problem into smalle - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. - If no valid combination exists for `grandTotal`, an exception is thrown. -The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. +## Time and Space Complexity + +- The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. -The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. +- The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. From ddea7e44d2b8c798d62f36f98bb3315e548ea783 Mon Sep 17 00:00:00 2001 From: jagdish-15 Date: Tue, 19 Nov 2024 22:23:07 +0530 Subject: [PATCH 39/49] Update exercises/practice/queen-attack/.approaches/introduction.md Co-authored-by: Kah Goh --- exercises/practice/queen-attack/.approaches/introduction.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/queen-attack/.approaches/introduction.md b/exercises/practice/queen-attack/.approaches/introduction.md index bec2a4d29..c6a4c77c3 100644 --- a/exercises/practice/queen-attack/.approaches/introduction.md +++ b/exercises/practice/queen-attack/.approaches/introduction.md @@ -1,4 +1,4 @@ -# Queen Attack Exercise +# Introduction In this exercise, we determine if two queens on a chessboard can attack each other based on their positions. A queen in chess can move any number of squares horizontally, vertically, or diagonally. From ec9e1e22316b4d1c02d7a63be660db9babb3c8f0 Mon Sep 17 00:00:00 2001 From: jagdish-15 Date: Tue, 19 Nov 2024 22:23:18 +0530 Subject: [PATCH 40/49] Update exercises/practice/queen-attack/.approaches/introduction.md Co-authored-by: Kah Goh --- exercises/practice/queen-attack/.approaches/introduction.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/queen-attack/.approaches/introduction.md b/exercises/practice/queen-attack/.approaches/introduction.md index c6a4c77c3..460d792bf 100644 --- a/exercises/practice/queen-attack/.approaches/introduction.md +++ b/exercises/practice/queen-attack/.approaches/introduction.md @@ -4,7 +4,7 @@ In this exercise, we determine if two queens on a chessboard can attack each oth A queen in chess can move any number of squares horizontally, vertically, or diagonally. The task is to check if two queens, placed on specific coordinates, can attack each other. -## Genral Advice +## General Guidance The problem boils down to checking three conditions: From a4d74388f79f8c55a21385659ad88c555803cb0f Mon Sep 17 00:00:00 2001 From: jagdish-15 Date: Tue, 19 Nov 2024 22:26:12 +0530 Subject: [PATCH 41/49] Update exercises/practice/queen-attack/.approaches/simple-comparison/content.md Co-authored-by: Kah Goh --- .../queen-attack/.approaches/simple-comparison/content.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md index a29d18e92..b996933bb 100644 --- a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md +++ b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md @@ -67,7 +67,7 @@ class QueenAttackCalculator { 1. **Constructor**: - In the constructor of `QueenAttackCalculator`, we check if the queens are positioned at valid places. + The constructor of `QueenAttackCalculator` takes two `Queen` objects and checks if they are positioned at valid places. If either queen is `null`, or if both queens occupy the same position, an exception is thrown. The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables. From d4f1b8e66194c09f066184bc52f351ec54b06912 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Tue, 19 Nov 2024 23:17:14 +0530 Subject: [PATCH 42/49] Changing the name of the approach for queen-attack exercise and updating the content for the same --- .../queen-attack/.approaches/config.json | 6 +- .../difference-comparison/content.md | 46 +++++++++++ .../snippet.txt | 0 .../queen-attack/.approaches/introduction.md | 6 +- .../.approaches/simple-comparison/content.md | 80 ------------------- 5 files changed, 52 insertions(+), 86 deletions(-) create mode 100644 exercises/practice/queen-attack/.approaches/difference-comparison/content.md rename exercises/practice/queen-attack/.approaches/{simple-comparison => difference-comparison}/snippet.txt (100%) delete mode 100644 exercises/practice/queen-attack/.approaches/simple-comparison/content.md diff --git a/exercises/practice/queen-attack/.approaches/config.json b/exercises/practice/queen-attack/.approaches/config.json index fbfa109a1..fd78dc118 100644 --- a/exercises/practice/queen-attack/.approaches/config.json +++ b/exercises/practice/queen-attack/.approaches/config.json @@ -7,9 +7,9 @@ "approaches": [ { "uuid": "b2e474c8-b778-41e7-83c0-8e41cc84af9e", - "slug": "simple-comparison", - "title": "Simple Comparison Approach", - "blurb": "Use basic comparison checks to determine if queens can attack each other.", + "slug": "difference-comparison", + "title": "Difference Comparison Approach", + "blurb": "Use difference comparison checks to determine if queens can attack each other.", "authors": [ "jagdish-15" ] diff --git a/exercises/practice/queen-attack/.approaches/difference-comparison/content.md b/exercises/practice/queen-attack/.approaches/difference-comparison/content.md new file mode 100644 index 000000000..a33e93c66 --- /dev/null +++ b/exercises/practice/queen-attack/.approaches/difference-comparison/content.md @@ -0,0 +1,46 @@ +# Difference Comparison Approach + +```java +class QueenAttackCalculator { + private final Queen queen1; + private final Queen queen2; + + QueenAttackCalculator(Queen queen1, Queen queen2) { + if (queen1 == null || queen2 == null) { + throw new IllegalArgumentException("You must supply valid positions for both Queens."); + } + if (queen1.getRow() == queen2.getRow() && queen1.getColumn() == queen2.getColumn()) { + throw new IllegalArgumentException("Queens cannot occupy the same position."); + } + this.queen1 = queen1; + this.queen2 = queen2; + } + + boolean canQueensAttackOneAnother() { + int rowDifference = Math.abs(queen1.getRow() - queen2.getRow()); + int columnDifference = Math.abs(queen1.getColumn() - queen2.getColumn()); + return rowDifference == 0 || columnDifference == 0 || rowDifference == columnDifference; + } +} +``` + +## Explanation + +1. **Constructor**: + + The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables after validating the following conditions: + + - If either queen is `null`. + - If both queens occupy the same position. + + If either of these conditions is true, an exception is thrown. + +2. **Method (`canQueensAttackOneAnother`)**: + + This method calculates the row and column differences between the two queens and checks the following conditions: + + - If the row difference is zero (the queens are on the same row). + - If the column difference is zero (the queens are on the same column). + - If the row and column differences are equal (the queens are on the same diagonal). + + If any of these conditions are true, the method returns `true`, indicating that the queens can attack each other. diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/snippet.txt b/exercises/practice/queen-attack/.approaches/difference-comparison/snippet.txt similarity index 100% rename from exercises/practice/queen-attack/.approaches/simple-comparison/snippet.txt rename to exercises/practice/queen-attack/.approaches/difference-comparison/snippet.txt diff --git a/exercises/practice/queen-attack/.approaches/introduction.md b/exercises/practice/queen-attack/.approaches/introduction.md index bec2a4d29..f4fe1e185 100644 --- a/exercises/practice/queen-attack/.approaches/introduction.md +++ b/exercises/practice/queen-attack/.approaches/introduction.md @@ -12,7 +12,7 @@ The problem boils down to checking three conditions: 2. **Same Column**: If the queens are on the same column. 3. **Same Diagonal**: If the queens are on the same diagonal, i.e., the absolute difference between their row and column positions is equal. -## Approach: Simple Comparison Approach +## Approach: Difference Comparison Approach ```java class QueenAttackCalculator { @@ -38,6 +38,6 @@ class QueenAttackCalculator { } ``` -For more details on the implementation of this approach, check out the [Simple Comparison Approach][simple-comparison-approach]. +For more details on the implementation of this approach, check out the [Difference Comparison Approach][difference-comparison-approach]. -[simple-comparison-approach]: https://exercism.org/tracks/java/exercises/queen-attack/approaches/simple-comparison +[difference-comparison-approach]: https://exercism.org/tracks/java/exercises/queen-attack/approaches/difference-comparison diff --git a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md b/exercises/practice/queen-attack/.approaches/simple-comparison/content.md deleted file mode 100644 index a29d18e92..000000000 --- a/exercises/practice/queen-attack/.approaches/simple-comparison/content.md +++ /dev/null @@ -1,80 +0,0 @@ -# Queen Attack Approach - -```java -class QueenAttackCalculator { - private final Queen queen1; - private final Queen queen2; - - QueenAttackCalculator(Queen queen1, Queen queen2) { - if (queen1 == null || queen2 == null) { - throw new IllegalArgumentException("You must supply valid positions for both Queens."); - } - if (queen1.getRow() == queen2.getRow() && queen1.getColumn() == queen2.getColumn()) { - throw new IllegalArgumentException("Queens cannot occupy the same position."); - } - this.queen1 = queen1; - this.queen2 = queen2; - } - - boolean canQueensAttackOneAnother() { - int rowDifference = Math.abs(queen1.getRow() - queen2.getRow()); - int columnDifference = Math.abs(queen1.getColumn() - queen2.getColumn()); - return rowDifference == 0 || columnDifference == 0 || rowDifference == columnDifference; - } -} -``` - -## Approach Steps - -1. **Check if Queens are on the Same Row**: - - If both queens are on the same row, they can attack each other. This is checked by comparing their row values: - - ```java - if (queen1.getRow() == queen2.getRow()) { - return true; - } - ``` - -2. **Check if Queens are on the Same Column**: - - If both queens are on the same column, they can attack each other. This is checked by comparing their column values: - - ```java - if (queen1.getColumn() == queen2.getColumn()) { - return true; - } - ``` - -3. **Check if Queens are on the Same Diagonal**: - - If both queens are on the same diagonal, they can attack each other. This is checked by comparing the absolute difference between their row and column values: - - ```java - if (Math.abs(queen1.getRow() - queen2.getRow()) == Math.abs(queen1.getColumn() - queen2.getColumn())) { - return true; - } - ``` - -4. **Return the Result**: - - If any of the above checks return `true`, the queens can attack each other. Otherwise, they cannot. - -## Explanation - -- **Row Check**: We first check if the queens are in the same row. If they are, they can attack each other. -- **Column Check**: Next, we check if the queens are in the same column. If they are, they can attack each other. -- **Diagonal Check**: Lastly, we check if the queens are positioned on the same diagonal. This is determined by comparing the absolute differences in their row and column positions. -- **Final Decision**: If any of these checks return `true`, the queens can attack each other. If none of these conditions are met, they cannot attack each other. - -## Additional Explanation for Code - -1. **Constructor**: - - In the constructor of `QueenAttackCalculator`, we check if the queens are positioned at valid places. - If either queen is `null`, or if both queens occupy the same position, an exception is thrown. - The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables. - -2. **Method (`canQueensAttackOneAnother`)**: - - - This method computes the row and column differences between the two queens and then checks: - - If the row difference is zero (queens are on the same row). - - If the column difference is zero (queens are on the same column). - - If the row and column differences are equal (queens are on the same diagonal). - - If any of these checks are true, the method returns `true`, indicating that the queens can attack each other. From 7f4e9808d68349a341c8937498fede2aec8012fa Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 23 Nov 2024 20:20:51 +0530 Subject: [PATCH 43/49] Updating the approach for queen-attack after feedback --- .../queen-attack/.approaches/config.json | 4 ++++ .../difference-comparison/content.md | 22 +++++++++---------- .../queen-attack/.approaches/introduction.md | 6 ++--- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/exercises/practice/queen-attack/.approaches/config.json b/exercises/practice/queen-attack/.approaches/config.json index fd78dc118..e087317ce 100644 --- a/exercises/practice/queen-attack/.approaches/config.json +++ b/exercises/practice/queen-attack/.approaches/config.json @@ -2,6 +2,10 @@ "introduction": { "authors": [ "jagdish-15" + ], + "contributors": [ + "kahgoh", + "tasxatzial" ] }, "approaches": [ diff --git a/exercises/practice/queen-attack/.approaches/difference-comparison/content.md b/exercises/practice/queen-attack/.approaches/difference-comparison/content.md index a33e93c66..56b3cdfb6 100644 --- a/exercises/practice/queen-attack/.approaches/difference-comparison/content.md +++ b/exercises/practice/queen-attack/.approaches/difference-comparison/content.md @@ -26,21 +26,21 @@ class QueenAttackCalculator { ## Explanation -1. **Constructor**: +### Constructor - The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables after validating the following conditions: +The constructor takes two `Queen` objects, `queen1` and `queen2`, and stores them as instance variables after validating the following conditions: - - If either queen is `null`. - - If both queens occupy the same position. +- Either queen is `null`. +- Both queens occupy the same position. - If either of these conditions is true, an exception is thrown. +If either of these conditions is true, an exception is thrown. -2. **Method (`canQueensAttackOneAnother`)**: +### `canQueensAttackOneAnother` Method - This method calculates the row and column differences between the two queens and checks the following conditions: +This method calculates the row and column differences between the two queens and checks the following conditions: - - If the row difference is zero (the queens are on the same row). - - If the column difference is zero (the queens are on the same column). - - If the row and column differences are equal (the queens are on the same diagonal). +- The row difference is zero (the queens are on the same row). +- The column difference is zero (the queens are on the same column). +- The row and column differences are equal (the queens are on the same diagonal). - If any of these conditions are true, the method returns `true`, indicating that the queens can attack each other. +If any of these conditions are true, the method returns `true`, indicating that the queens can attack each other. diff --git a/exercises/practice/queen-attack/.approaches/introduction.md b/exercises/practice/queen-attack/.approaches/introduction.md index c0e02d337..3c2d6d765 100644 --- a/exercises/practice/queen-attack/.approaches/introduction.md +++ b/exercises/practice/queen-attack/.approaches/introduction.md @@ -8,9 +8,9 @@ The task is to check if two queens, placed on specific coordinates, can attack e The problem boils down to checking three conditions: -1. **Same Row**: If the queens are on the same row. -2. **Same Column**: If the queens are on the same column. -3. **Same Diagonal**: If the queens are on the same diagonal, i.e., the absolute difference between their row and column positions is equal. +1. **Same Row**: The queens are on the same row. +2. **Same Column**: The queens are on the same column. +3. **Same Diagonal**: The queens are on the same diagonal, i.e., the absolute difference between their row and column positions is equal. ## Approach: Difference Comparison Approach From c6e7deb45d0e389b27ed84a4aee8d4b58ccf751f Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Tue, 19 Nov 2024 11:57:35 +0530 Subject: [PATCH 44/49] Updating tests of Forth to sync with problem-specifications --- exercises/practice/forth/.meta/config.json | 1 + exercises/practice/forth/.meta/tests.toml | 18 +++++++++ .../src/test/java/ForthEvaluatorTest.java | 40 +++++++++++++++++++ 3 files changed, 59 insertions(+) diff --git a/exercises/practice/forth/.meta/config.json b/exercises/practice/forth/.meta/config.json index 85016dbdc..65de8e284 100644 --- a/exercises/practice/forth/.meta/config.json +++ b/exercises/practice/forth/.meta/config.json @@ -6,6 +6,7 @@ "aadityakulkarni", "FridaTveit", "hgvanpariya", + "jagdish-15", "jmrunkle", "kytrinyx", "lemoncurry", diff --git a/exercises/practice/forth/.meta/tests.toml b/exercises/practice/forth/.meta/tests.toml index c9c1d6377..d1e146a1e 100644 --- a/exercises/practice/forth/.meta/tests.toml +++ b/exercises/practice/forth/.meta/tests.toml @@ -24,6 +24,9 @@ description = "addition -> errors if there is nothing on the stack" [06efb9a4-817a-435e-b509-06166993c1b8] description = "addition -> errors if there is only one value on the stack" +[1e07a098-c5fa-4c66-97b2-3c81205dbc2f] +description = "addition -> more than two values on the stack" + [09687c99-7bbc-44af-8526-e402f997ccbf] description = "subtraction -> can subtract two numbers" @@ -33,6 +36,9 @@ description = "subtraction -> errors if there is nothing on the stack" [b3cee1b2-9159-418a-b00d-a1bb3765c23b] description = "subtraction -> errors if there is only one value on the stack" +[2c8cc5ed-da97-4cb1-8b98-fa7b526644f4] +description = "subtraction -> more than two values on the stack" + [5df0ceb5-922e-401f-974d-8287427dbf21] description = "multiplication -> can multiply two numbers" @@ -42,6 +48,9 @@ description = "multiplication -> errors if there is nothing on the stack" [8ba4b432-9f94-41e0-8fae-3b3712bd51b3] description = "multiplication -> errors if there is only one value on the stack" +[5cd085b5-deb1-43cc-9c17-6b1c38bc9970] +description = "multiplication -> more than two values on the stack" + [e74c2204-b057-4cff-9aa9-31c7c97a93f5] description = "division -> can divide two numbers" @@ -57,12 +66,21 @@ description = "division -> errors if there is nothing on the stack" [d5547f43-c2ff-4d5c-9cb0-2a4f6684c20d] description = "division -> errors if there is only one value on the stack" +[f224f3e0-b6b6-4864-81de-9769ecefa03f] +description = "division -> more than two values on the stack" + [ee28d729-6692-4a30-b9be-0d830c52a68c] description = "combined arithmetic -> addition and subtraction" [40b197da-fa4b-4aca-a50b-f000d19422c1] description = "combined arithmetic -> multiplication and division" +[f749b540-53aa-458e-87ec-a70797eddbcb] +description = "combined arithmetic -> multiplication and addition" + +[c8e5a4c2-f9bf-4805-9a35-3c3314e4989a] +description = "combined arithmetic -> addition and multiplication" + [c5758235-6eef-4bf6-ab62-c878e50b9957] description = "dup -> copies a value on the stack" diff --git a/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java b/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java index 9a43e11bf..bd36657b3 100644 --- a/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java +++ b/exercises/practice/forth/src/test/java/ForthEvaluatorTest.java @@ -48,6 +48,13 @@ public void testErrorIfAdditionAttemptedWithOneNumberOnTheStack() { .withMessage("Addition requires that the stack contain at least 2 values"); } + @Disabled("Remove to run test") + @Test + public void testAdditionForMoreThanTwoValuesOnTheStack() { + assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 +"))) + .containsExactly(1, 5); + } + @Disabled("Remove to run test") @Test public void testTwoNumbersCanBeSubtracted() { @@ -72,6 +79,13 @@ public void testErrorIfSubtractionAttemptedWithOneNumberOnTheStack() { .withMessage("Subtraction requires that the stack contain at least 2 values"); } + @Disabled("Remove to run test") + @Test + public void testSubtractionForMoreThanTwoValuesOnTheStack() { + assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 12 3 -"))) + .containsExactly(1, 9); + } + @Disabled("Remove to run test") @Test public void testTwoNumbersCanBeMultiplied() { @@ -94,6 +108,13 @@ public void testErrorIfMultiplicationAttemptedWithOneNumberOnTheStack() { .withMessage("Multiplication requires that the stack contain at least 2 values"); } + @Disabled("Remove to run test") + @Test + public void testMultiplicationForMoreThanTwoValuesOnTheStack() { + assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 2 3 *"))) + .containsExactly(1, 6); + } + @Disabled("Remove to run test") @Test public void testTwoNumbersCanBeDivided() { @@ -130,6 +151,13 @@ public void testErrorIfDivisionAttemptedWithOneNumberOnTheStack() { .withMessage("Division requires that the stack contain at least 2 values"); } + @Disabled("Remove to run test") + @Test + public void testDivisionForMoreThanTwoValuesOnTheStack() { + assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 12 3 /"))) + .containsExactly(1, 4); + } + @Disabled("Remove to run test") @Test public void testCombinedAdditionAndSubtraction() { @@ -142,6 +170,18 @@ public void testCombinedMultiplicationAndDivision() { assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("2 4 * 3 /"))).containsExactly(2); } + @Disabled("Remove to run test") + @Test + public void testCombinedMultiplicationAndAddition() { + assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 3 4 * +"))).containsExactly(13); + } + + @Disabled("Remove to run test") + @Test + public void testCombinedAdditionAndMultiplication() { + assertThat(forthEvaluator.evaluateProgram(Collections.singletonList("1 3 4 + *"))).containsExactly(7); + } + @Disabled("Remove to run test") @Test public void testDupCopiesAValueOnTheStack() { From cd1e0c11e83bcb2aac4852d3c9443a40d8f64a9e Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Tue, 19 Nov 2024 11:39:42 +0530 Subject: [PATCH 45/49] Updating tests for bob with problem-specifications --- exercises/practice/bob/.meta/config.json | 1 + exercises/practice/bob/.meta/tests.toml | 18 +++++++++++++++--- .../practice/bob/src/test/java/BobTest.java | 14 +++++++------- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/exercises/practice/bob/.meta/config.json b/exercises/practice/bob/.meta/config.json index 22fda09a3..a86461574 100644 --- a/exercises/practice/bob/.meta/config.json +++ b/exercises/practice/bob/.meta/config.json @@ -7,6 +7,7 @@ "austinlyons", "c-thornton", "FridaTveit", + "jagdish-15", "jmrunkle", "jtigger", "kytrinyx", diff --git a/exercises/practice/bob/.meta/tests.toml b/exercises/practice/bob/.meta/tests.toml index 630485579..5299e2895 100644 --- a/exercises/practice/bob/.meta/tests.toml +++ b/exercises/practice/bob/.meta/tests.toml @@ -1,6 +1,13 @@ -# This is an auto-generated file. Regular comments will be removed when this -# file is regenerated. Regenerating will not touch any manually added keys, -# so comments can be added in a "comment" key. +# 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. [e162fead-606f-437a-a166-d051915cea8e] description = "stating something" @@ -64,6 +71,7 @@ description = "alternate silence" [66953780-165b-4e7e-8ce3-4bcb80b6385a] description = "multiple line question" +include = false [5371ef75-d9ea-4103-bcfa-2da973ddec1b] description = "starting with whitespace" @@ -76,3 +84,7 @@ description = "other whitespace" [12983553-8601-46a8-92fa-fcaa3bc4a2a0] description = "non-question ending with whitespace" + +[2c7278ac-f955-4eb4-bf8f-e33eb4116a15] +description = "multiple line question" +reimplements = "66953780-165b-4e7e-8ce3-4bcb80b6385a" diff --git a/exercises/practice/bob/src/test/java/BobTest.java b/exercises/practice/bob/src/test/java/BobTest.java index c7a671206..801315b42 100644 --- a/exercises/practice/bob/src/test/java/BobTest.java +++ b/exercises/practice/bob/src/test/java/BobTest.java @@ -152,13 +152,6 @@ public void alternateSilence() { .isEqualTo("Fine. Be that way!"); } - @Disabled("Remove to run test") - @Test - public void multipleLineQuestion() { - assertThat(bob.hey("\nDoes this cryogenic chamber make me look fat?\nNo.")) - .isEqualTo("Whatever."); - } - @Disabled("Remove to run test") @Test public void startingWithWhitespace() { @@ -187,4 +180,11 @@ public void nonQuestionEndingWithWhiteSpace() { .isEqualTo("Whatever."); } + @Disabled("Remove to run test") + @Test + public void multipleLineQuestion() { + assertThat(bob.hey("\nDoes this cryogenic chamber make\n me look fat?")) + .isEqualTo("Sure."); + } + } From f00cba6ac012c7ae249aa6464db4709f4141f012 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Tue, 19 Nov 2024 11:06:33 +0530 Subject: [PATCH 46/49] Syncing docs, metadata and filepaths with problem-specifications --- exercises/practice/dot-dsl/.meta/config.json | 3 +++ .../practice/hamming/.docs/instructions.md | 10 +++++----- exercises/practice/hamming/.meta/config.json | 2 +- exercises/practice/luhn/.docs/instructions.md | 3 ++- exercises/practice/pov/.meta/config.json | 2 +- .../protein-translation/.docs/instructions.md | 8 ++++---- .../rna-transcription/.docs/instructions.md | 6 +++--- .../practice/square-root/.docs/instructions.md | 17 +++++++++++------ .../practice/square-root/.docs/introduction.md | 10 ++++++++++ .../state-of-tic-tac-toe/.docs/instructions.md | 2 +- .../practice/sublist/.docs/instructions.md | 4 ++-- 11 files changed, 43 insertions(+), 24 deletions(-) create mode 100644 exercises/practice/square-root/.docs/introduction.md diff --git a/exercises/practice/dot-dsl/.meta/config.json b/exercises/practice/dot-dsl/.meta/config.json index e3c063c3a..d1c57ef6e 100644 --- a/exercises/practice/dot-dsl/.meta/config.json +++ b/exercises/practice/dot-dsl/.meta/config.json @@ -16,6 +16,9 @@ "editor": [ "src/main/java/Node.java", "src/main/java/Edge.java" + ], + "invalidator": [ + "build.gradle" ] }, "blurb": "Write a Domain Specific Language similar to the Graphviz dot language.", diff --git a/exercises/practice/hamming/.docs/instructions.md b/exercises/practice/hamming/.docs/instructions.md index 020fdd02d..b9ae6efc5 100644 --- a/exercises/practice/hamming/.docs/instructions.md +++ b/exercises/practice/hamming/.docs/instructions.md @@ -1,6 +1,6 @@ # Instructions -Calculate the Hamming Distance between two DNA strands. +Calculate the Hamming distance between two DNA strands. Your body is made up of cells that contain DNA. Those cells regularly wear out and need replacing, which they achieve by dividing into daughter cells. @@ -9,18 +9,18 @@ In fact, the average human body experiences about 10 quadrillion cell divisions When cells divide, their DNA replicates too. Sometimes during this process mistakes happen and single pieces of DNA get encoded with the incorrect information. If we compare two strands of DNA and count the differences between them we can see how many mistakes occurred. -This is known as the "Hamming Distance". +This is known as the "Hamming distance". -We read DNA using the letters C,A,G and T. +We read DNA using the letters C, A, G and T. Two strands might look like this: GAGCCTACTAACGGGAT CATCGTAATGACGGCCT ^ ^ ^ ^ ^ ^^ -They have 7 differences, and therefore the Hamming Distance is 7. +They have 7 differences, and therefore the Hamming distance is 7. -The Hamming Distance is useful for lots of things in science, not just biology, so it's a nice phrase to be familiar with :) +The Hamming distance is useful for lots of things in science, not just biology, so it's a nice phrase to be familiar with :) ## Implementation notes diff --git a/exercises/practice/hamming/.meta/config.json b/exercises/practice/hamming/.meta/config.json index 5e2dba3ae..acf067955 100644 --- a/exercises/practice/hamming/.meta/config.json +++ b/exercises/practice/hamming/.meta/config.json @@ -43,7 +43,7 @@ "build.gradle" ] }, - "blurb": "Calculate the Hamming difference between two DNA strands.", + "blurb": "Calculate the Hamming distance between two DNA strands.", "source": "The Calculating Point Mutations problem at Rosalind", "source_url": "https://rosalind.info/problems/hamm/" } diff --git a/exercises/practice/luhn/.docs/instructions.md b/exercises/practice/luhn/.docs/instructions.md index 8cbe791fc..49934c106 100644 --- a/exercises/practice/luhn/.docs/instructions.md +++ b/exercises/practice/luhn/.docs/instructions.md @@ -22,7 +22,8 @@ The first step of the Luhn algorithm is to double every second digit, starting f We will be doubling ```text -4_3_ 3_9_ 0_4_ 6_6_ +4539 3195 0343 6467 +↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ (double these) ``` If doubling the number results in a number greater than 9 then subtract 9 from the product. diff --git a/exercises/practice/pov/.meta/config.json b/exercises/practice/pov/.meta/config.json index 451fa6122..a4e51ec6e 100644 --- a/exercises/practice/pov/.meta/config.json +++ b/exercises/practice/pov/.meta/config.json @@ -18,5 +18,5 @@ }, "blurb": "Reparent a graph on a selected node.", "source": "Adaptation of exercise from 4clojure", - "source_url": "https://www.4clojure.com/" + "source_url": "https://github.com/oxalorg/4ever-clojure" } diff --git a/exercises/practice/protein-translation/.docs/instructions.md b/exercises/practice/protein-translation/.docs/instructions.md index 7dc34d2ed..44880802c 100644 --- a/exercises/practice/protein-translation/.docs/instructions.md +++ b/exercises/practice/protein-translation/.docs/instructions.md @@ -2,12 +2,12 @@ Translate RNA sequences into proteins. -RNA can be broken into three nucleotide sequences called codons, and then translated to a polypeptide like so: +RNA can be broken into three-nucleotide sequences called codons, and then translated to a protein like so: RNA: `"AUGUUUUCU"` => translates to Codons: `"AUG", "UUU", "UCU"` -=> which become a polypeptide with the following sequence => +=> which become a protein with the following sequence => Protein: `"Methionine", "Phenylalanine", "Serine"` @@ -27,9 +27,9 @@ Protein: `"Methionine", "Phenylalanine", "Serine"` Note the stop codon `"UAA"` terminates the translation and the final methionine is not translated into the protein sequence. -Below are the codons and resulting Amino Acids needed for the exercise. +Below are the codons and resulting amino acids needed for the exercise. -| Codon | Protein | +| Codon | Amino Acid | | :----------------- | :------------ | | AUG | Methionine | | UUU, UUC | Phenylalanine | diff --git a/exercises/practice/rna-transcription/.docs/instructions.md b/exercises/practice/rna-transcription/.docs/instructions.md index 36da381f5..4dbfd3a27 100644 --- a/exercises/practice/rna-transcription/.docs/instructions.md +++ b/exercises/practice/rna-transcription/.docs/instructions.md @@ -1,12 +1,12 @@ # Instructions -Your task is determine the RNA complement of a given DNA sequence. +Your task is to determine the RNA complement of a given DNA sequence. Both DNA and RNA strands are a sequence of nucleotides. -The four nucleotides found in DNA are adenine (**A**), cytosine (**C**), guanine (**G**) and thymine (**T**). +The four nucleotides found in DNA are adenine (**A**), cytosine (**C**), guanine (**G**), and thymine (**T**). -The four nucleotides found in RNA are adenine (**A**), cytosine (**C**), guanine (**G**) and uracil (**U**). +The four nucleotides found in RNA are adenine (**A**), cytosine (**C**), guanine (**G**), and uracil (**U**). Given a DNA strand, its transcribed RNA strand is formed by replacing each nucleotide with its complement: diff --git a/exercises/practice/square-root/.docs/instructions.md b/exercises/practice/square-root/.docs/instructions.md index e9905e9d4..d258b8687 100644 --- a/exercises/practice/square-root/.docs/instructions.md +++ b/exercises/practice/square-root/.docs/instructions.md @@ -1,13 +1,18 @@ # Instructions -Given a natural radicand, return its square root. +Your task is to calculate the square root of a given number. -Note that the term "radicand" refers to the number for which the root is to be determined. -That is, it is the number under the root symbol. +- Try to avoid using the pre-existing math libraries of your language. +- As input you'll be given a positive whole number, i.e. 1, 2, 3, 4… +- You are only required to handle cases where the result is a positive whole number. -Check out the Wikipedia pages on [square root][square-root] and [methods of computing square roots][computing-square-roots]. +Some potential approaches: -Recall also that natural numbers are positive real whole numbers (i.e. 1, 2, 3 and up). +- Linear or binary search for a number that gives the input number when squared. +- Successive approximation using Newton's or Heron's method. +- Calculating one digit at a time or one bit at a time. -[square-root]: https://en.wikipedia.org/wiki/Square_root +You can check out the Wikipedia pages on [integer square root][integer-square-root] and [methods of computing square roots][computing-square-roots] to help with choosing a method of calculation. + +[integer-square-root]: https://en.wikipedia.org/wiki/Integer_square_root [computing-square-roots]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots diff --git a/exercises/practice/square-root/.docs/introduction.md b/exercises/practice/square-root/.docs/introduction.md new file mode 100644 index 000000000..1d692934f --- /dev/null +++ b/exercises/practice/square-root/.docs/introduction.md @@ -0,0 +1,10 @@ +# Introduction + +We are launching a deep space exploration rocket and we need a way to make sure the navigation system stays on target. + +As the first step in our calculation, we take a target number and find its square root (that is, the number that when multiplied by itself equals the target number). + +The journey will be very long. +To make the batteries last as long as possible, we had to make our rocket's onboard computer very power efficient. +Unfortunately that means that we can't rely on fancy math libraries and functions, as they use more power. +Instead we want to implement our own square root calculation. diff --git a/exercises/practice/state-of-tic-tac-toe/.docs/instructions.md b/exercises/practice/state-of-tic-tac-toe/.docs/instructions.md index f525d3585..1a03ebb6c 100644 --- a/exercises/practice/state-of-tic-tac-toe/.docs/instructions.md +++ b/exercises/practice/state-of-tic-tac-toe/.docs/instructions.md @@ -3,7 +3,7 @@ In this exercise, you're going to implement a program that determines the state of a [tic-tac-toe][] game. (_You may also know the game as "noughts and crosses" or "Xs and Os"._) -The games is played on a 3×3 grid. +The game is played on a 3×3 grid. Players take turns to place `X`s and `O`s on the grid. The game ends when one player has won by placing three of marks in a row, column, or along a diagonal of the grid, or when the entire grid is filled up. diff --git a/exercises/practice/sublist/.docs/instructions.md b/exercises/practice/sublist/.docs/instructions.md index 7535931af..8228edc6c 100644 --- a/exercises/practice/sublist/.docs/instructions.md +++ b/exercises/practice/sublist/.docs/instructions.md @@ -8,8 +8,8 @@ Given any two lists `A` and `B`, determine if: - None of the above is true, thus lists `A` and `B` are unequal Specifically, list `A` is equal to list `B` if both lists have the same values in the same order. -List `A` is a superlist of `B` if `A` contains a sub-sequence of values equal to `B`. -List `A` is a sublist of `B` if `B` contains a sub-sequence of values equal to `A`. +List `A` is a superlist of `B` if `A` contains a contiguous sub-sequence of values equal to `B`. +List `A` is a sublist of `B` if `B` contains a contiguous sub-sequence of values equal to `A`. Examples: From 1a859f12e0bf9e9826accc53ba12d2d1138bb708 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Wed, 20 Nov 2024 13:30:04 +0530 Subject: [PATCH 47/49] Syncing unsynced docs and metadata --- .../complex-numbers/.docs/instructions.md | 107 +++++++++++++++--- .../pythagorean-triplet/.meta/config.json | 4 +- 2 files changed, 91 insertions(+), 20 deletions(-) diff --git a/exercises/practice/complex-numbers/.docs/instructions.md b/exercises/practice/complex-numbers/.docs/instructions.md index 50b19aedf..2b8a7a49d 100644 --- a/exercises/practice/complex-numbers/.docs/instructions.md +++ b/exercises/practice/complex-numbers/.docs/instructions.md @@ -1,29 +1,100 @@ # Instructions -A complex number is a number in the form `a + b * i` where `a` and `b` are real and `i` satisfies `i^2 = -1`. +A **complex number** is expressed in the form `z = a + b * i`, where: -`a` is called the real part and `b` is called the imaginary part of `z`. -The conjugate of the number `a + b * i` is the number `a - b * i`. -The absolute value of a complex number `z = a + b * i` is a real number `|z| = sqrt(a^2 + b^2)`. The square of the absolute value `|z|^2` is the result of multiplication of `z` by its complex conjugate. +- `a` is the **real part** (a real number), -The sum/difference of two complex numbers involves adding/subtracting their real and imaginary parts separately: -`(a + i * b) + (c + i * d) = (a + c) + (b + d) * i`, -`(a + i * b) - (c + i * d) = (a - c) + (b - d) * i`. +- `b` is the **imaginary part** (also a real number), and -Multiplication result is by definition -`(a + i * b) * (c + i * d) = (a * c - b * d) + (b * c + a * d) * i`. +- `i` is the **imaginary unit** satisfying `i^2 = -1`. -The reciprocal of a non-zero complex number is -`1 / (a + i * b) = a/(a^2 + b^2) - b/(a^2 + b^2) * i`. +## Operations on Complex Numbers -Dividing a complex number `a + i * b` by another `c + i * d` gives: -`(a + i * b) / (c + i * d) = (a * c + b * d)/(c^2 + d^2) + (b * c - a * d)/(c^2 + d^2) * i`. +### Conjugate -Raising e to a complex exponent can be expressed as `e^(a + i * b) = e^a * e^(i * b)`, the last term of which is given by Euler's formula `e^(i * b) = cos(b) + i * sin(b)`. +The conjugate of the complex number `z = a + b * i` is given by: -Implement the following operations: +```text +zc = a - b * i +``` -- addition, subtraction, multiplication and division of two complex numbers, -- conjugate, absolute value, exponent of a given complex number. +### Absolute Value -Assume the programming language you are using does not have an implementation of complex numbers. +The absolute value (or modulus) of `z` is defined as: + +```text +|z| = sqrt(a^2 + b^2) +``` + +The square of the absolute value is computed as the product of `z` and its conjugate `zc`: + +```text +|z|^2 = z * zc = a^2 + b^2 +``` + +### Addition + +The sum of two complex numbers `z1 = a + b * i` and `z2 = c + d * i` is computed by adding their real and imaginary parts separately: + +```text +z1 + z2 = (a + b * i) + (c + d * i) + = (a + c) + (b + d) * i +``` + +### Subtraction + +The difference of two complex numbers is obtained by subtracting their respective parts: + +```text +z1 - z2 = (a + b * i) - (c + d * i) + = (a - c) + (b - d) * i +``` + +### Multiplication + +The product of two complex numbers is defined as: + +```text +z1 * z2 = (a + b * i) * (c + d * i) + = (a * c - b * d) + (b * c + a * d) * i +``` + +### Reciprocal + +The reciprocal of a non-zero complex number is given by: + +```text +1 / z = 1 / (a + b * i) + = a / (a^2 + b^2) - b / (a^2 + b^2) * i +``` + +### Division + +The division of one complex number by another is given by: + +```text +z1 / z2 = z1 * (1 / z2) + = (a + b * i) / (c + d * i) + = (a * c + b * d) / (c^2 + d^2) + (b * c - a * d) / (c^2 + d^2) * i +``` + +### Exponentiation + +Raising _e_ (the base of the natural logarithm) to a complex exponent can be expressed using Euler's formula: + +```text +e^(a + b * i) = e^a * e^(b * i) + = e^a * (cos(b) + i * sin(b)) +``` + +## Implementation Requirements + +Given that you should not use built-in support for complex numbers, implement the following operations: + +- **addition** of two complex numbers +- **subtraction** of two complex numbers +- **multiplication** of two complex numbers +- **division** of two complex numbers +- **conjugate** of a complex number +- **absolute value** of a complex number +- **exponentiation** of _e_ (the base of the natural logarithm) to a complex number diff --git a/exercises/practice/pythagorean-triplet/.meta/config.json b/exercises/practice/pythagorean-triplet/.meta/config.json index 6cfac6820..9905ac631 100644 --- a/exercises/practice/pythagorean-triplet/.meta/config.json +++ b/exercises/practice/pythagorean-triplet/.meta/config.json @@ -36,7 +36,7 @@ "build.gradle" ] }, - "blurb": "There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the triplet.", - "source": "Problem 9 at Project Euler", + "blurb": "Given an integer N, find all Pythagorean triplets for which a + b + c = N.", + "source": "A variation of Problem 9 from Project Euler", "source_url": "https://projecteuler.net/problem=9" } From 2dea9103e6f3c62ad3ca687b2efd5fb0d6a0483a Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Sat, 23 Nov 2024 20:43:20 +0530 Subject: [PATCH 48/49] Updating content.md of dynamic approach of chnage exercise --- .../dynamic-programming/content.md | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/exercises/practice/change/.approaches/dynamic-programming/content.md b/exercises/practice/change/.approaches/dynamic-programming/content.md index 7e264778f..640c58a47 100644 --- a/exercises/practice/change/.approaches/dynamic-programming/content.md +++ b/exercises/practice/change/.approaches/dynamic-programming/content.md @@ -44,25 +44,25 @@ It minimizes the number of coins needed by breaking down the problem into smalle ## Explanation -1. **Initialize Coins Usage Tracker**: +### Initialize Coins Usage Tracker - - If the `grandTotal` is negative, an exception is thrown immediately. - - We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. - - The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. +- If the `grandTotal` is negative, an exception is thrown immediately. +- We create a list `coinsUsed`, where each index `i` stores the most efficient combination of coins that sum up to the value `i`. +- The list is initialized with an empty list at index `0`, as no coins are needed to achieve a total of zero. -2. **Iterative Dynamic Programming**: +### Iterative Dynamic Programming - - For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. - - For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). - - If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. +- For each value `i` from 1 to `grandTotal`, we explore all available coin denominations to find the best combination that can achieve the total `i`. +- For each coin, we check if it can be part of the solution (i.e., if `coin <= i` and `coinsUsed[i - coin]` is a valid combination). +- If so, we generate a new combination by adding the current coin to the solution for `i - coin`. We then compare the size of this new combination with the existing best combination and keep the one with fewer coins. -3. **Result**: +### Result - - After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. - - If no valid combination exists for `grandTotal`, an exception is thrown. +- After processing all values up to `grandTotal`, the combination at `coinsUsed[grandTotal]` will represent the most efficient solution. +- If no valid combination exists for `grandTotal`, an exception is thrown. ## Time and Space Complexity -- The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. +The time complexity of this approach is **O(n * m)**, where `n` is the `grandTotal` and `m` is the number of available coin denominations. This is because we iterate over all coin denominations for each amount up to `grandTotal`. -- The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. +The space complexity is **O(n)** due to the list `coinsUsed`, which stores the most efficient coin combination for each total up to `grandTotal`. From 7ac1f159905de0ac31a505ae6044a41ad4f300b7 Mon Sep 17 00:00:00 2001 From: Jagdish Prajapati Date: Tue, 26 Nov 2024 23:02:18 +0530 Subject: [PATCH 49/49] Fixing consistancy issues in reference answer of Salary Calculator --- .../.meta/src/reference/java/SalaryCalculator.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/exercises/concept/salary-calculator/.meta/src/reference/java/SalaryCalculator.java b/exercises/concept/salary-calculator/.meta/src/reference/java/SalaryCalculator.java index c6e6ea140..fac9e15c3 100644 --- a/exercises/concept/salary-calculator/.meta/src/reference/java/SalaryCalculator.java +++ b/exercises/concept/salary-calculator/.meta/src/reference/java/SalaryCalculator.java @@ -8,11 +8,11 @@ public int bonusMultiplier(int productsSold) { return productsSold < 20 ? 10 : 13; } - public double bonusForProductsSold (int productsSold) { + public double bonusForProductsSold(int productsSold) { return productsSold * bonusMultiplier(productsSold); } - public double finalSalary (int daysSkipped, int productsSold) { + public double finalSalary(int daysSkipped, int productsSold) { double finalSalary = 1000.0 * salaryMultiplier(daysSkipped) + bonusForProductsSold(productsSold); return finalSalary > 2000.0 ? 2000.0 : finalSalary; }