Last active
July 28, 2019 21:48
-
-
Save asm0dey/ee80e0966f804f6474b680bdd2f5973d 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
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