Skip to content

Instantly share code, notes, and snippets.

@asm0dey
Last active July 28, 2019 21:48
Show Gist options
  • Save asm0dey/ee80e0966f804f6474b680bdd2f5973d to your computer and use it in GitHub Desktop.
Save asm0dey/ee80e0966f804f6474b680bdd2f5973d to your computer and use it in GitHub Desktop.
package some;
import java.util.*;
import java.util.stream.Stream;
import static java.lang.Integer.parseInt;
import static java.util.Collections.singletonList;
import static java.util.Locale.ENGLISH;
public class Solver {
int solve(int numberOfRows, String occupied) {
Map<Integer, List<Character>> occupiedMap = getOccupiedMap(occupied.toLowerCase(ENGLISH), numberOfRows);
int result = 0;
for (int i = 1; i <= numberOfRows; i++) {
List<Character> occupiedSeatsOnRow = occupiedMap.get(i);
if (occupiedSeatsOnRow == null) {
result += 3;
continue;
}
Collections.sort(occupiedSeatsOnRow);
boolean aOccupied = false;
boolean dOccupied = false;
boolean hOccupied = false;
for (Character seat : occupiedSeatsOnRow) {
if (seat == 'i') throw new IllegalArgumentException("I seat should not exist");
if (seat >= 'a' && seat <= 'c') aOccupied = true;
if (seat >= 'h' && seat <= 'k') hOccupied = true;
if (seat >= 'e' && seat <= 'f') dOccupied = true;
}
if (!dOccupied) {
int countOfMiddleOccupied = 0;
for (Character seat : occupiedSeatsOnRow) {
if (seat >= 'd' && seat <= 'g') countOfMiddleOccupied++;
}
if (countOfMiddleOccupied > 1) dOccupied = true;
}
if (!aOccupied) result++;
if (!dOccupied) result++;
if (!hOccupied) result++;
}
return result;
}
private Map<Integer, List<Character>> getOccupiedMap(String occupied, int numberOfRows) {
if (occupied.length() == 0) return new HashMap<>();
Map<Integer, List<Character>> occupiedMap = new HashMap<>();
Stream
.of(occupied.split(" "))
.peek(s -> {
if (Integer.valueOf(s.substring(0, s.length() - 1)) > numberOfRows) {
throw new IllegalArgumentException("Occupied seat on nonexistent row detected");
}
})
.forEach(s -> occupiedMap.compute(parseInt(s.substring(0, s.length() - 1)), (integer, characters) -> {
char currentChar = s.charAt(1);
if (characters == null) return new ArrayList<>(singletonList(currentChar));
characters.add(currentChar);
return characters;
}));
return occupiedMap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment