Skip to content

Instantly share code, notes, and snippets.

@viktorpenelski
Created October 13, 2023 19:27
Show Gist options
  • Save viktorpenelski/d3494e31a9909863ed9aa043637fb7ff to your computer and use it in GitHub Desktop.
Save viktorpenelski/d3494e31a9909863ed9aa043637fb7ff to your computer and use it in GitHub Desktop.
13.10.2023 - Java Advanced - exam prep
package easterBasket;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
public class Basket {
private List<Egg> data; // 10, 3, 5, 42 list addEgg -> O(1) getStrongest -> O(N)
// get strongest -> O(N) heap instead of list addEgg -> O(log N) getStrongest -> O(1)
// get by color -> O(N) Map -> O(1) get/remove "Red" -> Egg(..), "Blue" -> Egg(..);
// remove by color -> O(N)
private String material;
private int capacity;
public Basket(String material, int capacity) {
this.material = material;
this.capacity = capacity;
this.data = new ArrayList<>();
}
public void addEgg(Egg egg) {
if (data.size() >= capacity) {
throw new RuntimeException("The basket is out of capacity!");
}
data.add(egg);
}
public boolean removeEgg(String color) {
int initialEggCount = data.size();
data = data.stream()
.filter(egg -> !egg.getColor().equals(color))
.collect(Collectors.toList());
return data.size() != initialEggCount;
// red, green, blue (3) -> removeEgg(red) -> green, blue (2) 2 != 3?? true
// red, green blue (3) -> removeEgg(gray) -> red, green, blue (3) 3 != 3?? false
}
public Egg getStrongestEgg() {
if (data.isEmpty()) {
return null;
}
var strongestEgg = data.get(0);
for (Egg egg : data) {
if (egg.getStrength() > strongestEgg.getStrength()) {
strongestEgg = egg;
}
}
return strongestEgg;
}
public Egg getEgg(String color) {
return data.stream()
.filter(egg -> egg.getColor().equals(color))
.findFirst()
.orElse(null);
}
public int getCount() {
return data.size();
}
public String report() {
var sj = new StringJoiner("\n");
sj.add(material +" basket contains:");
for (Egg egg : data) {
sj.add(egg.toString());
}
return sj.toString();
}
public Egg getStrongestEggStream() {
return data.stream().reduce(
(egg1, egg2) -> egg1.getStrength() > egg2.getStrength() ? egg1 : egg2
).orElse(null);
}
}
package easterBasket;
public class Egg {
private String color;
private int strength;
private String shape;
public Egg(String color, int strength, String shape) {
this.color = color;
this.strength = strength;
this.shape = shape;
}
@Override
public String toString() {
return String.format("%s egg, with %d strength and %s shape.", color, strength, shape);
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public String getShape() {
return shape;
}
public void setShape(String shape) {
this.shape = shape;
}
}
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.Scanner;
public class Meetings {
public static void main(String[] args) {
var sc = new Scanner(System.in);
Deque<Integer> males = parseInputAsStack(sc.nextLine());
Deque<Integer> females = parseInputAsQueue(sc.nextLine());
int matches = 0;
while (!males.isEmpty() && !females.isEmpty()) {
var female = getPerson(females); // x
if (female == null) {
break;
}
var male = getPerson(males);
if (male == null) {
females.addFirst(female);
break;
}
if (female.equals(male)) {
matches++;
} else {
males.addFirst(male - 2);
}
}
System.out.println(prettifyOutput(matches, males, females));
}
private static String prettifyOutput(int matches,
Deque<Integer> males,
Deque<Integer> females) {
// males.toString() -> "[1, 2, 5]"
var stringifiedMales = males.toString();
var stringifiedFemales = females.toString();
var malesLeft = (males.isEmpty()
? "none"
: stringifiedMales.substring(1, stringifiedMales.length() - 1));
var femalesLeft = (females.isEmpty()
? "none"
: stringifiedFemales.substring(1, stringifiedFemales.length() - 1));
return "Matches: " + matches +
"\nMales left: " + malesLeft +
"\nFemales left: " + femalesLeft;
}
private static Integer getPersonRec(Deque<Integer> people) {
if (people.isEmpty()) {
return null;
}
var person = people.pollFirst();
if (person <= 0) {
return getPersonRec(people);
}
if (person % 25 == 0) {
people.pollFirst();
return getPersonRec(people);
}
return person;
}
private static Integer getPerson(Deque<Integer> people) {
while(!people.isEmpty()) { // [ 25, 10 ]
var person = people.pollFirst();
if (person <= 0) {
continue;
}
if (person % 25 == 0) { // person = 25; people = [ 10 ]
var thisWouldHaveBeenATen = people.pollFirst(); // people = [ ]
continue;
}
return person;
}
return null;
}
private static Deque<Integer> parseInputAsQueue(String nextLine) {
return Arrays.stream(nextLine.split(" "))
.map(Integer::valueOf)
.collect(ArrayDeque::new,
ArrayDeque::addLast,
ArrayDeque::addAll);
}
private static ArrayDeque<Integer> parseInputAsStack(String line) {
var stack = new ArrayDeque<Integer>();
for (String input : line.split(" ")) {
stack.addFirst(Integer.valueOf(input));
}
return stack;
}
}
import java.util.Scanner;
// array solution
public class PawnWars {
private static String TEST_INPUTS = "------b-\n" +
"--------\n" +
"--------\n" +
"--------\n" +
"--------\n" +
"-w------\n" +
"--------\n" +
"--------\n";
public static void main(String[] args) {
var sc = new Scanner(System.in);
char[][] board = inputToBoard(sc);
boolean whiteToMove = true;
while(true) {
if (whiteToMove) {
String captured = canPawnCapture(board, -1,'w', 'b');
if (captured != null) {
System.out.println(String.format("Game over! White capture on %s.", captured));
break;
}
String promoted = movePawnForward(board, -1, 'w');
if (promoted != null) {
System.out.println(String.format("Game over! White pawn is promoted to a queen at %s.", promoted));
break;
}
} else {
String captured = canPawnCapture(board, 1, 'b', 'w');
if (captured != null) {
System.out.println(String.format("Game over! Black capture on %s.", captured));
break;
}
String promoted = movePawnForward(board, 1, 'b');
if (promoted != null) {
System.out.println(String.format("Game over! Black pawn is promoted to a queen at %s.", promoted));
break;
}
}
whiteToMove = !whiteToMove;
}
}
private static String coordinatesToChessNotation(int[] coordinates) {
// [0, 1]
int row = 8 - coordinates[0];
char col = (char)('a' + coordinates[1]);
return String.format("%c%d", col, row);
}
private static String movePawnForward(char[][] board, int direction, char pawn) {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (board[row][col] == pawn) {
if ((row + direction == 0 && pawn == 'w')|| (row + direction == 7 && pawn == 'b')) {
return coordinatesToChessNotation(new int[]{row + direction, col});
}
board[row][col] = '-';
board[row + direction][col] = pawn;
return null;
}
}
}
return null;
}
private static String canPawnCapture(char[][] board, int direction, char pawn, char enemyPawn) {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (board[row][col] == pawn) {
if ((row + direction >= 0
&& col - 1 >= 0
) && board[row + direction][col - 1] == enemyPawn
) {
return coordinatesToChessNotation(new int[]{row + direction, col - 1});
}
if ((row + direction >= 0
&& row+direction < board.length
&& col + 1 < board[row].length
) && board[row + direction][col + 1] == enemyPawn
) {
return coordinatesToChessNotation(new int[]{row + direction, col + 1});
}
return null;
}
}
}
return null;
}
private static void printBoard(char[][] board) {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
System.out.print(board[row][col]);
}
System.out.println();
}
}
private static char[][] inputToBoard(Scanner sc) {
char[][] board = new char[8][8];
for (int row = 0; row < 8; row++) {
var line = sc.nextLine();
for (int col = 0; col < 8; col++) {
board[row][col] = line.charAt(col);
}
}
return board;
}
}
import java.util.*;
public class PawnWarsNoArr {
// in java 16 and above, this class can be represented as:
// private record Position(int row, int col) {}
private static class Position {
private final int row;
private final int col;
public Position(int row, int col) {
this.row = row;
this.col = col;
}
public Position moveUp() {
return new Position(this.row - 1, this.col);
}
public Position moveDown() {
return new Position(this.row + 1, this.col);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Position position = (Position) o;
return row == position.row && col == position.col;
}
@Override
public int hashCode() {
return Objects.hash(row, col);
}
@Override
public String toString() {
int row = 8 - this.row;
char col = (char)('a' + this.col);
return String.format("%c%d", col, row);
}
}
private static class GameState {
private final Position whitePawn;
private final Position blackPawn;
private final boolean whiteToMove;
private String gameOverText;
public GameState(Position whitePawn, Position blackPawn, boolean whiteToMove) {
this.whitePawn = whitePawn;
this.blackPawn = blackPawn;
this.whiteToMove = whiteToMove;
this.gameOverText = "n/a";
}
public Optional<GameState> nextState() {
Optional<Position> capture = checkForCapture();
if (!capture.isEmpty()) {
this.gameOverText = String.format(
"Game over! %s capture on %s.",
whiteToMove ? "White" : "Black",
capture.get()
);
return Optional.empty();
}
GameState nextState = moveOneRow();
Optional<Position> promoted = nextState.checkForPromotion();
if (!promoted.isEmpty()) {
this.gameOverText = String.format("Game over! %s pawn is promoted to a queen at %s.",
whiteToMove ? "White" : "Black",
promoted.get()
);
return Optional.empty();
}
return Optional.of(nextState);
}
private Optional<Position> checkForCapture() {
if (whiteToMove) {
Set<Position> capturable = Set.of(
new Position(whitePawn.row - 1, whitePawn.col),
new Position(whitePawn.row - 1, whitePawn.col - 1),
new Position(whitePawn.row - 1, whitePawn.col + 1)
);
if (capturable.contains(blackPawn)) {
// white captures on the black pawn square
return Optional.of(blackPawn);
}
} else {
Set<Position> capturable = Set.of(
new Position(blackPawn.row + 1, blackPawn.col),
new Position(blackPawn.row + 1, blackPawn.col - 1),
new Position(blackPawn.row + 1, blackPawn.col + 1)
);
if (capturable.contains(whitePawn)) {
// black captures on the white pawn square
return Optional.of(whitePawn);
}
}
return Optional.empty();
}
private Optional<Position> checkForPromotion() {
if (whitePawn.row == 0) {
return Optional.of(whitePawn);
}
if (blackPawn.row == 7) {
return Optional.of(blackPawn);
}
return Optional.empty();
}
private GameState moveOneRow() {
if (whiteToMove) {
return new GameState(whitePawn.moveUp(), blackPawn, !whiteToMove);
}
return new GameState(whitePawn, blackPawn.moveDown(), !whiteToMove);
}
@Override
public String toString() {
return gameOverText;
}
}
private static GameState parseInput(Scanner sc) {
Position whitePawn = null;
Position blackPawn = null;
for (int row = 0; row < 8; row++) {
String line = sc.nextLine();
for (int col = 0; col < 8; col++) {
char ch = line.charAt(col);
if (ch == 'b') {
blackPawn = new Position(row, col);
}
if (ch == 'w') {
whitePawn = new Position(row, col);
}
}
}
return new GameState(whitePawn, blackPawn, true);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
GameState gameState = parseInput(sc);
Optional<GameState> next = gameState.nextState();
while (!next.isEmpty()) {
gameState = next.get();
next = gameState.nextState();
}
System.out.println(gameState);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment