Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Iterator;
- import java.util.LinkedList;
- import java.util.stream.Collector;
- import java.util.stream.Collectors;
- /**
- * This class implements a game of Row of Bowls.
- * For the games rules see Blatt05. The goal is to find an optimal strategy.
- */
- public class RowOfBowls {
- public RowOfBowls() {
- }
- /**
- * Implements an optimal game using dynamic programming
- * @param values array of the number of marbles in each bowl
- * @return number of game points that the first player gets, provided both parties play optimally
- */
- /*public int maxGain(int[] values)
- {
- // TODO
- }
- */
- /**
- * Implements an optimal game recursively.
- *
- * @param values array of the number of marbles in each bowl
- * @return number of game points that the first player gets, provided both parties play optimally
- */
- public int maxGainRecursive(int[] values) {
- // TODO
- LinkedList<Integer> list_values
- = (LinkedList<Integer>) Arrays.stream(values).boxed().collect(Collectors.toList());
- return maxGainRecursive(list_values, 0, 0, 1);
- }
- public int maxGainRecursive(LinkedList<Integer> values, int score_a, int score_b, int player) {
- // TODO
- //rekursionsende wenn das spiel beendet
- if (values.isEmpty()){
- int max = Math.max(score_a, score_b);
- int min = Math.min(score_a, score_b);
- return max - min;
- }
- // 7 4 3 2 -> 7 2 koennen in diesem zug genommen werden
- int num_l = values.getFirst(); //7
- int num_r = values.getLast(); //2
- LinkedList<Integer> values_left = new LinkedList<>(values.subList(1, values.size()));
- LinkedList<Integer> values_right = new LinkedList<>(values.subList(0, values.size() - 1));
- //rekursiver aufruf linker teilbaum
- if (player == -1){ //spieler:in A
- score_a += num_l;
- }
- else score_b += num_l;
- int left = -maxGainRecursive(values_left, score_a, score_b, -player);
- //rekursiver aufruf rechter teilbaum
- if (player == -1){ //spieler:in A
- score_a += num_r;
- }
- else score_b += num_r;
- int right = -maxGainRecursive(values_right, score_a, score_b, -player);
- return Math.max(left, right);
- }
- /**
- * Calculates an optimal sequence of bowls using the partial solutions found in maxGain(int values)
- * @return optimal sequence of chosen bowls (represented by the index in the values array)
- */
- /*public Iterable<Integer> optimalSequence()
- {
- // TODO
- }
- */
- public static void main(String[] args)
- {
- // For Testing
- RowOfBowls game = new RowOfBowls();
- int[] values = {7, 4, 3, 2};
- System.out.println("Max gain (recursive): " + game.maxGainRecursive(values));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement