Last active
January 26, 2023 07:24
-
-
Save alexanderankin/2505f0b970baf66e9d6d8e7d643e7787 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.ArrayList; | |
| import java.util.Collection; | |
| import java.util.List; | |
| public class StepsNumWays { | |
| public static void main(String[] args) { | |
| StepsNumWays solution = new StepsNumWays(); | |
| System.out.println(solution.solve(2, List.of(1, 2))); | |
| System.out.println(solution.solve(3, List.of(1, 2))); | |
| System.out.println(solution.solve(3, List.of(1, 2, 3))); | |
| System.out.println(solution.solve(4, List.of(1, 2, 3))); | |
| System.out.println(solution.solve(4, List.of(1, 2))); | |
| } | |
| public int solve(int steps, Collection<Integer> ways) { | |
| System.out.printf("solving for %s (%s)%n", steps, ways); | |
| return solve(steps, new ArrayList<>(), ways); | |
| } | |
| private int solve(int steps, ArrayList<Integer> taken, Collection<Integer> ways) { | |
| int sum = 0; | |
| for (Integer way : ways) { | |
| if (way == steps) { | |
| sum += 1; | |
| taken.add(way); | |
| System.out.println("way: " + taken); | |
| taken.remove(taken.size() - 1); | |
| } else if (way < steps) { | |
| taken.add(way); | |
| int solve = solve(steps - way, taken, ways); | |
| taken.remove(taken.size() - 1); | |
| sum += solve; | |
| } | |
| } | |
| return sum; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.junit.jupiter.params.ParameterizedTest; | |
| import org.junit.jupiter.params.provider.CsvSource; | |
| import java.util.List; | |
| import java.util.stream.Stream; | |
| import static org.junit.jupiter.api.Assertions.assertEquals; | |
| class StepsNumWaysTest { | |
| StepsNumWays solution = new StepsNumWays(); | |
| @ParameterizedTest | |
| @CsvSource({ | |
| "2,2,1:2", | |
| "3,3,1:2", | |
| "4,3,1:2:3", | |
| "7,4,1:2:3", | |
| "5,4,1:2" | |
| }) | |
| void test(int expected, int input, String waysString) { | |
| List<Integer> ways = Stream.of(waysString.split(":")) | |
| .map(Integer::parseInt) | |
| .toList(); | |
| assertEquals(expected, solution.solve(input, ways)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment