├── .gitignore ├── Easy ├── AddemUp.java ├── AreTheClumpsNormal.java ├── AsciiArt.java ├── BalancedTernaryComputerEncode.java ├── BankRobbers.java ├── BlowingFuse.java ├── BracketsExtremeEdition.java ├── BrickInTheWall.java ├── BulkEmailGenerator.java ├── ChuckNorris.java ├── CountAsICount.java ├── CreditCardVerifierLuhnsAlgorithm.java ├── Darts.java ├── DeadMensShot.java ├── Defibrillators.java ├── DisorderedFirstContact.java ├── DisorderedFirstContactV2.java ├── EncryptionDecryptionOfEnigmaMachine.java ├── GhostLegs.java ├── GuessingNCheating.java ├── HoochClash.java ├── HorseRacingDuals.java ├── HorseRacingHyperDuals.java ├── HowTimeFlies.java ├── HungerGames.java ├── IsbnCheckDigit.java ├── JackSilverTheCasino.java ├── Lumen.java ├── MarsLanderEpisode1.java ├── MayTheTriforceBeWithYou.java ├── MimeType.java ├── MorelletsRandomLines.java ├── NatureOfQuadrilterals.java ├── OneDSpreadsheet.java ├── OrderOfSuccession.java ├── OrganicCompounds.java ├── PiratesTreasure.java ├── PlagueJR.java ├── PowerOfThorEpisode1.java ├── RectangularBlockSpinner.java ├── RooksMovements.java ├── RubiksCubeMovements.java ├── RugbyScore.java ├── SelfDrivingCarTesting.java ├── SimpleAwale.java ├── Smooth.java ├── Temperatures.java ├── TextFormatting.java ├── TheDart101.java ├── TheDescent.java ├── TheFrogJump1.java ├── TheHoochClashGrouch.java ├── TheRiver1.java ├── TheRiver2.java ├── TheTravellingSalesmanProblem.java ├── WhatsSoComplexAboutMandelbrot.java └── XmlMdf2016.java ├── Hard └── TheLastCrusadeEpisode2.java ├── Medium ├── AChildsPlay.java ├── Aneo.java ├── BenderEpisode1.java ├── CGFungeInterpreter.java ├── ConwaySequence.java ├── DepotOrganization.java ├── DiceProbabilityCalculator.java ├── DigitSumSuccessor.java ├── DigitSumSuccessor2.java ├── DontPanicEpisode1.java ├── DwarfsStandingOnTheShouldersOfGiants.java ├── ElementaryCellularAutomaton.java ├── FactorialVsExponential.java ├── FindTheWinningStrategy.java ├── FoldingPaper.java ├── ForestFire.java ├── GoroWantChocolate.java ├── GravityCentrifugeTuning.java ├── HorseHyperracingHyperduals.java ├── JumpingFrogs.java ├── LengthOfSyracuseConjectureSequence.java ├── MayanCalculation.java ├── MicroAssembly.java ├── NetworkCabling.java ├── NumberOfLettersInANumberBinary.java ├── RegularPolygons.java ├── RoadTrip.java ├── RobberyOptimisation.java ├── Rotatetris.java ├── Scrabble.java ├── ShadowsOfTheKnightEpisode1.java ├── ShortAccountsMakeLongFriends.java ├── SkynetRevolutionEpisode1.java ├── SnakeEncoding.java ├── StallTilt.java ├── StockExchangeLosses.java ├── SudokuSolver.java ├── TelephoneNumbers.java ├── TheGift.java ├── TheGrandFestival1.java ├── TheLastCrusadeEpisode1.java ├── TheOptimalUrinalProblem.java ├── ThereIsNoSpoonEpisode1.java ├── TheseRomansAreCrazy.java ├── TritsBalancedTernaryComputing.java └── WinamaxBattle.java ├── README.md ├── VeryHard └── MusicScores.java └── link.png /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | -------------------------------------------------------------------------------- /Easy/AddemUp.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.List; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Auto-generated code below aims at helping you parse 8 | * the standard input according to the problem statement. 9 | **/ 10 | class Solution { 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int N = in.nextInt(); 15 | List list = new ArrayList<>(N); 16 | for (int i = 0; i < N; i++) { 17 | list.add(in.nextInt()); 18 | } 19 | Collections.sort(list); 20 | 21 | int total = 0; 22 | 23 | while (list.size() > 1) { 24 | int nb1 = list.remove(1); 25 | int nb2 = list.remove(0); 26 | int sum = nb1 + nb2; 27 | list.add(sum); 28 | Collections.sort(list); 29 | total += sum; 30 | } 31 | System.out.println(total); 32 | } 33 | } -------------------------------------------------------------------------------- /Easy/AreTheClumpsNormal.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | 12 | int[] numbers = in.nextLine().chars().map(i -> i - '0').toArray(); 13 | 14 | int min = 1; // value for mod 1 15 | 16 | for (int j = 2; j <= 9; j++) { 17 | int nbModular = 1; 18 | int currModulo = numbers[0] % j; 19 | 20 | for (int i = 1; i < numbers.length; i++) { 21 | int tmp = numbers[i] % j; 22 | 23 | if (currModulo != tmp) { 24 | nbModular++; 25 | currModulo = tmp; 26 | } 27 | } 28 | 29 | if (min > nbModular) { 30 | System.out.println(j); 31 | return; 32 | } 33 | 34 | min = nbModular; 35 | } 36 | 37 | System.out.println("Normal"); 38 | } 39 | } -------------------------------------------------------------------------------- /Easy/AsciiArt.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | public static void main(String args[]) { 9 | Scanner in = new Scanner(System.in); 10 | int L = in.nextInt(); 11 | int H = in.nextInt(); 12 | if (in.hasNextLine()) { 13 | in.nextLine(); 14 | } 15 | String text = in.nextLine().toUpperCase(); 16 | 17 | for (int i = 0; i < H; i++) { 18 | String ROW = in.nextLine(); 19 | 20 | for(int j = 0; j < text.length(); j++) { 21 | int delta = text.charAt(j) - 65; // Ascii code for 'A' 22 | if (delta < 0 || delta >= 26) { 23 | delta = 26; 24 | } 25 | 26 | System.out.print(ROW.substring(L * delta, L * (delta + 1))); 27 | } 28 | System.out.println(); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /Easy/BalancedTernaryComputerEncode.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int N = in.nextInt(); 12 | 13 | boolean negative = N < 0; 14 | N = Math.abs(N); 15 | 16 | int[] base = new int[]{0, 1, -1}; 17 | String strP = "01T"; 18 | String strN = "0T1"; 19 | 20 | String result = ""; 21 | do{ 22 | int remaining = N % 3; 23 | 24 | N -= base[remaining]; 25 | result = (negative ? strN.charAt(remaining) : strP.charAt(remaining)) + result; 26 | 27 | N = N / 3; 28 | } while(N > 0); 29 | 30 | System.out.println(result); 31 | } 32 | } -------------------------------------------------------------------------------- /Easy/BankRobbers.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | 10 | static int nbDigit = 10; 11 | static int nbVowels = 5; 12 | 13 | public static void main(String args[]) { 14 | Scanner in = new Scanner(System.in); 15 | int R = in.nextInt(); 16 | int V = in.nextInt(); 17 | 18 | int[] robbers = new int[R]; 19 | for (int i = 0; i < V; i++) { 20 | int C = in.nextInt(); 21 | int N = in.nextInt(); 22 | 23 | int combination = (int) Math.pow(nbDigit, N) * (int) Math.pow(nbVowels, (C - N)); 24 | robbers[0] += combination; 25 | Arrays.sort(robbers); 26 | } 27 | 28 | System.out.println(robbers[R - 1]); 29 | } 30 | } -------------------------------------------------------------------------------- /Easy/BlowingFuse.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int n = in.nextInt(); 12 | int m = in.nextInt(); 13 | int c = in.nextInt(); 14 | 15 | int[] devices = new int[n]; 16 | boolean[] devicesOn = new boolean[n]; 17 | for (int i = 0; i < n; i++) { 18 | devices[i] = in.nextInt(); 19 | } 20 | 21 | boolean blown = false; 22 | int min = c; 23 | int tmp = c; 24 | for (int i = 0; i < m; i++) { 25 | int mx = in.nextInt() - 1; 26 | 27 | if (devicesOn[mx]) { 28 | tmp += devices[mx]; 29 | } else { 30 | tmp -= devices[mx]; 31 | } 32 | 33 | if (tmp < 0) { 34 | blown = true; 35 | break; 36 | } 37 | 38 | if (tmp < min) { 39 | min = tmp; 40 | } 41 | 42 | devicesOn[mx] = !devicesOn[mx]; 43 | } 44 | 45 | if (blown) { 46 | System.out.println("Fuse was blown."); 47 | } else { 48 | System.out.println("Fuse was not blown."); 49 | System.out.println("Maximal consumed current was " + (c - min) + " A."); 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /Easy/BracketsExtremeEdition.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Stack; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | String expression = in.next(); 13 | 14 | Stack stack = new Stack<>(); 15 | 16 | boolean found = true; 17 | for (Character c : expression.toCharArray()) { 18 | switch (c) { 19 | case '{': 20 | case '(': 21 | case '[': 22 | stack.push(c); 23 | break; 24 | case '}': 25 | if (stack.isEmpty() || stack.pop() != '{') { 26 | found = false; 27 | } 28 | break; 29 | case ')': 30 | if (stack.isEmpty() || stack.pop() != '(') { 31 | found = false; 32 | } 33 | break; 34 | case ']': 35 | if (stack.isEmpty() || stack.pop() != '[') { 36 | found = false; 37 | } 38 | break; 39 | } 40 | 41 | if (!found) { 42 | break; 43 | } 44 | } 45 | 46 | if (found) { 47 | found = stack.isEmpty(); 48 | } 49 | 50 | System.out.println(found ? "true" : "false"); 51 | } 52 | } -------------------------------------------------------------------------------- /Easy/BrickInTheWall.java: -------------------------------------------------------------------------------- 1 | import java.text.DecimalFormat; 2 | import java.util.ArrayList; 3 | import java.util.Collections; 4 | import java.util.List; 5 | import java.util.Scanner; 6 | 7 | /** 8 | * Auto-generated code below aims at helping you parse 9 | * the standard input according to the problem statement. 10 | **/ 11 | class Solution { 12 | 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | int X = in.nextInt(); 16 | int N = in.nextInt(); 17 | List bricks = new ArrayList<>(); 18 | for (int i = 0; i < N; i++) { 19 | bricks.add(in.nextInt()); 20 | } 21 | 22 | bricks.sort(Collections.reverseOrder()); 23 | 24 | double W = 0d; 25 | 26 | for (int i = 0; i < N; i++) { 27 | int L = i / X; 28 | W += L * 0.65 * bricks.get(i); 29 | } 30 | 31 | System.out.println(new DecimalFormat("0.000").format(W)); 32 | } 33 | } -------------------------------------------------------------------------------- /Easy/BulkEmailGenerator.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.regex.Matcher; 3 | import java.util.regex.Pattern; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int N = in.nextInt(); 14 | in.nextLine(); 15 | 16 | StringBuilder builder = new StringBuilder(); 17 | 18 | for (int i = 0; i < N; i++) { 19 | builder.append(in.nextLine()).append("\n"); 20 | } 21 | 22 | String expr = "\\((.*?)\\)"; 23 | Pattern p = Pattern.compile(expr, Pattern.DOTALL); 24 | Matcher m = p.matcher(builder); 25 | 26 | StringBuilder res = new StringBuilder(); 27 | 28 | int index = 0; 29 | while (m.find()) { 30 | String group = m.group(); 31 | String[] grouped = group.substring(1, group.length() - 1).split("\\|", -1); 32 | String tmp = grouped[index++ % grouped.length]; 33 | m.appendReplacement(res, tmp); 34 | } 35 | 36 | m.appendTail(res); 37 | System.out.println(res); 38 | } 39 | } -------------------------------------------------------------------------------- /Easy/ChuckNorris.java: -------------------------------------------------------------------------------- 1 | import java.io.UnsupportedEncodingException; 2 | import java.util.Scanner; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | 10 | public static void main(String[] args) throws UnsupportedEncodingException { 11 | Scanner in = new Scanner(System.in); 12 | String MESSAGE = in.nextLine(); 13 | 14 | StringBuilder binString = new StringBuilder(); 15 | for (byte b : MESSAGE.getBytes()) { 16 | StringBuilder tmp = new StringBuilder(Integer.toBinaryString(b)); 17 | while (tmp.length() < 7) { 18 | tmp.insert(0, "0"); 19 | } 20 | 21 | binString.append(tmp); 22 | } 23 | 24 | char currentValue = ' '; 25 | StringBuilder result = new StringBuilder(); 26 | 27 | for (char c : binString.toString().toCharArray()) { 28 | if (currentValue != c) { 29 | if (c == '1') { 30 | result.append(" 0 0"); 31 | } else { 32 | result.append(" 00 0"); 33 | } 34 | currentValue = c; 35 | } else { 36 | result.append("0"); 37 | } 38 | } 39 | 40 | System.out.println(result.toString().trim()); 41 | } 42 | } -------------------------------------------------------------------------------- /Easy/CountAsICount.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | static int sum = 0; 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int n = in.nextInt(); 14 | 15 | calc(n, 0, 1); 16 | 17 | System.out.println(sum); 18 | } 19 | 20 | private static void calc(int currentSum, int round, int val) { 21 | if (round > 4) { 22 | return; 23 | } 24 | if (currentSum == 50) { 25 | sum += val; 26 | return; 27 | } 28 | 29 | for (int i = 1; i <= 12 && 50 - currentSum >= i; i++) { 30 | calc(currentSum + i, round + 1, val * (i == 1 ? 1 : 2)); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Easy/CreditCardVerifierLuhnsAlgorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.stream.IntStream; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int n = in.nextInt(); 13 | in.nextLine(); 14 | IntStream.range(0, n).forEach(i -> { 15 | String card = in.nextLine().replaceAll(" ", ""); 16 | 17 | int sum = 0; 18 | for (int j = card.length() - 1; j >= 0; j--) { 19 | int nb = Character.getNumericValue(card.charAt(j)); 20 | if (j % 2 == 0) { 21 | nb = nb * 2; 22 | } 23 | sum += nb > 9 ? nb - 9 : nb; 24 | } 25 | if (sum % 10 == 0) { 26 | System.out.println("YES"); 27 | } else { 28 | System.out.println("NO"); 29 | } 30 | }); 31 | } 32 | } -------------------------------------------------------------------------------- /Easy/Darts.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int SIZE = in.nextInt(); 12 | double half = SIZE / 2d; 13 | 14 | int N = in.nextInt(); 15 | if (in.hasNextLine()) { 16 | in.nextLine(); 17 | } 18 | 19 | Map scoreBoard = new LinkedHashMap<>(); 20 | for (int i = 0; i < N; i++) { 21 | String name = in.nextLine(); 22 | scoreBoard.put(name, 0); 23 | } 24 | 25 | int T = in.nextInt(); 26 | for (int i = 0; i < T; i++) { 27 | String throwName = in.next(); 28 | int x = in.nextInt(); 29 | int y = in.nextInt(); 30 | 31 | scoreBoard.put(throwName, scoreBoard.get(throwName) + calcScore(x, y, half)); 32 | } 33 | 34 | scoreBoard 35 | .entrySet() 36 | .stream() 37 | .sorted((e1, e2) -> e2.getValue() - e1.getValue()) 38 | .forEach(e -> System.out.println(e.getKey() + " " + e.getValue())); 39 | } 40 | 41 | private static int calcScore(int x, int y, double radius) { 42 | // In diamond shape 43 | if (Math.abs(x) + Math.abs(y) <= radius) { 44 | return 15; 45 | } 46 | 47 | // In circle 48 | if (Math.hypot(x, y) <= radius) { 49 | return 10; 50 | } 51 | 52 | // In square 53 | if (Math.abs(x) <= radius && Math.abs(y) <= radius) { 54 | return 5; 55 | } 56 | 57 | return 0; 58 | } 59 | } -------------------------------------------------------------------------------- /Easy/DeadMensShot.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | import java.awt.Polygon; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int N = in.nextInt(); 14 | final Polygon polygon = new Polygon(); 15 | for (int i = 0; i < N; i++) { 16 | int x = in.nextInt(); 17 | int y = in.nextInt(); 18 | polygon.addPoint(x, y); 19 | } 20 | int M = in.nextInt(); 21 | for (int i = 0; i < M; i++) { 22 | int x = in.nextInt(); 23 | int y = in.nextInt(); 24 | System.out.println(polygon.contains(x, y) ? "hit" : "miss"); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /Easy/Defibrillators.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | 12 | Double longitude = Double.parseDouble(in.next().replaceAll(",", ".")); 13 | Double latitude = Double.parseDouble(in.next().replaceAll(",", ".")); 14 | 15 | int N = in.nextInt(); 16 | if (in.hasNextLine()) { 17 | in.nextLine(); 18 | } 19 | 20 | Double min = Double.MAX_VALUE; 21 | String res = ""; 22 | 23 | for (int i = 0; i < N; i++) { 24 | String DEFIB = in.nextLine(); 25 | String[] str = DEFIB.split(";"); 26 | Double defibLon = Double.parseDouble(str[4].replaceAll(",", ".")); 27 | Double defibLat = Double.parseDouble(str[5].replaceAll(",", ".")); 28 | 29 | Double x = (defibLon - longitude) * Math.cos((latitude + defibLat) / 2); 30 | Double y = defibLat - latitude; 31 | Double d = Math.sqrt(x * x + y * y) * 6371; 32 | 33 | if (d <= min) { 34 | res = str[1]; 35 | min = d; 36 | } 37 | } 38 | 39 | System.out.println(res); 40 | } 41 | } -------------------------------------------------------------------------------- /Easy/DisorderedFirstContact.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int N = in.nextInt(); 12 | 13 | int absN = Math.abs(N); 14 | 15 | if (in.hasNextLine()) { 16 | in.nextLine(); 17 | } 18 | String MESSAGE = in.nextLine(); 19 | 20 | while(absN > 0) { 21 | if (N < 0) { 22 | MESSAGE = encode(MESSAGE).message; 23 | } else { 24 | MESSAGE = decode(MESSAGE); 25 | } 26 | absN--; 27 | } 28 | 29 | System.out.println(MESSAGE); 30 | } 31 | 32 | private static Result encode(String message) { 33 | Result result = new Result(); 34 | int length = 1; 35 | StringBuilder builder = new StringBuilder(); 36 | for (int i = 0; i < message.length(); i += length++) { 37 | String sub = message.substring(i, Math.min(message.length(), i+length)); 38 | result.lastLength = length; 39 | result.lastSubLength = sub.length(); 40 | if (length % 2 == 0) { 41 | builder.insert(0, sub); 42 | } else { 43 | builder.append(sub); 44 | } 45 | } 46 | result.message = builder.toString(); 47 | return result; 48 | } 49 | 50 | private static String decode(String message) { 51 | Result r = encode(message); 52 | 53 | StringBuilder result; 54 | boolean fromLeft = r.lastLength % 2 == 0; 55 | 56 | int leftIndex = 0; 57 | int rightIndex = message.length(); 58 | 59 | if (fromLeft) { 60 | result = new StringBuilder(message.substring(leftIndex, r.lastSubLength)); 61 | leftIndex += r.lastSubLength; 62 | } else { 63 | result = new StringBuilder(message.substring(rightIndex - r.lastSubLength)); 64 | rightIndex -= r.lastSubLength; 65 | } 66 | 67 | int times = r.lastLength - 1; 68 | 69 | while (times > 0) { 70 | if (times % 2 == 0) { 71 | result.insert(0, message, leftIndex, leftIndex + times); 72 | leftIndex += times--; 73 | } else { 74 | result.insert(0, message, rightIndex - times, rightIndex); 75 | rightIndex -= times--; 76 | } 77 | } 78 | 79 | return result.toString(); 80 | } 81 | } 82 | 83 | class Result { 84 | int lastLength; 85 | int lastSubLength; 86 | String message; 87 | } -------------------------------------------------------------------------------- /Easy/DisorderedFirstContactV2.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | import java.util.function.Function; 5 | import java.util.stream.IntStream; 6 | 7 | /** 8 | * Auto-generated code below aims at helping you parse 9 | * the standard input according to the problem statement. 10 | **/ 11 | class Solution { 12 | 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | int N = in.nextInt(); 16 | 17 | int absN = Math.abs(N); 18 | 19 | if (in.hasNextLine()) { 20 | in.nextLine(); 21 | } 22 | String message = in.nextLine(); 23 | char[] MESSAGE = message.toCharArray(); 24 | 25 | List mappingList = createMappingList(message); 26 | 27 | while(absN > 0) { 28 | MESSAGE = N < 0 ? convert(MESSAGE, mappingList::get) : convert(MESSAGE, mappingList::indexOf); 29 | absN--; 30 | } 31 | 32 | System.out.println(MESSAGE); 33 | } 34 | 35 | private static List createMappingList(String message) { 36 | List res = new ArrayList<>(); 37 | 38 | MappingCheck mpCheck = new MappingCheck(); 39 | 40 | IntStream.range(0, message.length()).forEach(i -> { 41 | if (mpCheck.add) { 42 | res.add(i); 43 | } else { 44 | res.add(mpCheck.index++, i); 45 | } 46 | 47 | mpCheck.switchSide(i); 48 | }); 49 | 50 | return res; 51 | } 52 | 53 | private static char[] convert(char[] message, Function mappingFunc) { 54 | char[] res = new char[message.length]; 55 | IntStream.range(0, message.length).forEach(i -> res[i] = message[mappingFunc.apply(i)]); 56 | return res; 57 | } 58 | } 59 | 60 | class MappingCheck { 61 | boolean add = true; 62 | int nbCharToAdd = 1; 63 | int index = 0; 64 | int nbSwitch = 0; 65 | 66 | // welcome to the other side 67 | void switchSide(int i) { 68 | if (i == nbSwitch) { 69 | add = !add; 70 | nbSwitch += ++nbCharToAdd; 71 | index = 0; 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /Easy/EncryptionDecryptionOfEnigmaMachine.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | private static Map rotor1 = new HashMap<>(); 12 | private static Map rotor2 = new HashMap<>(); 13 | private static Map rotor3 = new HashMap<>(); 14 | private static Map decodeRotor1 = new HashMap<>(); 15 | private static Map decodeRotor2 = new HashMap<>(); 16 | private static Map decodeRotor3 = new HashMap<>(); 17 | private static String[] keys; 18 | 19 | public static void main(String[] args) { 20 | Scanner in = new Scanner(System.in); 21 | String operation = in.nextLine(); 22 | int N = in.nextInt(); 23 | if (in.hasNextLine()) { 24 | in.nextLine(); 25 | } 26 | 27 | keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""); 28 | parseRotor(in.nextLine(), 1); 29 | parseRotor(in.nextLine(), 2); 30 | parseRotor(in.nextLine(), 3); 31 | 32 | String message = in.nextLine(); 33 | 34 | String str; 35 | if (operation.equals("ENCODE")) { 36 | str = encode(message, N); 37 | } else { 38 | str = decode(message, N); 39 | } 40 | 41 | System.out.println(str); 42 | } 43 | 44 | private static void parseRotor(String rotor, int index) { 45 | String[] splitted = rotor.split(""); 46 | for (int i = 0; i < splitted.length; i++) { 47 | if (index == 1) { 48 | rotor1.put(keys[i], splitted[i]); 49 | decodeRotor1.put(splitted[i], keys[i]); 50 | } else if (index == 2) { 51 | rotor2.put(keys[i], splitted[i]); 52 | decodeRotor2.put(splitted[i], keys[i]); 53 | } else if (index == 3) { 54 | rotor3.put(keys[i], splitted[i]); 55 | decodeRotor3.put(splitted[i], keys[i]); 56 | } 57 | } 58 | } 59 | 60 | private static String encode(String word, int N) { 61 | String[] str = word.split(""); 62 | StringBuilder res = new StringBuilder(); 63 | int i = 0; 64 | for (String s : str) { 65 | String tmp = getLetter(s, N + i++, true); 66 | tmp = rotor1.get(tmp); 67 | tmp = rotor2.get(tmp); 68 | tmp = rotor3.get(tmp); 69 | res.append(tmp); 70 | } 71 | return res.toString(); 72 | } 73 | 74 | private static String decode(String word, int N) { 75 | String[] str = word.split(""); 76 | StringBuilder res = new StringBuilder(); 77 | int i = 0; 78 | for (String s : str) { 79 | String tmp = decodeRotor3.get(s); 80 | tmp = decodeRotor2.get(tmp); 81 | tmp = decodeRotor1.get(tmp); 82 | tmp = getLetter(tmp, N + i++, false); 83 | res.append(tmp); 84 | } 85 | return res.toString(); 86 | } 87 | 88 | private static String getLetter(String letter, int N, boolean encode) { 89 | int tmp = 0; 90 | 91 | for (int i = 0; i < keys.length; i++) { 92 | if (keys[i].equals(letter)) { 93 | tmp = i; 94 | break; 95 | } 96 | } 97 | 98 | if (encode) { 99 | tmp = tmp + N; 100 | } else { 101 | tmp = tmp - N; 102 | } 103 | 104 | tmp = tmp % 26; 105 | if (tmp < 0) { 106 | tmp = 26 + tmp; 107 | } 108 | 109 | return keys[tmp]; 110 | } 111 | 112 | 113 | } -------------------------------------------------------------------------------- /Easy/GhostLegs.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.stream.IntStream; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int W = in.nextInt(); 12 | int H = in.nextInt(); 13 | if (in.hasNextLine()) { 14 | in.nextLine(); 15 | } 16 | 17 | List ROWS = new ArrayList<>(); 18 | 19 | for (int i = 0; i < H; i++) { 20 | ROWS.add(in.nextLine()); 21 | } 22 | 23 | IntStream.range(0, W).filter(j -> j % 3 == 0).forEach(j -> { 24 | 25 | int position = j; 26 | char character = 'A'; 27 | 28 | for (int i = 0; i < ROWS.size(); i++) { 29 | if (i == 0) { 30 | character = ROWS.get(i).charAt(position); 31 | } 32 | 33 | if (position < W - 1 && ROWS.get(i).charAt(position + 1) == '-') { 34 | position += 3; 35 | } else if (position >= 1 && ROWS.get(i).charAt(position - 1) == '-') { 36 | position -= 3; 37 | } 38 | } 39 | 40 | System.out.println(character + "" + ROWS.get(H - 1).charAt(position)); 41 | }); 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /Easy/GuessingNCheating.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int R = in.nextInt(); 12 | in.nextLine(); 13 | 14 | boolean cheating = false; 15 | int i = 0; 16 | int min = 0; 17 | int max = Integer.MAX_VALUE; 18 | while (i < R && !cheating) { 19 | String[] line = in.nextLine().split(" "); 20 | int value = Integer.parseInt(line[0]); 21 | switch(line[2]) { 22 | case "high": 23 | if (value < min) { 24 | cheating = true; 25 | } else { 26 | max = Math.min(value, max); 27 | } 28 | break; 29 | case "low": 30 | if (value > max) { 31 | cheating = true; 32 | } else { 33 | min = Math.max(value, min); 34 | } 35 | break; 36 | case "on": 37 | if (value < min || value > max) { 38 | cheating = true; 39 | } 40 | break; 41 | } 42 | 43 | if (max == 1 || min == 100 || max - min < 2) { 44 | cheating = true; 45 | } 46 | 47 | i++; 48 | } 49 | 50 | if (cheating) { 51 | System.out.println("Alice cheated in round " + i); 52 | } else { 53 | System.out.println("No evidence of cheating"); 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /Easy/HoochClash.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int A = in.nextInt(); 12 | int B = in.nextInt(); 13 | int C = in.nextInt(); 14 | int D = in.nextInt(); 15 | 16 | double toFind = Math.pow(C * 0.5d, 3) + Math.pow(D * 0.5d, 3); 17 | 18 | int low = A; 19 | int high = B; 20 | 21 | int i = D; 22 | int j = C; 23 | 24 | boolean found = false; 25 | 26 | while (high >= low) { 27 | double cal = Math.pow(high * 0.5d, 3) + Math.pow(low * 0.5d, 3); 28 | 29 | if (cal == toFind) { 30 | i = high; 31 | j = low; 32 | if (i != D || j != C) { 33 | found = true; 34 | break; 35 | } 36 | high--; 37 | } else if (cal > toFind) { 38 | high--; 39 | } else { 40 | low++; 41 | } 42 | } 43 | 44 | if (found) { 45 | System.out.println(j + " " + i); 46 | } else { 47 | System.out.println("VALID"); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /Easy/HorseRacingDuals.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.List; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Auto-generated code below aims at helping you parse 8 | * the standard input according to the problem statement. 9 | **/ 10 | class Solution { 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int N = in.nextInt(); 15 | 16 | List horses = new ArrayList<>(); 17 | for (int i = 0; i < N; i++) { 18 | int pi = in.nextInt(); 19 | horses.add(pi); 20 | } 21 | 22 | Collections.sort(horses); 23 | int delta = 10000000; 24 | for (int i = 0; i < N-1; i++) { 25 | int tmp = horses.get(i+1) - horses.get(i); 26 | if (tmp < delta) { 27 | delta = tmp; 28 | } 29 | } 30 | 31 | System.out.println(delta); 32 | } 33 | } -------------------------------------------------------------------------------- /Easy/HorseRacingHyperDuals.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int N = in.nextInt(); 14 | List horses = new ArrayList<>(); 15 | for (int i = 0; i < N; i++) { 16 | horses.add(new Horse(in.nextInt(), in.nextInt())); 17 | } 18 | 19 | int delta = Integer.MAX_VALUE; 20 | for (int i = 0; i < N - 1; i++) { 21 | for (int j = i + 1; j < N; j++) { 22 | delta = Math.min(delta, horses.get(i).strengthDiff(horses.get(j))); 23 | } 24 | } 25 | 26 | System.out.println(delta); 27 | } 28 | } 29 | 30 | class Horse { 31 | int v; 32 | int e; 33 | 34 | public Horse(int v, int e) { 35 | this.v = v; 36 | this.e = e; 37 | } 38 | 39 | int strengthDiff(Horse h) { 40 | return Math.abs(h.v - this.v) + Math.abs(h.e - this.e); 41 | } 42 | } -------------------------------------------------------------------------------- /Easy/HowTimeFlies.java: -------------------------------------------------------------------------------- 1 | import java.text.ParseException; 2 | import java.text.SimpleDateFormat; 3 | import java.time.LocalDate; 4 | import java.time.Period; 5 | import java.time.ZoneId; 6 | import java.util.Scanner; 7 | import java.time.temporal.ChronoUnit; 8 | 9 | /** 10 | * Auto-generated code below aims at helping you parse 11 | * the standard input according to the problem statement. 12 | **/ 13 | class Solution { 14 | 15 | static SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); 16 | 17 | public static void main(String[] args) { 18 | try { 19 | Scanner in = new Scanner(System.in); 20 | LocalDate d1 = sdf.parse(in.next()).toInstant() 21 | .atZone(ZoneId.systemDefault()) 22 | .toLocalDate(); 23 | LocalDate d2 = sdf.parse(in.next()).toInstant() 24 | .atZone(ZoneId.systemDefault()) 25 | .toLocalDate(); 26 | 27 | Period time = Period.between(d1, d2); 28 | long days = ChronoUnit.DAYS.between(d1, d2); 29 | 30 | StringBuilder build = new StringBuilder(); 31 | if (time.getYears() > 0) { 32 | build.append(time.getYears()).append(" year").append(time.getYears() > 1 ? "s" : "").append(", "); 33 | } 34 | if (time.getMonths() > 0) { 35 | build.append(time.getMonths()).append(" month").append(time.getMonths() > 1 ? "s" : "").append(", "); 36 | } 37 | build.append("total ").append(days).append(" days"); 38 | 39 | System.out.println(build.toString()); 40 | } catch (ParseException ignored) { 41 | 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /Easy/HungerGames.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.concurrent.atomic.AtomicInteger; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int tributes = in.nextInt(); 13 | in.nextLine(); 14 | 15 | Map map = new LinkedHashMap<>(); 16 | for (int i = 0; i < tributes; i++) { 17 | String name = in.nextLine(); 18 | map.put(name, new Tribute(name)); 19 | } 20 | int turns = in.nextInt(); 21 | in.nextLine(); 22 | 23 | for (int i = 0; i < turns; i++) { 24 | String line = in.nextLine(); 25 | String[] info = line.split(",?\\s"); 26 | 27 | String killerName = info[0]; 28 | 29 | for (int j = 2; j < info.length; j++) { 30 | String victimName = info[j]; 31 | Tribute t = map.get(killerName); 32 | t.killed.add(victimName); 33 | map.put(killerName, t); 34 | 35 | Tribute victim = map.get(victimName); 36 | victim.killer = t.name; 37 | map.put(victimName, victim); 38 | } 39 | 40 | } 41 | 42 | AtomicInteger i = new AtomicInteger(); 43 | map.entrySet() 44 | .stream() 45 | .sorted(Comparator.comparing(e -> e.getValue().name)) 46 | .forEach(e -> { 47 | Tribute t = e.getValue(); 48 | if (i.get() != 0) { 49 | System.out.println(); 50 | } 51 | System.out.println("Name: " + t.name); 52 | 53 | t.killed.sort(String::compareTo); 54 | System.out.print("Killed: " + (t.killed.size() == 0 ? "None" : String.join(", ", t.killed))); 55 | System.out.println("Killer: " + (t.killer.equals("") ? "Winner" : t.killer)); 56 | 57 | i.addAndGet(1); 58 | }); 59 | } 60 | } 61 | 62 | class Tribute { 63 | String name; 64 | String killer = ""; 65 | List killed = new ArrayList<>(); 66 | 67 | 68 | public Tribute(String name) { 69 | this.name = name; 70 | } 71 | } -------------------------------------------------------------------------------- /Easy/IsbnCheckDigit.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int N = in.nextInt(); 14 | in.nextLine(); 15 | 16 | List invalid = new ArrayList<>(); 17 | for (int i = 0; i < N; i++) { 18 | String ISBN = in.nextLine(); 19 | if (ISBN.length() == 10) { 20 | if (!check10Digits(ISBN)) { 21 | invalid.add(ISBN); 22 | } 23 | } else if (ISBN.length() == 13) { 24 | if (!check13Digits(ISBN)) { 25 | invalid.add(ISBN); 26 | } 27 | } else { 28 | invalid.add(ISBN); 29 | } 30 | } 31 | System.out.println(invalid.size() + " invalid:"); 32 | for (String s : invalid) { 33 | System.out.println(s); 34 | } 35 | } 36 | 37 | private static boolean check13Digits(String ISBN) { 38 | if (ISBN.contains("X")) { 39 | return false; 40 | } 41 | 42 | char[] c = ISBN.toCharArray(); 43 | int sum = 0; 44 | for (int j = 0; j < c.length; j++) { 45 | sum += (c[j] - '0') * (j % 2 == 1 ? 3 : 1); 46 | } 47 | return sum % 10 == 0; 48 | } 49 | 50 | private static boolean check10Digits(String ISBN) { 51 | if (ISBN.substring(0, ISBN.length() - 1).contains("X")) { 52 | return false; 53 | } 54 | 55 | char[] c = ISBN.toCharArray(); 56 | int sum = 0; 57 | for (int j = 0; j < c.length - 1; j++) { 58 | sum += (c[j] - '0') * (c.length - j); 59 | } 60 | 61 | int lastDigit = c[c.length - 1] - '0'; 62 | lastDigit = lastDigit > 9 ? 10 : lastDigit; 63 | return (sum + lastDigit) % 11 == 0; 64 | } 65 | } -------------------------------------------------------------------------------- /Easy/JackSilverTheCasino.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int ROUNDS = in.nextInt(); 12 | int CASH = in.nextInt(); 13 | in.nextLine(); 14 | for (int i = 0; i < ROUNDS; i++) { 15 | String[] PLAY = in.nextLine().split(" "); 16 | int casino = Integer.parseInt(PLAY[0]); 17 | int player = Integer.parseInt(PLAY.length == 3 ? PLAY[2] : "-1"); 18 | 19 | int bet = (int) Math.ceil(CASH / 4d); 20 | CASH -= bet; 21 | 22 | int multiply = -1; 23 | 24 | if (PLAY[1].equals("PLAIN") && casino == player) { 25 | multiply = 35; 26 | } else if ((PLAY[1].equals("EVEN") && casino % 2 == 0 && casino != 0) 27 | || (PLAY[1].equals("ODD") && casino % 2 == 1)) { 28 | multiply = 1; 29 | } 30 | 31 | CASH += bet + bet * multiply; 32 | } 33 | 34 | System.out.println(CASH); 35 | } 36 | } -------------------------------------------------------------------------------- /Easy/Lumen.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int N = in.nextInt(); 12 | int L = in.nextInt(); 13 | if (in.hasNextLine()) { 14 | in.nextLine(); 15 | } 16 | 17 | boolean[][] lighted = new boolean[N][N]; 18 | 19 | int nbDarkSpot = N * N; 20 | 21 | // lines 22 | for (int i = 0; i < N; i++) { 23 | String[] line = in.nextLine().split(" "); 24 | 25 | int nbLights = 0; 26 | // rows 27 | for (int j = 0; j < N; j++) { 28 | if (line[j].equals("C")) { 29 | for (int k = Math.max(0, i - L + 1); k < Math.min(N, i + L); k++) { 30 | for (int l = Math.max(0, j - L + 1); l < Math.min(N, j + L); l++) { 31 | if (!lighted[k][l]) { 32 | lighted[k][l] = true; 33 | nbLights++; 34 | } 35 | } 36 | } 37 | } 38 | } 39 | 40 | nbDarkSpot -= nbLights; 41 | } 42 | 43 | System.out.println(nbDarkSpot); 44 | } 45 | } -------------------------------------------------------------------------------- /Easy/MarsLanderEpisode1.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Player { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int surfaceN = in.nextInt(); // the number of points used to draw the surface of Mars. 12 | for (int i = 0; i < surfaceN; i++) { 13 | int landX = in.nextInt(); // X coordinate of a surface point. (0 to 6999) 14 | int landY = in.nextInt(); // Y coordinate of a surface point. By linking all the points together in a sequential fashion, you form the surface of Mars. 15 | } 16 | 17 | double marsGravity = 3.711; 18 | 19 | // game loop 20 | while (true) { 21 | int X = in.nextInt(); 22 | int Y = in.nextInt(); 23 | int hSpeed = in.nextInt(); // the horizontal speed (in m/s), can be negative. 24 | int vSpeed = in.nextInt(); // the vertical speed (in m/s), can be negative. 25 | int fuel = in.nextInt(); // the quantity of remaining fuel in liters. 26 | int rotate = in.nextInt(); // the rotation angle in degrees (-90 to 90). 27 | int power = in.nextInt(); // the thrust power (0 to 4). 28 | 29 | if (vSpeed <= -40) { 30 | System.out.println("0 4"); 31 | } else if (vSpeed <= -30) { 32 | System.out.println("0 3"); 33 | } else { 34 | System.out.println("0 0"); 35 | } 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /Easy/MayTheTriforceBeWithYou.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.stream.IntStream; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int N = in.nextInt(); 13 | 14 | int width = 1 + 2 * (N - 1); 15 | int maxWidth = 1 + 2 * width; 16 | 17 | String space = " "; 18 | String star = "*"; 19 | 20 | System.out.println("." + space.repeat(width - 1) + "*"); 21 | 22 | IntStream.range(1, N).forEach(i -> { 23 | int nbStars = 1 + 2 * i; 24 | int nbSpace = (maxWidth - nbStars) / 2; 25 | System.out.println(space.repeat(nbSpace) + star.repeat(nbStars)); 26 | }); 27 | 28 | IntStream.range(0, N).forEach(i -> { 29 | int nbStars = (1 + 2 * i); 30 | int nbSpace1 = (width - nbStars) / 2; 31 | int nbSpace2 = 2 * nbSpace1 + 1; 32 | System.out.println(space.repeat(nbSpace1) + star.repeat(nbStars) + space.repeat(nbSpace2) + star.repeat(nbStars)); 33 | }); 34 | } 35 | } -------------------------------------------------------------------------------- /Easy/MimeType.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int N = in.nextInt(); // Number of elements which make up the association table. 14 | int Q = in.nextInt(); // Number Q of file names to be analyzed. 15 | 16 | Map mimeMap = new HashMap<>(); 17 | for (int i = 0; i < N; i++) { 18 | mimeMap.put(in.next().toUpperCase(), in.next()); 19 | in.nextLine(); 20 | } 21 | 22 | for (int i = 0; i < Q; i++) { 23 | String FNAME = in.nextLine().toUpperCase(); // One file name per line. 24 | 25 | String extension = ""; 26 | int index = FNAME.lastIndexOf('.'); 27 | if (index >= 0) { 28 | extension = FNAME.substring(index+1); 29 | } 30 | 31 | System.out.println(mimeMap.getOrDefault(extension, "UNKNOWN")); 32 | 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Easy/MorelletsRandomLines.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int xA = in.nextInt(); 12 | int yA = in.nextInt(); 13 | int xB = in.nextInt(); 14 | int yB = in.nextInt(); 15 | int n = in.nextInt(); 16 | 17 | Set coefs = new HashSet<>(); 18 | 19 | for (int i = 0; i < n; i++) { 20 | int a = in.nextInt(); 21 | int b = in.nextInt(); 22 | int c = in.nextInt(); 23 | 24 | if (a < 0) { 25 | a = -1 * a; 26 | b = -1 * b; 27 | c = -1 * c; 28 | } 29 | 30 | addCoefficients(coefs, a, b, c); 31 | } 32 | 33 | int countA = 0; 34 | int countB = 0; 35 | 36 | for(Coefficient coef : coefs) { 37 | int valA = (coef.a * xA) + (coef.b * yA) + coef.c; 38 | int valB = (coef.a * xB) + (coef.b * yB) + coef.c; 39 | 40 | if (valA == 0 || valB == 0) { 41 | System.out.println("ON A LINE"); 42 | return; 43 | } 44 | 45 | if (valA < 0) { 46 | countA++; 47 | } 48 | if (valB < 0) { 49 | countB++; 50 | } 51 | } 52 | 53 | if (countA % 2 == countB % 2) { 54 | System.out.println("YES"); 55 | } else { 56 | System.out.println("NO"); 57 | } 58 | } 59 | 60 | private static void addCoefficients(Set coefficients, int a, int b, int c) { 61 | List list = new ArrayList<>(); 62 | if (a != 0) { 63 | list.add(Math.abs(a)); 64 | } 65 | if (b != 0) { 66 | list.add(Math.abs(b)); 67 | } 68 | if (c != 0) { 69 | list.add(Math.abs(c)); 70 | } 71 | 72 | int val = Collections.min(list); 73 | 74 | Coefficient coef; 75 | if (a % val == 0 && b % val == 0 && c % val == 0) { 76 | coef = new Coefficient(a / val, b / val, c / val); 77 | } else { 78 | coef = new Coefficient(a, b, c); 79 | } 80 | 81 | coefficients.add(coef); 82 | } 83 | } 84 | 85 | class Coefficient{ 86 | int a; 87 | int b; 88 | int c; 89 | 90 | public Coefficient(int a, int b, int c) { 91 | this.a = a; 92 | this.b = b; 93 | this.c = c; 94 | } 95 | 96 | @Override 97 | public boolean equals(Object o) { 98 | if (this == o) return true; 99 | if (o == null || getClass() != o.getClass()) return false; 100 | Coefficient coef = (Coefficient) o; 101 | return a == coef.a && 102 | b == coef.b && 103 | c == coef.c; 104 | } 105 | 106 | @Override 107 | public int hashCode() { 108 | return Objects.hash(a, b, c); 109 | } 110 | } -------------------------------------------------------------------------------- /Easy/NatureOfQuadrilterals.java: -------------------------------------------------------------------------------- 1 | import java.util.EnumSet; 2 | import java.util.Scanner; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int n = in.nextInt(); 13 | for (int i = 0; i < n; i++) { 14 | String A = in.next(); 15 | int xA = in.nextInt(); 16 | int yA = in.nextInt(); 17 | String B = in.next(); 18 | int xB = in.nextInt(); 19 | int yB = in.nextInt(); 20 | String C = in.next(); 21 | int xC = in.nextInt(); 22 | int yC = in.nextInt(); 23 | String D = in.next(); 24 | int xD = in.nextInt(); 25 | int yD = in.nextInt(); 26 | 27 | double abY = Math.abs(yB - yA); 28 | double abX = Math.abs(xB - xA); 29 | double bcY = Math.abs(yC - yB); 30 | double bcX = Math.abs(xC - xB); 31 | double cdY = Math.abs(yD - yC); 32 | double cdX = Math.abs(xD - xC); 33 | double daY = Math.abs(yA - yD); 34 | double daX = Math.abs(xA - xD); 35 | 36 | EnumSet flags = EnumSet.noneOf(Flag.class); 37 | 38 | if (abY / abX == cdY / cdX && bcY / bcX == daY / daX) { 39 | flags.add(Flag.PARALLELOGRAM); 40 | } 41 | if (Math.hypot(abY, abX) == Math.hypot(cdY, cdX) 42 | && Math.hypot(abY, abX) == Math.hypot(bcY, bcX)) { 43 | flags.add(Flag.RHOMBUS); 44 | } 45 | if (Math.toDegrees(Math.atan2(yD - yA, xD - xA) - Math.atan2(yB - yA, xB - xA)) % 90 == 0 46 | && Math.toDegrees(Math.atan2(yB - yC, xB - xC) - Math.atan2(yD - yC, xD - xC)) % 90 == 0) { 47 | flags.add(Flag.RECTANGLE); 48 | } 49 | 50 | displayFlag(A+B+C+D, flags); 51 | } 52 | } 53 | 54 | private static void displayFlag(String value, EnumSet enums) { 55 | String res; 56 | if (enums.contains(Flag.RECTANGLE) && enums.contains(Flag.RHOMBUS)) { 57 | res = "square"; 58 | } else if (enums.contains(Flag.RECTANGLE)) { 59 | res = "rectangle"; 60 | } else if (enums.contains(Flag.RHOMBUS)) { 61 | res = "rhombus"; 62 | } else if (enums.contains(Flag.PARALLELOGRAM)) { 63 | res = "parallelogram"; 64 | } else { 65 | res = "quadrilateral"; 66 | 67 | } 68 | System.out.println(value + " is a " + res + "."); 69 | } 70 | 71 | public enum Flag { 72 | PARALLELOGRAM, RHOMBUS, RECTANGLE 73 | } 74 | } 75 | 76 | -------------------------------------------------------------------------------- /Easy/OneDSpreadsheet.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | static Integer[] res; 10 | static String[][] sheets; 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int N = in.nextInt(); 15 | sheets = new String[N][3]; 16 | res = new Integer[N]; 17 | for (int i = 0; i < N; i++) { 18 | sheets[i] = new String[]{in.next(), in.next(), in.next()}; 19 | } 20 | 21 | for (int i = 0; i < N; i++) { 22 | System.out.println(getRes(i)); 23 | } 24 | } 25 | 26 | private static int getRes(int index) { 27 | if (res[index] != null) { 28 | return res[index]; 29 | } 30 | 31 | String val1 = sheets[index][1]; 32 | String val2 = sheets[index][2]; 33 | 34 | int i1 = val1.charAt(0) == '$' ? getRes(Integer.parseInt(val1.substring(1))) : Integer.parseInt(val1); 35 | int i2 = val2.equals("_") ? 0 : val2.charAt(0) == '$' ? getRes(Integer.parseInt(val2.substring(1))) : Integer.parseInt(val2); 36 | 37 | switch (sheets[index][0]) { 38 | case "VALUE": 39 | res[index] = i1; 40 | break; 41 | case "ADD": 42 | res[index] = i1 + i2; 43 | break; 44 | case "SUB": 45 | res[index] = i1 - i2; 46 | break; 47 | case "MULT": 48 | res[index] = i1 * i2; 49 | break; 50 | } 51 | 52 | return res[index]; 53 | } 54 | } -------------------------------------------------------------------------------- /Easy/OrderOfSuccession.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Comparator; 3 | import java.util.List; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Auto-generated code below aims at helping you parse 8 | * the standard input according to the problem statement. 9 | **/ 10 | class Solution { 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int n = in.nextInt(); 15 | 16 | Node root = null; 17 | for (int i = 0; i < n; i++) { 18 | Node node = new Node(in); 19 | if (root == null) { 20 | root = node; 21 | } else { 22 | root.addNode(node); 23 | } 24 | } 25 | 26 | downFirst(root); 27 | } 28 | 29 | private static void downFirst(Node node) { 30 | if (node.isVisible()) { 31 | System.out.println(node.name); 32 | } 33 | 34 | if (node.hasChildren()) { 35 | for (int i = 0; i < node.children.size(); i++) { 36 | downFirst(node.children.get(i)); 37 | } 38 | } 39 | } 40 | } 41 | 42 | class Node { 43 | String name; 44 | String parent; 45 | Integer birth; 46 | boolean alive; 47 | String religion; 48 | String gender; 49 | 50 | List children; 51 | 52 | Node(Scanner in) { 53 | this.name = in.next(); 54 | this.parent = in.next(); 55 | this.birth = in.nextInt(); 56 | this.alive = in.next().equals("-"); 57 | this.religion = in.next(); 58 | this.gender = in.next(); 59 | children = new ArrayList<>(); 60 | } 61 | 62 | boolean addNode(Node node) { 63 | if (node.parent.equals("-")) { 64 | return false; 65 | } else if (node.parent.equals(this.name)) { 66 | this.children.add(node); 67 | this.children.sort(Comparator.comparing(Node::getGender).reversed().thenComparing(Node::getBirth)); 68 | return true; 69 | } else { 70 | for (Node child : children) { 71 | boolean b = child.addNode(node); 72 | if (b) { 73 | return true; 74 | } 75 | } 76 | } 77 | 78 | return false; 79 | } 80 | 81 | boolean hasChildren() { 82 | return !children.isEmpty(); 83 | } 84 | 85 | private String getGender() { 86 | return gender; 87 | } 88 | 89 | private Integer getBirth() { 90 | return birth; 91 | } 92 | 93 | private boolean isAlive() { 94 | return this.alive; 95 | } 96 | 97 | private boolean isAnglican() { 98 | return religion.equals("Anglican"); 99 | } 100 | 101 | boolean isVisible() { 102 | return isAlive() && isAnglican(); 103 | } 104 | } -------------------------------------------------------------------------------- /Easy/OrganicCompounds.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int N = in.nextInt(); 12 | in.nextLine(); 13 | 14 | String[] compounds = new String[N]; 15 | for (int i = 0; i < N; i++) { 16 | compounds[i] = in.nextLine(); 17 | } 18 | 19 | boolean found = true; 20 | for (int i = 0; i < N; i++) { 21 | for (int j = 0; j < compounds[i].length() - 2; j++) { 22 | if (compounds[i].substring(j, j + 2).equals("CH")) { 23 | int bonds = Integer.parseInt("" + compounds[i].charAt(j + 2)); 24 | try { 25 | bonds += Integer.parseInt("" + compounds[i - 1].charAt(j + 1)); 26 | } catch (Exception ignored) { 27 | }//Don't like it but it's easier 28 | try { 29 | bonds += Integer.parseInt("" + compounds[i + 1].charAt(j + 1)); 30 | } catch (Exception ignored) { 31 | } 32 | try { 33 | bonds += Integer.parseInt("" + compounds[i].charAt(j - 2)); 34 | } catch (Exception ignored) { 35 | } 36 | try { 37 | bonds += Integer.parseInt("" + compounds[i].charAt(j + 4)); 38 | } catch (Exception ignored) { 39 | } 40 | if (bonds != 4) { 41 | found = false; 42 | } 43 | } 44 | j += 5; 45 | } 46 | } 47 | 48 | System.out.println(found ? "VALID" : "INVALID"); 49 | } 50 | } -------------------------------------------------------------------------------- /Easy/PiratesTreasure.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int W = in.nextInt(); 12 | int H = in.nextInt(); 13 | int[][] map = new int[H][W]; 14 | for (int i = 0; i < H; i++) { 15 | for (int j = 0; j < W; j++) { 16 | map[i][j] = in.nextInt(); 17 | } 18 | } 19 | 20 | for (int i = 0; i < H; i++) { 21 | for (int j = 0; j < W; j++) { 22 | if ((map[i][j] == 1) 23 | || (i > 0 && j > 0 && map[i-1][j-1] == 0) 24 | || (i > 0 && map[i-1][j] == 0) 25 | || (i > 0 && j < W - 1 && map[i-1][j+1] == 0) 26 | || (i < H - 1 && j < W - 1 && map[i+1][j+1] == 0) 27 | || (i < H - 1 && map[i+1][j] == 0) 28 | || (i < H - 1 && j > 0 && map[i+1][j-1] == 0) 29 | || (j > 0 && map[i][j-1] == 0) 30 | || (j < W - 1 && map[i][j+1] == 0)) { 31 | continue; 32 | } 33 | 34 | System.out.println(j + " " + i); 35 | } 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /Easy/PlagueJR.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Solution { 4 | 5 | static Map> links = new HashMap<>(); 6 | static boolean[] visited; 7 | 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | int N = in.nextInt(); 11 | 12 | for (int i = 0; i < N; i++) { 13 | int A = in.nextInt(); 14 | int B = in.nextInt(); 15 | links.computeIfAbsent(A, k -> new ArrayList<>()).add(B); 16 | links.computeIfAbsent(B, k -> new ArrayList<>()).add(A); 17 | } 18 | 19 | int max = Integer.MAX_VALUE; 20 | for (Map.Entry> e : links.entrySet()) { 21 | 22 | visited = new boolean[N+1]; 23 | visited[e.getKey()] = true; 24 | 25 | int tmp = findMaxDepth(e.getKey()) - 1; 26 | 27 | max = Math.min(max, tmp); 28 | 29 | } 30 | 31 | System.out.println(max); 32 | } 33 | 34 | private static int findMaxDepth(Integer index) { 35 | List list = links.get(index); 36 | if (list != null && !list.isEmpty()) { 37 | int max = 0; 38 | for (Integer i : list) { 39 | if (!visited[i]) { 40 | visited[i] = true; 41 | max = Math.max(max, findMaxDepth(i)); 42 | } 43 | } 44 | return max + 1; 45 | } 46 | return 1; 47 | } 48 | } -------------------------------------------------------------------------------- /Easy/PowerOfThorEpisode1.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | * --- 7 | * Hint: You can use the debug stream to print initialTX and initialTY, if Thor seems not follow your orders. 8 | **/ 9 | class Player { 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int lightX = in.nextInt(); // the X position of the light of power 14 | int lightY = in.nextInt(); // the Y position of the light of power 15 | int initialTX = in.nextInt(); // Thor's starting X position 16 | int initialTY = in.nextInt(); // Thor's starting Y position 17 | 18 | // game loop 19 | while (true) { 20 | String direction = ""; 21 | 22 | if (lightY < initialTY) { 23 | direction += "N"; 24 | initialTY--; 25 | } else if (lightY > initialTY) { 26 | direction += "S"; 27 | initialTY++; 28 | } 29 | 30 | if (lightX < initialTX) { 31 | direction += "W"; 32 | initialTX--; 33 | } else if (lightX > initialTX) { 34 | direction += "E"; 35 | initialTX++; 36 | } 37 | 38 | System.out.println(direction); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Easy/RectangularBlockSpinner.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int size = in.nextInt(); 12 | int angle = in.nextInt() % 360; 13 | in.nextLine(); 14 | 15 | int newSize = 2 * size - 1; 16 | 17 | char[][] results = new char[newSize][newSize]; 18 | for (int i = 0; i < newSize; i++) { 19 | for (int j = 0; j < newSize; j++) { 20 | results[i][j] = ' '; 21 | } 22 | } 23 | 24 | for (int i = 0; i < size; i++) { 25 | String line = in.nextLine(); 26 | for (int j = 0; j < size; j++) { 27 | switch (angle) { 28 | case 45: 29 | results[size - 1 + i - j][i + j] = line.charAt(j * 2); 30 | break; 31 | case 135: 32 | results[2 * size - 2 - i - j][size - 1 + i - j] = line.charAt(j * 2); 33 | break; 34 | case 225: 35 | results[size - 1 - i + j][i + j] = line.charAt(j * 2); 36 | break; 37 | case 315: 38 | results[i + j][size - 1 - i + j] = line.charAt(j * 2); 39 | break; 40 | } 41 | } 42 | } 43 | 44 | for (int i = 0; i < newSize; i++) { 45 | for (int j = 0; j < newSize; j++) { 46 | System.out.print(results[i][j]); 47 | } 48 | System.out.println(); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /Easy/RooksMovements.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Comparator; 3 | import java.util.List; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Auto-generated code below aims at helping you parse 8 | * the standard input according to the problem statement. 9 | **/ 10 | class Solution { 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | 15 | Point rook = new Point(in); 16 | 17 | int nbPieces = in.nextInt(); 18 | int[][] board = new int[8][8]; 19 | for (int i = 0; i < nbPieces; i++) { 20 | int colour = in.nextInt(); 21 | Point onePiece = new Point(in); 22 | board[onePiece.x][onePiece.y] = colour == 0 ? -1 : 1; 23 | } 24 | 25 | List points = new ArrayList<>(); 26 | for (int i = rook.x - 1; i >= 0; i--) { 27 | if (horizontalCheck(rook, board, points, i)) break; 28 | } 29 | 30 | for (int i = rook.x + 1; i < 8; i++) { 31 | if (horizontalCheck(rook, board, points, i)) break; 32 | } 33 | 34 | for (int j = rook.y - 1; j >= 0; j--) { 35 | if (verticalCheck(rook, board, points, j)) break; 36 | } 37 | 38 | for (int j = rook.y + 1; j < 8; j++) { 39 | if (verticalCheck(rook, board, points, j)) break; 40 | } 41 | 42 | points.stream() 43 | .sorted(Comparator.comparing(p -> p.getString(rook))).forEach(p -> System.out.println(p.getString(rook))); 44 | } 45 | 46 | private static boolean horizontalCheck(Point rook, int[][] board, List points, int i) { 47 | if (board[i][rook.y] == -1) { 48 | return true; 49 | } else { 50 | points.add(new Point(i, rook.y, board[i][rook.y] == 1)); 51 | return board[i][rook.y] == 1; 52 | } 53 | } 54 | 55 | private static boolean verticalCheck(Point rook, int[][] board, List points, int j) { 56 | if (board[rook.x][j] == -1) { 57 | return true; 58 | } else { 59 | points.add(new Point(rook.x, j, board[rook.x][j] == 1)); 60 | return board[rook.x][j] == 1; 61 | } 62 | } 63 | } 64 | 65 | class Point { 66 | int x; 67 | int y; 68 | String pos; 69 | boolean taken; 70 | 71 | public Point(Scanner in) { 72 | this.pos = in.next(); 73 | this.x = (Character.getNumericValue(pos.charAt(0)) - 10); 74 | this.y = (Character.getNumericValue(pos.charAt(1)) - 1); 75 | } 76 | 77 | public Point(int x, int y, boolean taken) { 78 | this.x = x; 79 | this.y = y; 80 | this.taken = taken; 81 | } 82 | 83 | String getString(Point initial) { 84 | return "R" + initial.pos + (taken ? "x" : "-") + (char) (x + 'a') + "" + (y + 1); 85 | } 86 | } -------------------------------------------------------------------------------- /Easy/RubiksCubeMovements.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | List availableRotations = Arrays.asList("x", "x'", "y", "y'", "z", "z'"); 12 | Map rotationsMap = new HashMap<>(); 13 | rotationsMap.put("F", "UDLRFF"); 14 | rotationsMap.put("B", "DURLBB"); 15 | rotationsMap.put("U", "BFUURL"); 16 | rotationsMap.put("D", "FBDDLR"); 17 | rotationsMap.put("L", "LLBFUD"); 18 | rotationsMap.put("R", "RRFBDU"); 19 | 20 | List rotations = Arrays.asList(in.nextLine().split(" ")); 21 | 22 | Faces f = new Faces(in.nextLine(), in.nextLine()); 23 | 24 | rotations.parallelStream().forEach(rot -> { 25 | int index = availableRotations.indexOf(rot); 26 | f.s1 = rotationsMap.get(f.s1).substring(index, index + 1); 27 | f.s2 = rotationsMap.get(f.s2).substring(index, index + 1); 28 | }); 29 | 30 | System.out.println(f.s1); 31 | System.out.println(f.s2); 32 | } 33 | } 34 | 35 | class Faces { 36 | String s1; 37 | String s2; 38 | 39 | public Faces(String s1, String s2) { 40 | this.s1 = s1; 41 | this.s2 = s2; 42 | } 43 | } -------------------------------------------------------------------------------- /Easy/RugbyScore.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int score = in.nextInt(); 12 | 13 | for (int i = 0; i <= score / 5; i++) { 14 | for (int j = 0; j <= i; j++) { 15 | int nbPoint = score - (i * 5) - (j * 2); 16 | 17 | if (nbPoint >= 0 && nbPoint % 3 == 0) { 18 | System.out.println(i + " " + j + " " + nbPoint / 3); 19 | } 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Easy/SelfDrivingCarTesting.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayDeque; 2 | import java.util.Queue; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int N = in.nextInt(); 14 | in.nextLine(); 15 | String[] pos = in.nextLine().split(";"); 16 | int index = Integer.parseInt(pos[0]) - 1; 17 | 18 | Queue queue = new ArrayDeque<>(); 19 | for (int i = 1; i < pos.length; i++) { 20 | int nb = Integer.parseInt(pos[i].substring(0, pos[i].length() - 1)); 21 | char c = pos[i].charAt(pos[i].length() - 1); 22 | while (nb-- > 0) { 23 | queue.add(c == 'L' ? -1 : (c == 'R' ? 1 : 0)); 24 | } 25 | } 26 | 27 | index += queue.poll(); 28 | for (int i = 0; i < N; i++) { 29 | String[] patterns = in.nextLine().split(";"); 30 | int j = Integer.parseInt(patterns[0]); 31 | while (j-- > 0) { 32 | System.out.println(patterns[1].substring(0, index) + '#' + patterns[1].substring(index + 1)); 33 | index += queue.poll(); 34 | } 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Easy/SimpleAwale.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Scanner; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int[] opBowls = Arrays.stream(in.nextLine().split(" ")) 13 | .mapToInt(Integer::parseInt) 14 | .toArray(); 15 | int[] myBowls = Arrays.stream(in.nextLine().split(" ")) 16 | .mapToInt(Integer::parseInt) 17 | .toArray(); 18 | int num = in.nextInt(); 19 | 20 | int nbGrain = myBowls[num]; 21 | myBowls[num++] = 0; 22 | boolean mine = true; 23 | 24 | while (nbGrain > 0) { 25 | if ((mine && num >= 7) || (!mine && num >= 6)) { 26 | mine = !mine; 27 | num = 0; 28 | } 29 | 30 | if (mine) { 31 | myBowls[num]++; 32 | } else { 33 | opBowls[num]++; 34 | } 35 | 36 | num++; 37 | nbGrain--; 38 | } 39 | 40 | for (int i = 0; i < 6; i++) { 41 | System.out.print(opBowls[i] + " "); 42 | } 43 | System.out.println("[" + opBowls[6] + "]"); 44 | 45 | for (int i = 0; i < 6; i++) { 46 | System.out.print(myBowls[i] + " "); 47 | } 48 | System.out.println("[" + myBowls[6] + "]"); 49 | 50 | if (num == opBowls.length && mine) { 51 | System.out.println("REPLAY"); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /Easy/Smooth.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int N = in.nextInt(); 12 | 13 | for (int i = 0; i < N; i++) { 14 | System.out.println(reduce(in.nextLong()) ? "VICTORY" : "DEFEAT"); 15 | } 16 | } 17 | 18 | private static boolean reduce(long nb) { 19 | nb = reduceBy(nb, 5); 20 | nb = reduceBy(nb, 3); 21 | nb = reduceBy(nb, 2); 22 | 23 | return nb == 1; 24 | } 25 | 26 | private static long reduceBy(long nb, int red) { 27 | while (nb % red == 0) { 28 | nb /= red; 29 | } 30 | 31 | return nb; 32 | } 33 | } -------------------------------------------------------------------------------- /Easy/Temperatures.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int n = in.nextInt(); // the number of temperatures to analyse 12 | 13 | int closest = 0; 14 | for (int i = 0; i < n; i++) { 15 | int t = in.nextInt(); // a temperature expressed as an integer ranging from -273 to 5526 16 | if ((closest == 0 || Math.abs(closest) >= Math.abs(t)) 17 | && (Math.abs(closest) != Math.abs(t) || closest <= t)) { 18 | closest = t; 19 | } 20 | } 21 | 22 | System.out.println(closest); 23 | } 24 | } -------------------------------------------------------------------------------- /Easy/TextFormatting.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.regex.Matcher; 3 | import java.util.regex.Pattern; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | String intext = in.nextLine(); 14 | intext = intext.toLowerCase(); 15 | intext = intext.replaceAll("(\\s+)?([.,;]+)(\\s)?", "$2"); 16 | intext = intext.replaceAll("([.,;])+", "$1 "); 17 | intext = intext.replaceAll("(\\s)*", "$1"); 18 | intext = intext.trim(); 19 | 20 | Matcher m = Pattern.compile("(^|(?<=(\\.\\s)))(\\w)").matcher(intext); 21 | StringBuffer sb = new StringBuffer(); 22 | while (m.find()) { 23 | m.appendReplacement(sb, m.group(3).toUpperCase()); 24 | } 25 | intext = m.appendTail(sb).toString(); 26 | System.out.println(intext); 27 | } 28 | } -------------------------------------------------------------------------------- /Easy/TheDart101.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int N = in.nextInt(); 12 | in.nextLine(); 13 | 14 | Map playerMap = new LinkedHashMap<>(); 15 | String[] playerName = new String[N]; 16 | 17 | for (int i = 0; i < N; i++) { 18 | playerName[i] = in.nextLine(); 19 | playerMap.put(i, 0); 20 | } 21 | 22 | for (int i = 0; i < N; i++) { 23 | GameState gameState = new GameState(); 24 | 25 | String shot = in.nextLine(); 26 | 27 | String[] playerShoots = shot.split(" "); 28 | for (String playerShoot : playerShoots) { 29 | gameState.nbShot++; 30 | 31 | if (playerShoot.contains("X")) { 32 | gameState.addMiss(); 33 | } else { 34 | gameState.addScore(playerShoot); 35 | } 36 | 37 | if (gameState.getTotalScore() == 101) { 38 | playerMap.put(i, gameState.round); 39 | } else if (gameState.nbShot == 3) { 40 | gameState.endRound(); 41 | gameState.nextRound(); 42 | } else if (gameState.getTotalScore() > 101) { 43 | gameState.nextRound(); 44 | } 45 | } 46 | } 47 | 48 | Optional> entry = playerMap 49 | .entrySet() 50 | .stream().filter(e -> e.getValue() > 0).min(Map.Entry.comparingByValue()); 51 | 52 | System.out.println(playerName[entry.get().getKey()]); 53 | } 54 | } 55 | 56 | class GameState { 57 | int currentScore; 58 | int tmpScore; 59 | int miss; 60 | int round; 61 | int nbShot; 62 | 63 | public GameState() { 64 | this.round = 1; 65 | } 66 | 67 | private void resetScore() { 68 | this.currentScore = 0; 69 | this.tmpScore = 0; 70 | } 71 | 72 | void addMiss() { 73 | this.miss++; 74 | this.tmpScore -= 20; 75 | 76 | if (this.miss == 2) { 77 | this.tmpScore -= 10; 78 | } 79 | 80 | if (this.miss == 3) { 81 | this.resetScore(); 82 | } 83 | } 84 | 85 | void addScore(String shoot) { 86 | this.miss = 0; 87 | int index = shoot.indexOf("*"); 88 | if (index == -1) { 89 | this.tmpScore += Integer.parseInt(shoot); 90 | } else { 91 | this.tmpScore += Integer.parseInt(shoot.substring(0, index)) * Integer.parseInt(shoot.substring(index + 1)); 92 | } 93 | } 94 | 95 | void nextRound() { 96 | this.miss = 0; 97 | this.nbShot = 0; 98 | this.tmpScore = 0; 99 | this.round++; 100 | } 101 | 102 | void endRound() { 103 | this.currentScore += tmpScore; 104 | this.currentScore = this.currentScore < 0 ? 0 : this.currentScore; 105 | } 106 | 107 | int getTotalScore() { 108 | return this.tmpScore + this.currentScore; 109 | } 110 | } -------------------------------------------------------------------------------- /Easy/TheDescent.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * The while loop represents the game. 5 | * Each iteration represents a turn of the game 6 | * where you are given inputs (the heights of the mountains) 7 | * and where you have to print an output (the index of the mountain to fire on) 8 | * The inputs you are given are automatically updated according to your last actions. 9 | **/ 10 | class Player { 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | 15 | // game loop 16 | while (true) { 17 | int tmp = 0; 18 | int index = 0; 19 | for (int i = 0; i < 8; i++) { 20 | int mountainH = in.nextInt(); // represents the height of one mountain. 21 | if (mountainH > tmp) { 22 | tmp = mountainH; 23 | index = i; 24 | } 25 | } 26 | 27 | System.out.println(index); // The index of the mountain to fire on. 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /Easy/TheFrogJump1.java: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal; 2 | import java.math.RoundingMode; 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.Scanner; 7 | 8 | /** 9 | * Auto-generated code below aims at helping you parse 10 | * the standard input according to the problem statement. 11 | **/ 12 | class Solution { 13 | 14 | public static void main(String[] args) { 15 | Scanner in = new Scanner(System.in); 16 | int f = in.nextInt(); 17 | List jumps = new ArrayList<>(f); 18 | for (int i = 0; i < f; i++) { 19 | jumps.add(in.nextDouble()); 20 | } 21 | 22 | jumps.sort(Collections.reverseOrder()); 23 | 24 | int initialX = in.nextInt(); 25 | int initialY = in.nextInt(); 26 | int mass = in.nextInt(); 27 | int alpha = in.nextInt(); 28 | float speed = in.nextFloat(); 29 | float gravityA = in.nextFloat(); 30 | float gravityB = in.nextFloat(); 31 | 32 | double speedX = Math.cos(Math.toRadians(alpha)) * speed; 33 | double speedY = Math.sin(Math.toRadians(alpha)) * speed; 34 | 35 | double delta = speedY * speedY - 4 * (gravityB * 0.5d) * initialY; 36 | double time = (-1d * speedY - Math.sqrt(delta)) / (2d * gravityB * 0.5); 37 | 38 | double res = (gravityA * 0.5 * time * time) + (speedX * time) + initialX; 39 | BigDecimal bd = new BigDecimal(res); 40 | res = bd.setScale(2, RoundingMode.HALF_UP).doubleValue(); 41 | 42 | int index = f+1; 43 | for (int i = 0; i < jumps.size() ;i++) { 44 | if (jumps.get(i).compareTo(res) <= 0) { 45 | index = i + 1; 46 | break; 47 | } 48 | } 49 | 50 | System.out.println(index); 51 | } 52 | } -------------------------------------------------------------------------------- /Easy/TheHoochClashGrouch.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | import java.util.Scanner; 4 | import java.util.function.Function; 5 | import java.util.stream.Collectors; 6 | 7 | /** 8 | * Auto-generated code below aims at helping you parse 9 | * the standard input according to the problem statement. 10 | **/ 11 | class Solution { 12 | 13 | private static int[] combi = new int[]{1, 1, 2, 6, 24, 120}; 14 | private static double[] pow = new double[3500]; 15 | 16 | public static void main(String[] args) { 17 | Scanner in = new Scanner(System.in); 18 | int low = in.nextInt(); 19 | int high = in.nextInt(); 20 | 21 | Map volumes = new HashMap<>(); 22 | 23 | for (int i = low; i <= high; i++) { 24 | pow[i - low] = Math.pow(i * 0.5d, 3); 25 | } 26 | 27 | for (int i = low; i < high; i++) { 28 | for (int j = i + 1; j <= high; j++) { 29 | double val = pow[i - low] + pow[j - low]; 30 | volumes.compute(val, (k, v) -> (v == null) ? 1 : v + 1); 31 | } 32 | } 33 | 34 | long count = volumes.entrySet() 35 | .stream() 36 | .filter(e -> e.getValue() >= 2) 37 | .count(); 38 | 39 | Map maps = volumes.values() 40 | .stream() 41 | .filter(i -> i >= 2) 42 | .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); 43 | 44 | long count2 = maps.entrySet() 45 | .stream() 46 | .mapToLong(e -> e.getValue() * combi[e.getKey()]) 47 | .sum(); 48 | 49 | System.out.println(count + " " + count2); 50 | } 51 | } -------------------------------------------------------------------------------- /Easy/TheRiver1.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | long r1 = in.nextLong(); 12 | long r2 = in.nextLong(); 13 | 14 | boolean found = false; 15 | while (!found) { 16 | if (r1 < r2) { 17 | r1 = nextRiver(r1); 18 | } else if (r2 < r1) { 19 | r2 = nextRiver(r2); 20 | } else { 21 | found = true; 22 | } 23 | } 24 | 25 | System.out.println(r1); 26 | } 27 | 28 | private static long nextRiver(long n) { 29 | long s = n; 30 | while (s > 0) { 31 | n = n + (s % 10); 32 | s = s / 10; 33 | } 34 | return n; 35 | } 36 | } -------------------------------------------------------------------------------- /Easy/TheRiver2.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int r1 = in.nextInt(); 12 | 13 | boolean found = false; 14 | for (int start = r1 - 1; start > 0; start--) { 15 | int current = start; 16 | current = nextRiver(current); 17 | if (current == r1) { 18 | found = true; 19 | break; 20 | } 21 | } 22 | 23 | if (found) { 24 | System.out.println("YES"); 25 | } else { 26 | System.out.println("NO"); 27 | } 28 | } 29 | 30 | private static int nextRiver(int n) { 31 | int s = n; 32 | while (s > 0) { 33 | n = n + (s % 10); 34 | s = s / 10; 35 | } 36 | return n; 37 | } 38 | } -------------------------------------------------------------------------------- /Easy/TheTravellingSalesmanProblem.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Auto-generated code below aims at helping you parse 8 | * the standard input according to the problem statement. 9 | **/ 10 | class Solution { 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int N = in.nextInt(); 15 | Integer[][] cities = new Integer[N][2]; 16 | for (int i = 0; i < N; i++) { 17 | int X = in.nextInt(); 18 | int Y = in.nextInt(); 19 | cities[i] = new Integer[]{X, Y}; 20 | } 21 | 22 | Integer[] coord = cities[0]; 23 | List list = new ArrayList<>(Arrays.asList(cities)); 24 | list.remove(0); 25 | 26 | Double total = 0.0; 27 | while (!list.isEmpty()) { 28 | int index = 0; 29 | Double tmpDistance = -1.0; 30 | for (int i = 0; i < list.size(); i++) { 31 | Double d = calc(coord[0], coord[1], list.get(i)[0], list.get(i)[1]); 32 | if (tmpDistance < 0.0 || d < tmpDistance) { 33 | index = i; 34 | tmpDistance = d; 35 | } 36 | } 37 | 38 | total += tmpDistance; 39 | coord = list.get(index); 40 | list.remove(index); 41 | } 42 | 43 | total += calc(coord[0], coord[1], cities[0][0], cities[0][1]); 44 | 45 | System.out.println(Math.round(total)); 46 | } 47 | 48 | private static Double calc(int x, int y, int x1, int y1) { 49 | return Math.sqrt(Math.pow(x - x1, 2) + Math.pow(y - y1, 2)); 50 | } 51 | } -------------------------------------------------------------------------------- /Easy/WhatsSoComplexAboutMandelbrot.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | String c = in.nextLine(); 12 | 13 | int index = c.indexOf("+"); 14 | if (index == -1) { 15 | index = c.lastIndexOf("-"); 16 | } 17 | 18 | double cReal = Double.parseDouble(c.substring(0, index)); 19 | double cImag = Double.parseDouble(c.substring(index, c.length() - 1)); 20 | 21 | int m = in.nextInt(); 22 | double zReal = 0.0; 23 | double zImag = 0.0; 24 | 25 | for (int i = 0; i < m; i++) { 26 | double tmp = zReal; 27 | zReal = zReal * zReal - zImag * zImag + cReal; 28 | zImag = 2 * tmp * zImag + cImag; 29 | 30 | if (zReal * zReal + zImag * zImag >= 4.0) { 31 | m = i + 1; 32 | break; 33 | } 34 | } 35 | 36 | System.out.println(m); 37 | } 38 | } -------------------------------------------------------------------------------- /Easy/XmlMdf2016.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | private static HashMap weight = new HashMap<>(); 12 | 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | String sequence = in.nextLine(); 16 | 17 | System.err.println(sequence); 18 | 19 | char[] charArray = sequence.toCharArray(); 20 | int depth = 0; 21 | for (int i = 0; i < charArray.length; i++) { 22 | if (charArray[i] == '-') { 23 | i++; 24 | weight.putIfAbsent(charArray[i], 0d); 25 | weight.put(charArray[i], weight.get(charArray[i]) + (1d / depth)); 26 | depth--; 27 | } else { 28 | depth++; 29 | } 30 | } 31 | 32 | Map.Entry max = null; 33 | for (Map.Entry entry : weight.entrySet()) { 34 | if (max == null || max.getValue() < entry.getValue()) { 35 | max = entry; 36 | } 37 | } 38 | 39 | System.out.println(max != null ? max.getKey() : null); 40 | } 41 | } -------------------------------------------------------------------------------- /Hard/TheLastCrusadeEpisode2.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Player { 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | Game g = new Game(in); 11 | 12 | // game loop 13 | while (true) { 14 | g.playOneTurn(in); 15 | } 16 | } 17 | } 18 | 19 | class Game { 20 | 21 | private int width; 22 | private int height; 23 | private int exitIndex; 24 | 25 | private List clockWiseIndex; 26 | 27 | private int[][] maze; 28 | private boolean[][][] visited; 29 | 30 | private List directions; 31 | private List rocks; 32 | 33 | private String[][] pieces = { // Down : 'D', Left : 'L', Right : 'R' 34 | // Top, Left, Right 35 | {"X", "X", "X"}, //0 36 | {"D", "D", "D"}, //1 37 | {"X", "R", "L"}, //2 38 | {"D", "X", "X"}, //3 39 | {"L", "X", "D"}, //4 40 | {"R", "D", "X"}, //5 41 | {"X", "R", "L"}, //6 42 | {"D", "X", "D"}, //7 43 | {"X", "D", "D"}, //8 44 | {"D", "D", "X"}, //9 45 | {"L", "X", "X"}, //10 46 | {"R", "X", "X"}, //11 47 | {"X", "X", "D"}, //12 48 | {"X", "D", "X"}, //13 49 | }; 50 | 51 | public Game(Scanner in) { 52 | clockWiseIndex = Arrays.asList(0, 1, 3, 2, 5, 4, 7, 8, 9, 6, 11, 12, 13, 10); 53 | directions = Arrays.asList("TOP", "LEFT", "RIGHT"); 54 | 55 | width = in.nextInt(); // number of columns. 56 | height = in.nextInt(); // number of rows. 57 | in.nextLine(); 58 | 59 | maze = new int[height][width]; 60 | for (int i = 0; i < height; i++) { 61 | String[] LINE = in.nextLine().split(" "); // represents a line in the grid and contains W integers. Each integer represents one room of a given type. 62 | for (int j = 0; j < LINE.length; j++) { 63 | maze[i][j] = Integer.parseInt(LINE[j]); 64 | } 65 | } 66 | 67 | exitIndex = in.nextInt(); 68 | } 69 | 70 | void playOneTurn(Scanner in) { 71 | int XI = in.nextInt(); 72 | int YI = in.nextInt(); 73 | int POS = directions.indexOf(in.next()); 74 | int R = in.nextInt(); // the number of rocks currently in the grid. 75 | rocks = new ArrayList<>(); 76 | for (int i = 0; i < R; i++) { 77 | rocks.add(new Rock(in.nextInt(), in.nextInt(), directions.indexOf(in.next()))); 78 | } 79 | 80 | State s = getImmediateState(XI, YI, POS); 81 | if (s.order.equals("RIGHT")) { 82 | maze[s.y][s.x] = clockWiseIndex(maze[s.y][s.x]); 83 | } else if (s.order.equals("LEFT")) { 84 | maze[s.y][s.x] = counterClockWiseIndex(maze[s.y][s.x]); 85 | } 86 | 87 | if (s.order.equals("WAIT")) { 88 | System.out.println(s.order); 89 | } else { 90 | System.out.println(s.x + " " + s.y + " " + s.order); 91 | } 92 | } 93 | 94 | State getImmediateState(int x, int y, int pos) { 95 | List states = getAllStates(x, y, pos); 96 | if (states.size() <= 1) { 97 | return new State(x, y, "WAIT"); 98 | } else if (!states.get(1).order.equals("WAIT")) { 99 | return states.get(1); 100 | } 101 | 102 | State rockState = removeRocks(x, y, states); 103 | if (rockState != null) { 104 | return rockState; 105 | } 106 | 107 | return states.get(1); 108 | } 109 | 110 | State removeRocks(int x, int y, List states) { 111 | for (int i = 0; i < states.size() - 1; i++) { 112 | if (!states.get(i).order.equals("WAIT")) { 113 | List newRocks = new ArrayList<>(); 114 | Iterator it = rocks.iterator(); 115 | while (it.hasNext()) { 116 | Rock rock = it.next(); 117 | Room r = new Room(rock.x, rock.y, rock.direction, maze[rock.y][rock.x]); 118 | Room nextRoom = getNextRoom(r, r.type); 119 | if (nextRoom.isValid) { 120 | // Add next rock position for next iteration on states 121 | newRocks.add(new Rock(nextRoom.x, nextRoom.y, nextRoom.direction)); 122 | } 123 | 124 | it.remove(); 125 | } 126 | 127 | // Add all new rock position 128 | rocks.addAll(newRocks); 129 | } else { 130 | // try to remove rocks 131 | for (Rock rock : rocks) { 132 | if (rock.x == x && rock.y == y) continue; //prevent rotation of cell occupied by indy 133 | 134 | Room r = new Room(rock.x, rock.y, rock.direction, maze[rock.y][rock.x]); 135 | if (r.canClockWise()) { 136 | Room nextRoom = getNextRoom(r, clockWiseIndex(r.type)); 137 | if (nextRoom.x == states.get(1).x && nextRoom.y == states.get(1).y) continue; 138 | if (!nextRoom.isValid) { 139 | return new State(nextRoom.x, nextRoom.y, "RIGHT"); 140 | } 141 | } 142 | } 143 | } 144 | } 145 | 146 | return null; 147 | } 148 | 149 | List getAllStates(int x, int y, int pos) { 150 | System.err.println("Current room: (" + x + ", " + y + ") entering by " + directions.get(pos)); 151 | Room currentRoom = new Room(x, y, pos, maze[y][x]); 152 | 153 | visited = new boolean[width][height][3]; 154 | visited[x][y][pos] = true; 155 | 156 | Queue queue = new ArrayDeque<>(); 157 | Room r = getNextRoom(currentRoom, currentRoom.type); 158 | r.states.add(new State(x, y, "NONE")); 159 | queue.add(r); 160 | 161 | visited[r.x][r.y][r.direction] = true; 162 | 163 | while (queue.size() > 0) { 164 | Room room = queue.poll(); 165 | if (room.x == exitIndex && room.y == height - 1) { 166 | return room.states; 167 | } 168 | queue.addAll(getNextRooms(room)); 169 | } 170 | 171 | return new ArrayList<>(); 172 | } 173 | 174 | List getNextRooms(Room room) { 175 | ArrayList res = new ArrayList<>(); 176 | 177 | // No rotation, we'll use this 'state' to replace it if needed 178 | Room nextRoom = getNextRoom(room, room.type); 179 | checkAndAddIfAbsent(room, nextRoom, res, "WAIT"); 180 | 181 | if (room.canClockWise()) { 182 | // rotate clockwise 183 | nextRoom = getNextRoom(room, clockWiseIndex(room.type)); 184 | checkAndAddIfAbsent(room, nextRoom, res, "RIGHT"); 185 | } 186 | // skip room type 2 3 4 5 for counterclockwise rotation since they are the same 187 | if (room.canCounterClockWise()) { 188 | // rotate counterclockwise 189 | nextRoom = getNextRoom(room, counterClockWiseIndex(room.type)); 190 | checkAndAddIfAbsent(room, nextRoom, res, "LEFT"); 191 | 192 | // Special case of double rotate 193 | nextRoom = getNextRoom(room, counterClockWiseIndex(counterClockWiseIndex(room.type))); 194 | checkAndAddDoubleIfAbsent(room, nextRoom, res); 195 | } 196 | 197 | return res; 198 | } 199 | 200 | private void checkAndAddIfAbsent(Room room, Room nextRoom, ArrayList res, String order) { 201 | if (nextRoom.isValid && !visited[nextRoom.x][nextRoom.y][nextRoom.direction]) { 202 | nextRoom.states.addAll(room.states); 203 | nextRoom.states.add(new State(room.x, room.y, order)); 204 | 205 | visited[nextRoom.x][nextRoom.y][nextRoom.direction] = true; 206 | 207 | System.err.println("Adding room: (" + room.x + ", " + room.y + ")[" + room.type + "][" + directions.get(room.direction) + "] -> " + order); 208 | 209 | res.add(nextRoom); 210 | } 211 | } 212 | 213 | // Special case 214 | private void checkAndAddDoubleIfAbsent(Room room, Room nextRoom, ArrayList res) { 215 | if (nextRoom.isValid && !visited[nextRoom.x][nextRoom.y][nextRoom.direction]) { 216 | nextRoom.states.addAll(room.states); 217 | visited[nextRoom.x][nextRoom.y][nextRoom.direction] = true; 218 | 219 | // Find the first WAIT state to replace it 220 | int i; 221 | for (i = room.states.size() - 1; i >= 0; i--) { 222 | if (room.states.get(i).order.equals("WAIT")) { 223 | break; 224 | } 225 | } 226 | if (i >= 0) { 227 | nextRoom.states.set(i, new State(room.x, room.y, "RIGHT")); 228 | } 229 | nextRoom.states.add(new State(room.x, room.y, "RIGHT")); 230 | 231 | System.err.println("Adding room: (" + room.x + ", " + room.y + ")[" + room.type + "][" + directions.get(room.direction) + "] -> " + "RIGHT"); 232 | 233 | res.add(nextRoom); 234 | } 235 | } 236 | 237 | Room getNextRoom(Room r, int roomType) { 238 | String exit = pieces[Math.abs(roomType)][r.direction]; 239 | 240 | // Check if current rotation (or lack of) produce a correct exit from the current direction 241 | boolean isValid = !exit.equals("X"); 242 | 243 | // Build the next Room object 244 | int newX = r.x + (exit.equals("L") ? -1 : (exit.equals("R") ? 1 : 0)); 245 | int newY = r.y + (exit.equals("D") ? 1 : 0); 246 | 247 | if (newX >= width || newX < 0) { 248 | isValid = false; 249 | newX = r.x; 250 | } 251 | if (newY >= height) { 252 | isValid = false; 253 | newY = r.y; 254 | } 255 | 256 | if (r.x == newX && r.y == newY) { 257 | isValid = false; 258 | } 259 | 260 | String res; 261 | switch (exit) { 262 | case "L": 263 | res = "RIGHT"; 264 | break; 265 | case "R": 266 | res = "LEFT"; 267 | break; 268 | default: 269 | res = "TOP"; 270 | break; 271 | } 272 | 273 | return new Room(newX, newY, directions.indexOf(res), maze[newY][newX], isValid); 274 | } 275 | 276 | int clockWiseIndex(int index) { 277 | return clockWiseIndex.get(index); 278 | } 279 | 280 | int counterClockWiseIndex(int index) { 281 | return clockWiseIndex.indexOf(index); 282 | } 283 | } 284 | 285 | abstract class Coordinate { 286 | int x; 287 | int y; 288 | 289 | public Coordinate(int x, int y) { 290 | this.x = x; 291 | this.y = y; 292 | } 293 | } 294 | 295 | class Rock extends Coordinate { 296 | int direction; 297 | 298 | public Rock(int x, int y, int direction) { 299 | super(x, y); 300 | this.direction = direction; 301 | } 302 | } 303 | 304 | class State extends Coordinate { 305 | String order; 306 | 307 | public State(int x, int y, String order) { 308 | super(x, y); 309 | this.order = order; 310 | } 311 | } 312 | 313 | class Room extends Coordinate { 314 | int direction; 315 | int type; 316 | boolean isValid; // Can we access this room ? 317 | List states; 318 | 319 | public Room(int x, int y, int direction, int type) { 320 | super(x, y); 321 | this.direction = direction; 322 | this.type = type; 323 | this.states = new ArrayList<>(); 324 | } 325 | 326 | public Room(int x, int y, int direction, int type, boolean isValid) { 327 | super(x, y); 328 | this.direction = direction; 329 | this.type = type; 330 | this.isValid = isValid; 331 | this.states = new ArrayList<>(); 332 | } 333 | 334 | boolean canClockWise() { 335 | return type >= 2; 336 | } 337 | 338 | boolean canCounterClockWise() { 339 | return type >= 6; 340 | } 341 | } -------------------------------------------------------------------------------- /Medium/AChildsPlay.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Objects; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Auto-generated code below aims at helping you parse 8 | * the standard input according to the problem statement. 9 | **/ 10 | class Solution { 11 | 12 | public static void main(String args[]) { 13 | Scanner in = new Scanner(System.in); 14 | int w = in.nextInt(); 15 | int h = in.nextInt(); 16 | long nb = in.nextLong(); 17 | if (in.hasNextLine()) { 18 | in.nextLine(); 19 | } 20 | 21 | int x = 0; 22 | int y = 0; 23 | 24 | char[][] grid = new char[h][w]; 25 | 26 | for (int i = 0; i < h; i++) { 27 | String str = in.nextLine(); 28 | grid[i] = str.toCharArray(); 29 | int val = str.indexOf('O'); 30 | if (val > 0) { 31 | y = i; 32 | x = val; 33 | } 34 | } 35 | 36 | Dir dir = Dir.TOP; 37 | 38 | // Find Cycle 39 | List cycles = new ArrayList<>(); 40 | 41 | while (true) { 42 | if (grid[y + dir.getY()][x + dir.getX()] == '#') { 43 | switch (dir) { 44 | case LEFT: 45 | dir = Dir.TOP; 46 | break; 47 | case TOP: 48 | dir = Dir.RIGHT; 49 | break; 50 | case RIGHT: 51 | dir = Dir.DOWN; 52 | break; 53 | case DOWN: 54 | dir = Dir.LEFT; 55 | break; 56 | } 57 | } 58 | 59 | y += dir.getY(); 60 | x += dir.getX(); 61 | 62 | Cycle curr = new Cycle(x, y, dir); 63 | 64 | if (cycles.contains(curr)) { 65 | break; 66 | } 67 | cycles.add(curr); 68 | } 69 | 70 | int val = (int) (nb % cycles.size()); 71 | 72 | Cycle c = cycles.get(val - 1); 73 | 74 | System.out.println(c.x + " " + c.y); 75 | } 76 | } 77 | 78 | enum Dir { 79 | LEFT(-1, 0), 80 | TOP(0, -1), 81 | RIGHT(1, 0), 82 | DOWN(0, 1), 83 | ; 84 | 85 | Dir(int x, int y) { 86 | this.x = x; 87 | this.y = y; 88 | } 89 | 90 | private int x; 91 | private int y; 92 | 93 | public int getX() { 94 | return x; 95 | } 96 | 97 | public int getY() { 98 | return y; 99 | } 100 | } 101 | 102 | class Cycle { 103 | int x; 104 | int y; 105 | Dir dir; 106 | 107 | public Cycle(int x, int y, Dir dir) { 108 | this.x = x; 109 | this.y = y; 110 | this.dir = dir; 111 | } 112 | 113 | @Override 114 | public boolean equals(Object o) { 115 | if (this == o) return true; 116 | if (o == null || getClass() != o.getClass()) return false; 117 | Cycle cycle = (Cycle) o; 118 | return x == cycle.x && 119 | y == cycle.y && 120 | dir == cycle.dir; 121 | } 122 | 123 | @Override 124 | public int hashCode() { 125 | return Objects.hash(x, y, dir); 126 | } 127 | } -------------------------------------------------------------------------------- /Medium/Aneo.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int speed = in.nextInt(); 12 | int lightCount = in.nextInt(); 13 | int[][] lights = new int[lightCount][2]; 14 | for (int i = 0; i < lightCount; i++) { 15 | lights[i] = new int[]{in.nextInt(), in.nextInt()}; 16 | } 17 | 18 | for (int i = 0; i < lightCount; i++) { 19 | if ((36 * lights[i][0]) % (20 * speed * lights[i][1]) >= (10 * speed * lights[i][1])) { 20 | speed--; 21 | i = -1; 22 | } 23 | } 24 | 25 | System.out.println(speed); 26 | } 27 | } -------------------------------------------------------------------------------- /Medium/BenderEpisode1.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | static Grid[][] grid; 12 | static List teleports; 13 | 14 | public static void main(String[] args) { 15 | Scanner in = new Scanner(System.in); 16 | int L = in.nextInt(); 17 | int C = in.nextInt(); 18 | 19 | in.nextLine(); 20 | 21 | Bender b = new Bender(-1, -1); 22 | 23 | grid = new Grid[L][C]; 24 | teleports = new ArrayList<>(); 25 | 26 | for (int i = 0; i < L; i++) { 27 | char[] tmp = in.nextLine().toCharArray(); 28 | for (int j = 0; j < C; j++) { 29 | grid[i][j] = new Grid(tmp[j]); 30 | if (tmp[j] == '@') { 31 | b = new Bender(j, i); 32 | } else if (tmp[j] == 'T') { 33 | teleports.add(new Teleport(j, i)); 34 | } 35 | } 36 | } 37 | 38 | List moves = new ArrayList<>(); 39 | 40 | boolean done = false; 41 | while (!done) { 42 | updateDirection(b); 43 | String move = move(b); 44 | if (move.equals("FINAL")) { 45 | done = true; 46 | moves.add(b.getDirection()); 47 | } else if (move.equals("LOOP")) { 48 | done = true; 49 | moves.clear(); 50 | } else { 51 | moves.add(move); 52 | } 53 | } 54 | 55 | if (moves.isEmpty()) { 56 | System.out.println("LOOP"); 57 | } else { 58 | moves.forEach(System.out::println); 59 | } 60 | } 61 | 62 | private static void updateDirection(Bender b) { 63 | Grid g = grid[b.getNextY()][b.getNextX()]; 64 | switch (g.c) { 65 | case 'X': 66 | if (b.enraged) { 67 | break; 68 | } 69 | case '#': 70 | for (int i = 0; i <= 3; i++) { 71 | b.index = b.reversed ? 3 - i : i; 72 | if (!grid[b.getNextY()][b.getNextX()].isObstacle() && !grid[b.getNextY()][b.getNextX()].isVisitedTooManyTime(b.index)) { 73 | break; 74 | } 75 | } 76 | break; 77 | default: 78 | break; 79 | } 80 | } 81 | 82 | private static String move(Bender b) { 83 | b.moveNext(); 84 | 85 | String res = b.getDirection(); 86 | 87 | Grid g = grid[b.y][b.x]; 88 | g.visited[b.index]++; 89 | 90 | if (g.isVisitedTooManyTime(b.index)) { 91 | return "LOOP"; 92 | } 93 | 94 | switch (g.c) { 95 | case 'B': 96 | b.enraged = !b.enraged; 97 | break; 98 | case 'S': 99 | b.index = 0; 100 | break; 101 | case 'E': 102 | b.index = 1; 103 | break; 104 | case 'N': 105 | b.index = 2; 106 | break; 107 | case 'W': 108 | b.index = 3; 109 | break; 110 | case 'I': 111 | b.reversed = !b.reversed; 112 | break; 113 | case 'T': 114 | if (teleports.get(0).x == b.x && teleports.get(0).y == b.y) { 115 | b.x = teleports.get(1).x; 116 | b.y = teleports.get(1).y; 117 | } else { 118 | b.x = teleports.get(0).x; 119 | b.y = teleports.get(0).y; 120 | } 121 | break; 122 | case '$': 123 | res = "FINAL"; 124 | break; 125 | case 'X': 126 | if (b.enraged) { 127 | g.c = ' '; 128 | break; 129 | } 130 | default: 131 | break; 132 | } 133 | 134 | 135 | return res; 136 | } 137 | } 138 | 139 | class Teleport { 140 | int x; 141 | int y; 142 | 143 | Teleport(int x, int y) { 144 | this.x = x; 145 | this.y = y; 146 | } 147 | } 148 | 149 | class Bender { 150 | int x; 151 | int y; 152 | 153 | private final int[][] directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; 154 | private final String[] dirString = {"SOUTH", "EAST", "NORTH", "WEST"}; 155 | int index = 0; 156 | 157 | boolean enraged; 158 | boolean reversed; 159 | 160 | String getDirection() { 161 | return dirString[index]; 162 | } 163 | 164 | 165 | Bender(int x, int y) { 166 | this.x = x; 167 | this.y = y; 168 | } 169 | 170 | void moveNext() { 171 | x = getNextX(); 172 | y = getNextY(); 173 | } 174 | 175 | int getNextY() { 176 | return y + directions[index][0]; 177 | } 178 | 179 | int getNextX() { 180 | return x + directions[index][1]; 181 | } 182 | } 183 | 184 | class Grid { 185 | char c; 186 | int[] visited = new int[4]; 187 | 188 | Grid(char c) { 189 | this.c = c; 190 | } 191 | 192 | boolean isObstacle() { 193 | return c == '#' || c == 'X'; 194 | } 195 | 196 | boolean isVisitedTooManyTime(int index) { 197 | return visited[index] > 4; 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /Medium/CGFungeInterpreter.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.Stack; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | 10 | private static final int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int N = in.nextInt(); 15 | if (in.hasNextLine()) { 16 | in.nextLine(); 17 | } 18 | 19 | String[] lines = new String[N]; 20 | 21 | for (int i = 0; i < N; i++) { 22 | lines[i] = in.nextLine(); 23 | } 24 | 25 | Position p = new Position(0, 0, 0); 26 | 27 | Stack stack = new Stack<>(); 28 | 29 | char c = lines[p.y].charAt(p.x); 30 | boolean charValue = false; 31 | 32 | while (c != 'E') { 33 | if (charValue && c != '"') { 34 | stack.push((int) c); 35 | } else if (c != ' ') { 36 | switch (c) { 37 | case '>': 38 | p.index = 0; 39 | break; 40 | case '<': 41 | p.index = 2; 42 | break; 43 | case '^': 44 | p.index = 3; 45 | break; 46 | case 'v': 47 | p.index = 1; 48 | break; 49 | case 'S': 50 | move(p, 1); 51 | break; 52 | case 'P': 53 | stack.pop(); 54 | break; 55 | case 'X': 56 | int a = stack.pop(); 57 | int b = stack.pop(); 58 | stack.push(a); 59 | stack.push(b); 60 | break; 61 | case 'D': 62 | stack.push(stack.peek()); 63 | break; 64 | case '_': 65 | int e = stack.pop(); 66 | if (e == 0) { 67 | p.index = 0; 68 | } else { 69 | p.index = 2; 70 | } 71 | break; 72 | case '|': 73 | int f = stack.pop(); 74 | if (f == 0) { 75 | p.index = 1; 76 | } else { 77 | p.index = 3; 78 | } 79 | break; 80 | case 'I': 81 | System.out.print(stack.pop()); 82 | break; 83 | case 'C': 84 | System.out.print(Character.toChars(stack.pop())); 85 | break; 86 | case '+': 87 | stack.push(stack.pop() + stack.pop()); 88 | break; 89 | case '-': 90 | int d = stack.pop(); 91 | stack.push(stack.pop() - d); 92 | break; 93 | case '*': 94 | stack.push(stack.pop() * stack.pop()); 95 | break; 96 | case '"': 97 | charValue = !charValue; 98 | break; 99 | default: 100 | stack.push(c - '0'); 101 | break; 102 | } 103 | } 104 | 105 | move(p, 1); 106 | c = lines[p.y].charAt(p.x); 107 | } 108 | } 109 | 110 | private static void move(Position p, int i) { 111 | int[] d = directions[p.index]; 112 | p.x += d[1] * i; 113 | p.y += d[0] * i; 114 | } 115 | } 116 | 117 | class Position { 118 | int x; 119 | int y; 120 | int index; 121 | 122 | public Position(int x, int y, int index) { 123 | this.x = x; 124 | this.y = y; 125 | this.index = index; 126 | } 127 | } -------------------------------------------------------------------------------- /Medium/ConwaySequence.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.stream.Collectors; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int R = in.nextInt(); 13 | int L = in.nextInt(); 14 | 15 | Queue queue = new ArrayDeque<>(); 16 | queue.add(R); 17 | 18 | List list = new ArrayList<>(); 19 | 20 | for (int i = 1; i < L; i++) { 21 | list.clear(); 22 | 23 | int current = queue.poll(); 24 | int counter = 1; 25 | while (!queue.isEmpty()) { 26 | int j = queue.poll(); 27 | if (current == j) { 28 | counter++; 29 | } else { 30 | list.add(counter); 31 | list.add(current); 32 | current = j; 33 | counter = 1; 34 | } 35 | } 36 | 37 | list.add(counter); 38 | list.add(current); 39 | 40 | queue.addAll(list); 41 | } 42 | 43 | System.out.println(queue.stream().map(Object::toString).collect(Collectors.joining(" "))); 44 | } 45 | } -------------------------------------------------------------------------------- /Medium/DepotOrganization.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.stream.Collectors; 3 | import java.util.stream.Stream; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | static Depot[] allDepots = new Depot[7]; 12 | 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | 16 | for (int i = 0; i < 7; i++) { 17 | allDepots[i] = new Depot(i, in.nextLine().split(" ")); 18 | } 19 | 20 | Depot[] tmp = new Depot[7]; 21 | recursiveFind(tmp, 0); 22 | 23 | System.out.println(Stream.of(1, 2, 6, 0, 3, 5, 4).map(i -> tmp[i].getResult()).collect(Collectors.joining(" "))); 24 | } 25 | 26 | static boolean recursiveFind(Depot[] depots, int index) { 27 | if (index == 7) { 28 | return true; 29 | } 30 | 31 | if (index == 0) { 32 | for (int i = 0; i < 7; i++) { 33 | Depot d = allDepots[i]; 34 | d.putSmallestOnRight(); 35 | depots[0] = d; 36 | if (recursiveFind(depots, index + 1)) { 37 | return true; 38 | } 39 | } 40 | } else { 41 | for (int i = 0; i < 7; i++) { 42 | Depot d = allDepots[i]; 43 | 44 | if (alreadyUsed(d.index, depots, index)) { 45 | continue; 46 | } 47 | 48 | for (int k = 0; k < 6; k++) { 49 | if (d.tab[index % 6].equals(depots[0].tab[(3 + index) % 6]) && (index == 1 || d.tab[(1 + index) % 6].equals(depots[index - 1].tab[index - 2]))) { 50 | depots[index] = d; 51 | 52 | if (recursiveFind(depots, index + 1)) { 53 | return true; 54 | } 55 | } 56 | d.turnClockWise(); 57 | } 58 | } 59 | } 60 | 61 | return false; 62 | } 63 | 64 | private static boolean alreadyUsed(int currentDepotIndex, Depot[] depotsUsed, int index) { 65 | boolean used = false; 66 | for (int j = 0; j < index; j++) { 67 | if (depotsUsed[j].index == currentDepotIndex) { 68 | used = true; 69 | break; 70 | } 71 | } 72 | return used; 73 | } 74 | } 75 | 76 | class Depot { 77 | int index; 78 | String[] tab; 79 | private String smallest; 80 | 81 | Depot(int index, String[] tab) { 82 | this.index = index; 83 | this.tab = tab; 84 | smallest = tab[0]; 85 | for (int i = 1; i < tab.length; i++) { 86 | if (tab[i].compareTo(smallest) < 0) { 87 | smallest = tab[i]; 88 | } 89 | } 90 | } 91 | 92 | void turnClockWise() { 93 | String[] tmp = new String[6]; 94 | System.arraycopy(tab, 0, tmp, 1, 5); 95 | tmp[0] = tab[5]; 96 | tab = tmp; 97 | } 98 | 99 | private boolean smallestOnRight() { 100 | return tab[0].equals(smallest); 101 | } 102 | 103 | void putSmallestOnRight() { 104 | while (!smallestOnRight()) { 105 | turnClockWise(); 106 | } 107 | } 108 | 109 | String getResult() { 110 | return index + tab[0]; 111 | } 112 | } -------------------------------------------------------------------------------- /Medium/DiceProbabilityCalculator.java: -------------------------------------------------------------------------------- 1 | import javax.script.ScriptEngine; 2 | import javax.script.ScriptEngineManager; 3 | import javax.script.ScriptException; 4 | import java.text.DecimalFormat; 5 | import java.math.RoundingMode; 6 | import java.util.*; 7 | import java.util.regex.Matcher; 8 | import java.util.regex.Pattern; 9 | import java.util.Scanner; 10 | 11 | /** 12 | * Auto-generated code below aims at helping you parse 13 | * the standard input according to the problem statement. 14 | **/ 15 | class Solution { 16 | 17 | static Map total = new HashMap<>(); 18 | static Map dices = new HashMap<>(); 19 | 20 | static List exprList = new ArrayList<>(); 21 | 22 | static ScriptEngineManager mgr = new ScriptEngineManager(); 23 | static ScriptEngine engine = mgr.getEngineByName("JavaScript"); 24 | 25 | static final String DICE = "DICE"; 26 | 27 | public static void main(String[] args) { 28 | Scanner in = new Scanner(System.in); 29 | String expr = in.nextLine(); 30 | 31 | Matcher m = Pattern.compile("d[0-9]").matcher(expr); 32 | 33 | int lastIndex = 0; 34 | while (m.find()) { 35 | String str = expr.substring(lastIndex, m.start()); 36 | exprList.add(str); 37 | exprList.add(DICE); 38 | dices.put(exprList.size() - 1, Integer.parseInt(m.group().substring(1, 2))); 39 | lastIndex += str.length() + 2; 40 | } 41 | 42 | if (lastIndex != expr.length()) { 43 | exprList.add(expr.substring(lastIndex)); 44 | } 45 | 46 | try { 47 | evaluate("", exprList, 0); 48 | } catch (ScriptException e) { 49 | e.printStackTrace(); 50 | } 51 | 52 | int nbCombination = total.values().stream().mapToInt(i -> i).sum(); 53 | 54 | DecimalFormat format = new DecimalFormat("##.00"); 55 | format.setRoundingMode(RoundingMode.HALF_UP); 56 | 57 | total.entrySet().stream().sorted(Map.Entry.comparingByKey()) 58 | .forEach(e -> System.out.println(e.getKey() + " " + format.format(e.getValue() * 100d / nbCombination))); 59 | } 60 | 61 | private static void evaluate(String eval, List exprList, int arrayIndex) throws ScriptException { 62 | if (exprList.size() <= arrayIndex) { 63 | Object value = engine.eval(eval); 64 | int val = value instanceof Boolean ? ((boolean)value ? 1 : 0) : (int)value; 65 | 66 | total.putIfAbsent(val, 0); 67 | total.computeIfPresent(val, (k, v) -> v+1); 68 | 69 | return; 70 | } 71 | 72 | if (exprList.get(arrayIndex).equals(DICE)) { 73 | for (int diceValue = 1; diceValue <= dices.get(arrayIndex); diceValue++) { 74 | evaluate(eval + diceValue, exprList, arrayIndex + 1); 75 | } 76 | } else { 77 | evaluate(eval + exprList.get(arrayIndex), exprList, arrayIndex + 1); 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /Medium/DigitSumSuccessor.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | 12 | String number = "0" + in.nextLong(); 13 | 14 | String trailingZero = ""; 15 | String lowestDigit = ""; 16 | String nines = ""; 17 | String remaining = ""; 18 | 19 | for (int i = number.length() - 1; i >= 0; i--) { 20 | if (number.charAt(i) != '0') { 21 | lowestDigit = "" + number.charAt(i); 22 | break; 23 | } 24 | trailingZero = number.charAt(i) + trailingZero; 25 | } 26 | 27 | int nbChar = lowestDigit.length() + trailingZero.length(); 28 | 29 | for (int i = number.length() - 1 - nbChar; i >= 0; i--) { 30 | if (number.charAt(i) != '9') { 31 | break; 32 | } 33 | nines = number.charAt(i) + nines; 34 | } 35 | 36 | nbChar += nines.length(); 37 | 38 | if (number.length() - nbChar > 0) { 39 | remaining = number.substring(0, number.length() - nbChar); 40 | } 41 | 42 | StringBuilder build = new StringBuilder(); 43 | if (!remaining.equals("")) { 44 | build.append((Integer.parseInt(remaining) + 1)); 45 | } 46 | if (!trailingZero.equals("")) { 47 | build.append(trailingZero); 48 | } 49 | if (!lowestDigit.equals("")) { 50 | build.append((Integer.parseInt(lowestDigit) - 1)); 51 | } 52 | if (!nines.equals("")) { 53 | build.append(nines); 54 | } 55 | 56 | System.out.println(build.toString()); 57 | } 58 | } -------------------------------------------------------------------------------- /Medium/DigitSumSuccessor2.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.util.regex.Matcher; 3 | import java.util.regex.Pattern; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | 14 | String number = "0" + in.nextLong(); 15 | 16 | Pattern p = Pattern.compile("(\\d*?)(9*)([1-9])(0*)$"); 17 | Matcher m = p.matcher(number); 18 | 19 | if (m.find()) { // Don't forget this one ^^ 20 | String trailingZero = m.group(4); 21 | String nines = m.group(2); 22 | int lowestDigit = Integer.parseInt(m.group(3)) - 1; 23 | int remaining = m.group(1).isEmpty() ? 0 : (Integer.parseInt(m.group(1)) + 1); 24 | 25 | String nextNumber = remaining + "" + trailingZero + lowestDigit + nines; 26 | 27 | System.out.println(nextNumber); 28 | } else { 29 | System.out.println(); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Medium/DontPanicEpisode1.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Player { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int nbFloors = in.nextInt(); // number of floors 12 | int width = in.nextInt(); // width of the area 13 | int nbRounds = in.nextInt(); // maximum number of rounds 14 | int exitFloor = in.nextInt(); // floor on which the exit is found 15 | int exitPos = in.nextInt(); // position of the exit on its floor 16 | int nbTotalClones = in.nextInt(); // number of generated clones 17 | int nbAdditionalElevators = in.nextInt(); // ignore (always zero) 18 | int nbElevators = in.nextInt(); // number of elevators 19 | int[] floors = new int[nbElevators+1]; 20 | floors[exitFloor] = exitPos; 21 | for (int i = 0; i < nbElevators; i++) { 22 | floors[in.nextInt()] = in.nextInt(); 23 | } 24 | 25 | // game loop 26 | while (true) { 27 | int floor = in.nextInt(); // floor of the leading clone 28 | int pos = in.nextInt(); // position of the leading clone on its floor 29 | int dir = in.next().compareTo("NONE"); // direction of the leading clone: LEFT or RIGHT 30 | 31 | boolean block = (floor >= 0) && (dir < 1 ? pos < floors[floor] : dir > 1 && pos > floors[floor]); 32 | 33 | System.out.println(block ? "BLOCK" : "WAIT"); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /Medium/DwarfsStandingOnTheShouldersOfGiants.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | static Map> map = new HashMap<>(); 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int n = in.nextInt(); // the number of relationships of influence 14 | 15 | for (int i = 0; i < n; i++) { 16 | map.computeIfAbsent(in.nextInt(), k -> new ArrayList<>()).add(in.nextInt()); 17 | } 18 | 19 | int max = 0; 20 | for (Map.Entry> e : map.entrySet()) { 21 | max = Math.max(max, findMaxDepth(e.getKey())); 22 | } 23 | 24 | System.out.println(max); 25 | } 26 | 27 | private static int findMaxDepth(Integer key) { 28 | List list = map.get(key); 29 | if (list!= null && !list.isEmpty()) { 30 | int max = 0; 31 | for (Integer i : list) { 32 | max = Math.max(max, findMaxDepth(i) + 1); 33 | } 34 | return max; 35 | } 36 | return 1; 37 | } 38 | } -------------------------------------------------------------------------------- /Medium/ElementaryCellularAutomaton.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | static List neighborhood = Arrays.asList("111", "110", "101", "100", "011", "010", "001", "000"); 12 | 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | 16 | String[] binary = Integer.toBinaryString((1 << 8) | in.nextInt()).substring(1).split(""); 17 | 18 | int N = in.nextInt(); 19 | String p = in.next(); 20 | 21 | System.out.println(p); 22 | p = p.replaceAll("\\.", "0").replaceAll("@", "1"); 23 | 24 | int l = p.length(); 25 | for (int i = 0; i < N - 1; i++) { 26 | StringBuilder tmp = new StringBuilder(); 27 | for (int j = 0; j < l; j++) { 28 | char c = p.charAt((l + j - 1) % l); 29 | char c1 = p.charAt((l + j) % l); 30 | char c2 = p.charAt((l + j + 1) % l); 31 | 32 | int index = neighborhood.indexOf("" + c + c1 + c2); 33 | tmp.append(binary[index]); 34 | } 35 | p = tmp.toString(); 36 | System.out.println(p.replaceAll("0", "\\.").replaceAll("1", "@")); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Medium/FactorialVsExponential.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Scanner; 4 | import java.util.stream.Collectors; 5 | 6 | /** 7 | * Auto-generated code below aims at helping you parse 8 | * the standard input according to the problem statement. 9 | **/ 10 | class Solution { 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int K = in.nextInt(); 15 | List s = new ArrayList<>(); 16 | for (int i = 0; i < K; i++) { 17 | float A = in.nextFloat(); 18 | 19 | int val = 1; 20 | double fact = 0; // ln(1) 21 | while (val * Math.log(A) > fact) { 22 | fact += Math.log(++val); // ln(n!) = ln(2) + ln(3) + ... 23 | } 24 | 25 | s.add(val); 26 | } 27 | 28 | System.out.println(s.stream().map(String::valueOf).collect(Collectors.joining(" "))); 29 | } 30 | } -------------------------------------------------------------------------------- /Medium/FindTheWinningStrategy.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Player { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int rows = in.nextInt(); // Number of rows 12 | in.nextInt(); // Number of columns 13 | 14 | int[][] grid = new int[rows][2]; 15 | 16 | // game loop 17 | while (true) { 18 | int nimSum = 0; 19 | for (int i = 0; i < rows; i++) { 20 | int xPlayer = in.nextInt(); // Position of the first player's token 21 | int xBoss = in.nextInt(); // Position of the second player's token 22 | 23 | int nimber = xBoss - xPlayer - 1; 24 | nimSum ^= nimber; 25 | 26 | grid[i] = new int[]{xPlayer, nimber}; 27 | } 28 | 29 | for (int i = 0; i < rows; i++) { 30 | int test = grid[i][1] ^ nimSum; 31 | if (test <= grid[i][1]) { 32 | System.out.println(i + " " + (grid[i][0] + (grid[i][1] - test))); 33 | break; 34 | } 35 | } 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /Medium/FoldingPaper.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | String order = in.nextLine(); 14 | String side = in.nextLine(); 15 | 16 | Map map = new HashMap<>(); 17 | map.put('U', 1); 18 | map.put('R', 1); 19 | map.put('L', 1); 20 | map.put('D', 1); 21 | 22 | for (int i = 0; i < order.length(); i++) { 23 | char c = order.charAt(i); 24 | 25 | switch (c) { 26 | case 'U': 27 | map.computeIfPresent('R', (k, v) -> v *= 2); 28 | map.computeIfPresent('L', (k, v) -> v *= 2); 29 | map.put('D', map.get('D') + map.get('U')); 30 | break; 31 | case 'D': 32 | map.computeIfPresent('R', (k, v) -> v *= 2); 33 | map.computeIfPresent('L', (k, v) -> v *= 2); 34 | map.put('U', map.get('U') + map.get('D')); 35 | break; 36 | case 'L': 37 | map.computeIfPresent('U', (k, v) -> v *= 2); 38 | map.computeIfPresent('D', (k, v) -> v *= 2); 39 | map.put('R', map.get('L') + map.get('R')); 40 | break; 41 | case 'R': 42 | map.computeIfPresent('U', (k, v) -> v *= 2); 43 | map.computeIfPresent('D', (k, v) -> v *= 2); 44 | map.put('L', map.get('L') + map.get('R')); 45 | break; 46 | } 47 | 48 | map.put(c, 1); 49 | } 50 | 51 | System.out.println(map.get(side.charAt(0))); 52 | } 53 | } -------------------------------------------------------------------------------- /Medium/ForestFire.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Send your available units to put out those fires! Watch out for water supplies! 5 | **/ 6 | class Player { 7 | 8 | static boolean[][] grid; 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | int L = in.nextInt(); // Size of forest map 13 | int water = in.nextInt(); // Total amount of water available 14 | 15 | // game loop 16 | while (true) { 17 | int N = in.nextInt(); // Amount of fires 18 | grid = new boolean[L][L]; 19 | for (int i = 0; i < N; i++) { 20 | int fireX = in.nextInt(); // X coordinate of fire 21 | int fireY = in.nextInt(); // Y coordinate of fire 22 | grid[fireY][fireX] = true; 23 | } 24 | 25 | Attack[] attack = new Attack[3]; 26 | attack[0] = new Attack(0, 0, 0); 27 | attack[1] = new Attack(0, 0, 0); 28 | attack[2] = new Attack(0, 0, 0); 29 | 30 | for (int i = 0 ; i < L; i++) { 31 | for (int j = 0 ; j < L; j++) { 32 | if (i + 2 < L && j + 2 < L) { 33 | // check for planes 34 | int nbFireIn3x3 = calcFireFrom(i, j, 3); 35 | if (nbFireIn3x3 > attack[0].nbFire) { 36 | attack[0] = new Attack(nbFireIn3x3, i, j); 37 | } 38 | } 39 | 40 | if (i + 1 < L && j + 1 < L) { 41 | int nbFireIn2x2 = calcFireFrom(i, j, 2); 42 | if (nbFireIn2x2 > attack[1].nbFire) { 43 | attack[1] = new Attack(nbFireIn2x2, i, j); 44 | } 45 | } 46 | 47 | if (grid[i][j]) { 48 | attack[2] = new Attack(1, i, j); 49 | } 50 | } 51 | } 52 | 53 | if (attack[0].nbFire > 5) { 54 | System.out.println("C " + attack[0].y + " " + attack[0].x); 55 | } else if (attack[1].nbFire > 1) { 56 | System.out.println("H " + attack[1].y + " " + attack[1].x); 57 | } else { 58 | System.out.println("J " + attack[2].y + " " + attack[2].x); 59 | } 60 | } 61 | } 62 | 63 | static int calcFireFrom(int i, int j, int nbArea) { 64 | int nbFire = 0; 65 | for (int k = 0; k < nbArea; k++) { 66 | for (int l = 0; l < nbArea; l++) { 67 | nbFire += grid[i + k][j + l] ? 1 : 0; 68 | } 69 | } 70 | return nbFire; 71 | } 72 | 73 | static class Attack { 74 | int nbFire; 75 | int x; 76 | int y; 77 | 78 | public Attack(int nbFire, int x, int y) { 79 | this.nbFire = nbFire; 80 | this.x = x; 81 | this.y = y; 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /Medium/GoroWantChocolate.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | static int[][] squared; 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int h = in.nextInt(); 14 | int w = in.nextInt(); 15 | 16 | squared = new int[h+1][w+1]; 17 | 18 | System.out.println(calc(h, w)); 19 | } 20 | 21 | static int calc(int h, int w) { 22 | if (h == w) { 23 | return 1; 24 | } 25 | 26 | if (squared[h][w] != 0) { 27 | return squared[h][w]; 28 | } 29 | 30 | int horizontalSquare = Integer.MAX_VALUE; 31 | int verticalSquare = Integer.MAX_VALUE; 32 | 33 | for (int i = 1; i <= h / 2 ; i++) { 34 | horizontalSquare = Math.min(calc(i, w) + calc(h - i, w), horizontalSquare); 35 | } 36 | 37 | for (int i = 1; i <= w / 2; i++) { 38 | horizontalSquare = Math.min(calc(h, i) + calc(h, w - i), horizontalSquare); 39 | } 40 | 41 | squared[h][w] = Math.min(horizontalSquare, verticalSquare); 42 | 43 | return squared[h][w]; 44 | } 45 | } -------------------------------------------------------------------------------- /Medium/GravityCentrifugeTuning.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Auto-generated code below aims at helping you parse 8 | * the standard input according to the problem statement. 9 | **/ 10 | class Solution { 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | String N = in.nextLine(); 15 | 16 | BigInteger n = new BigInteger(N); 17 | 18 | StringBuilder sb = new StringBuilder(); 19 | 20 | List fibs = fibNumbers(n); 21 | 22 | for (int i = fibs.size() - 1; i >= 0; i--) { 23 | BigInteger fib = fibs.get(i); 24 | sb.append(fib.compareTo(n) <= 0 ? "1" : "0"); 25 | if (fib.compareTo(n) <= 0) { 26 | n = n.subtract(fib); 27 | } 28 | } 29 | 30 | System.out.println(new BigInteger(sb.toString(), 2).toString(8)); 31 | } 32 | 33 | private static List fibNumbers(BigInteger n) { 34 | List fibs = new ArrayList<>(); 35 | fibs.add(BigInteger.ONE); 36 | BigInteger nextFib = BigInteger.TWO; 37 | while (n.compareTo(nextFib) >= 0) { 38 | fibs.add(nextFib); 39 | nextFib = nextFib.add(fibs.get(fibs.size() - 2)); 40 | } 41 | return fibs; 42 | } 43 | } -------------------------------------------------------------------------------- /Medium/HorseHyperracingHyperduals.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int N = in.nextInt(); 12 | int M = in.nextInt(); 13 | long X = in.nextLong(); 14 | 15 | List horses = new ArrayList<>(N + M); 16 | for (int i = 0; i < N; i++) { 17 | horses.add(new Horse(in.nextLong(), in.nextLong())); 18 | } 19 | 20 | for (int i = 0; i < M; i++) { 21 | long E = (1103515245L * X + 12345) % 2147483648L; 22 | horses.add(new Horse(X, E)); 23 | X = (1103515245L * E + 12345) % 2147483648L; 24 | } 25 | 26 | horses.sort(Comparator.comparingDouble(a -> a.v)); 27 | 28 | long delta = horses.get(0).deltaWith(horses.get(1)); 29 | for (int i = 0; i < horses.size() - 1; i++) { 30 | Horse ih = horses.get(i); 31 | 32 | for (int j = i + 1; j < horses.size(); j++) { 33 | Horse jh = horses.get(j); 34 | 35 | if (jh.v - ih.v >= delta) { 36 | break; 37 | } 38 | delta = Math.min(delta, jh.deltaWith(ih)); 39 | } 40 | } 41 | System.out.println(delta); 42 | } 43 | } 44 | 45 | public class Horse { 46 | long v; 47 | long e; 48 | 49 | Horse(long v, long e) { 50 | this.v = v; 51 | this.e = e; 52 | } 53 | 54 | long deltaWith(Horse h) { 55 | return Math.abs(h.v - this.v) + Math.abs(h.e - this.e); 56 | } 57 | } -------------------------------------------------------------------------------- /Medium/JumpingFrogs.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String args[]) { 10 | Scanner in = new Scanner(System.in); 11 | 12 | Frog[] frogs = new Frog[3]; 13 | 14 | for (int i = 0; i < 3; i++) { 15 | frogs[i] = new Frog(in.nextInt(), in.nextInt(), in.nextInt()); 16 | } 17 | 18 | if (canMeet(frogs[0], frogs[1]) && canMeet(frogs[1], frogs[2]) && canMeet(frogs[0], frogs[2])) { 19 | System.out.println("Possible"); 20 | } else { 21 | System.out.println("Impossible"); 22 | } 23 | } 24 | 25 | static boolean canMeet(Frog f1, Frog f2) { 26 | int pgcd = pgcd(f1.k, f2.k); 27 | return Math.abs(f1.x - f2.x) % pgcd == 0 && Math.abs(f1.y - f2.y) % pgcd == 0; 28 | } 29 | 30 | static int pgcd(int a, int b) { 31 | a = Math.abs(a); 32 | b = Math.abs(b); 33 | while (a!=b) { 34 | if (a > b) { 35 | a = a - b; 36 | } else { 37 | b = b - a; 38 | } 39 | } 40 | return a ; 41 | } 42 | } 43 | 44 | class Frog { 45 | int x; 46 | int y; 47 | int k; 48 | 49 | public Frog(int x, int y, int k) { 50 | this.x = x; 51 | this.y = y; 52 | this.k = k; 53 | } 54 | } -------------------------------------------------------------------------------- /Medium/LengthOfSyracuseConjectureSequence.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | static Map cycleMap = new HashMap<>(); 12 | 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | int N = in.nextInt(); 16 | for (int i = 0; i < N; i++) { 17 | int A = in.nextInt(); 18 | int B = in.nextInt(); 19 | 20 | int max = Integer.MIN_VALUE; 21 | int nbMax = A; 22 | for (int j = A; j <= B; j++) { 23 | int cycle = syracuseCycle(j); 24 | if (cycle > max) { 25 | max = cycle; 26 | nbMax = j; 27 | } 28 | } 29 | 30 | System.out.println(nbMax + " " + max); 31 | } 32 | } 33 | 34 | static int syracuseCycle(int number) { 35 | if (cycleMap.containsKey(number)) { 36 | return cycleMap.get(number); 37 | } 38 | 39 | int c = number; 40 | int res = 1; 41 | while (c != 1) { 42 | c = c % 2 == 0 ? c / 2 : 3 * c + 1; 43 | 44 | if (cycleMap.containsKey(c)) { 45 | cycleMap.put(number, cycleMap.get(c) + res); 46 | return cycleMap.get(number); 47 | } 48 | 49 | res++; 50 | } 51 | 52 | cycleMap.put(number, res); 53 | return res; 54 | } 55 | } -------------------------------------------------------------------------------- /Medium/MayanCalculation.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int L = in.nextInt(); 12 | int H = in.nextInt(); 13 | 14 | String[][] c = new String[H][L]; 15 | for (int i = 0; i < H; i++) { 16 | c[i] = in.next().split("(?<=\\G.{" + L + "})"); 17 | } 18 | 19 | long numA = getNumberFromInput(in, H, c); 20 | long numB = getNumberFromInput(in, H, c); 21 | 22 | long result = 0; 23 | switch (in.next()) { 24 | case "+": 25 | result = numA + numB; 26 | break; 27 | case "-": 28 | result = numA - numB; 29 | break; 30 | case "*": 31 | result = numA * numB; 32 | break; 33 | case "/": 34 | result = numA / numB; 35 | break; 36 | } 37 | 38 | writeNumber(result, c); 39 | } 40 | 41 | private static void writeNumber(long result, String[][] c) { 42 | Deque queue = new ArrayDeque<>(); 43 | 44 | queue.add(result); 45 | while (result >= 20) { 46 | queue.poll(); 47 | queue.push(result % 20); 48 | queue.push(result / 20); 49 | result /= 20; 50 | } 51 | 52 | while (!queue.isEmpty()) { 53 | int index = Math.toIntExact(queue.poll()); 54 | for (String[] strings : c) { 55 | System.out.println(strings[index]); 56 | } 57 | } 58 | } 59 | 60 | private static long getNumberFromInput(Scanner in, int H, String[][] c) { 61 | long num = 0; 62 | int S = in.nextInt(); 63 | int power = (S / H) - 1; 64 | 65 | List ints = new ArrayList<>(); 66 | for (int i = 0; i < S; i++) { 67 | 68 | ints = findIndexes(c[i % H], in.next(), ints); 69 | 70 | if ((i + 1) % H == 0) { 71 | num += ints.get(0) * Math.pow(20, power--); 72 | ints.clear(); 73 | } 74 | } 75 | 76 | return num; 77 | } 78 | 79 | private static List findIndexes(String[] origin, String toFind, List currentIndexes) { 80 | List indexes = new ArrayList<>(); 81 | for (int i = 0; i < origin.length; i++) { 82 | if (origin[i].equals(toFind) && (currentIndexes.isEmpty() || currentIndexes.contains(i))) { 83 | indexes.add(i); 84 | } 85 | } 86 | 87 | return indexes; 88 | } 89 | } -------------------------------------------------------------------------------- /Medium/MicroAssembly.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.stream.Collectors; 3 | 4 | /** 5 | * Auto-generated code below aims at helping you parse 6 | * the standard input according to the problem statement. 7 | **/ 8 | class Solution { 9 | 10 | public static void main(String[] args) { 11 | Scanner in = new Scanner(System.in); 12 | 13 | Map register = new HashMap<>(); 14 | register.put("a", in.nextInt()); 15 | register.put("b", in.nextInt()); 16 | register.put("c", in.nextInt()); 17 | register.put("d", in.nextInt()); 18 | 19 | int n = in.nextInt(); 20 | in.nextLine(); 21 | 22 | List instructions = new ArrayList<>(); 23 | for (int i = 0; i < n; i++) { 24 | instructions.add(in.nextLine().split(" ")); 25 | } 26 | 27 | for (int i = 0; i < instructions.size(); i++) { 28 | String[] s = instructions.get(i); 29 | 30 | int i2 = (register.containsKey(s[2]) ? register.get(s[2]) : Integer.parseInt(s[2])); 31 | int i3 = s.length == 4 ? (register.containsKey(s[3]) ? register.get(s[3]) : Integer.parseInt(s[3])) : 0; 32 | 33 | switch (s[0]) { 34 | case "MOV": 35 | register.put(s[1], i2); 36 | break; 37 | case "ADD": 38 | register.put(s[1], i2 + i3); 39 | break; 40 | case "SUB": 41 | register.put(s[1], i2 - i3); 42 | break; 43 | case "JNE": 44 | if (i2 != i3) { 45 | i = Integer.parseInt(s[1]) - 1; 46 | } 47 | break; 48 | } 49 | } 50 | 51 | System.out.println(register.values().stream().map(i -> Integer.toString(i)).collect(Collectors.joining(" "))); 52 | } 53 | } -------------------------------------------------------------------------------- /Medium/NetworkCabling.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | import java.math.*; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int N = in.nextInt(); 14 | 15 | int[] ys = new int[N]; 16 | 17 | int minX = Integer.MAX_VALUE; 18 | int maxX = Integer.MIN_VALUE; 19 | for (int i = 0; i < N; i++) { 20 | int x = in.nextInt(); 21 | int y = in.nextInt(); 22 | ys[i] = y; 23 | 24 | minX = Math.min(minX, x); 25 | maxX = Math.max(maxX, x); 26 | } 27 | 28 | Arrays.sort(ys); 29 | 30 | int medianY = ys[ys.length / 2]; 31 | 32 | long total = Math.abs(maxX - minX); 33 | for (int i : ys) { 34 | total += Math.abs(i - medianY); 35 | } 36 | 37 | System.out.println(total); 38 | } 39 | } -------------------------------------------------------------------------------- /Medium/NumberOfLettersInANumberBinary.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | long start = in.nextLong(); 12 | long n = in.nextLong(); 13 | 14 | for (int i = 0; i < n; i++) { 15 | String s = Long.toBinaryString(start); 16 | long end = s.chars().filter(ch -> ch == '1').count() * 3 17 | + s.chars().filter(ch -> ch == '0').count() * 4; 18 | 19 | if (start == end) { 20 | break; 21 | } 22 | 23 | start = end; 24 | } 25 | 26 | System.out.println(start); 27 | } 28 | } -------------------------------------------------------------------------------- /Medium/RegularPolygons.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | 5 | static int[] fermals = {1, 6 | 3, 7 | 5, 8 | 15, 9 | 17, 10 | 51, 11 | 85, 12 | 255, 13 | 257, 14 | 771, 15 | 1285, 16 | 3855, 17 | 4369, 18 | 13107, 19 | 21845, 20 | 65535, 21 | 65537, 22 | 196611, 23 | 327685, 24 | 983055, 25 | 1114129, 26 | 3342387, 27 | 5570645, 28 | 16711935, 29 | 16843009, 30 | 50529027, 31 | 84215045, 32 | 252645135, 33 | 286331153, 34 | 858993459, 35 | 1431655765}; 36 | 37 | public static void main(String[] args) { 38 | Scanner in = new Scanner(System.in); 39 | int a = in.nextInt(); 40 | int b = in.nextInt(); 41 | 42 | int nbSolution = 0; 43 | 44 | int powerOfTwo = 1; 45 | while(powerOfTwo <= b && powerOfTwo > 0) { 46 | for (int j : fermals) { 47 | if (powerOfTwo * j < 0) { 48 | break; 49 | } 50 | if (powerOfTwo * j >= a && powerOfTwo * j <= b) { 51 | nbSolution++; 52 | } 53 | } 54 | powerOfTwo *= 2; 55 | } 56 | 57 | System.out.println(nbSolution); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Medium/RoadTrip.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Comparator; 3 | import java.util.List; 4 | import java.util.Scanner; 5 | import java.util.stream.Collectors; 6 | 7 | /** 8 | * Auto-generated code below aims at helping you parse 9 | * the standard input according to the problem statement. 10 | **/ 11 | class Solution { 12 | 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | int N = in.nextInt(); 16 | double C = (double) in.nextInt(); 17 | int P = in.nextInt(); 18 | 19 | List friends = new ArrayList<>(); 20 | for (int i = 0; i < N; i++) { 21 | int budget = in.nextInt(); 22 | int joy = in.nextInt(); 23 | friends.add(new Friend((double) budget, joy)); 24 | } 25 | 26 | int maxJoy = 0; 27 | for (int i = 1; i <= N; i++) { 28 | double perPerson = (C + P * i) / i; 29 | 30 | List tmpList = friends.stream() 31 | .filter(f -> f.budget >= perPerson) 32 | .sorted(Comparator.comparingInt(Friend::getJoy).reversed()) 33 | .collect(Collectors.toList()); 34 | 35 | int tmpJoy = 0; 36 | if (tmpList.size() >= i - 1) { 37 | for (int j = 0; j < i - 1; j++) { 38 | tmpJoy += tmpList.get(j).getJoy(); 39 | } 40 | } 41 | 42 | maxJoy = Math.max(tmpJoy, maxJoy); 43 | } 44 | 45 | System.out.println(maxJoy); 46 | } 47 | } 48 | 49 | class Friend { 50 | double budget; 51 | int joy; 52 | 53 | public Friend(double budget, int joy) { 54 | this.budget = budget; 55 | this.joy = joy; 56 | } 57 | 58 | int getJoy() { 59 | return joy; 60 | } 61 | } -------------------------------------------------------------------------------- /Medium/RobberyOptimisation.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | private static long[] houses; 10 | private static long[] sumForIndexes; 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int N = in.nextInt(); 15 | 16 | houses = new long[N]; 17 | for (int i = 0; i < N; i++) { 18 | houses[i] = in.nextLong(); 19 | } 20 | 21 | sumForIndexes = new long[N]; 22 | 23 | // max start from index 0 or index 1 24 | long res = Math.max(calcMaxFromIndex(0), calcMaxFromIndex(1)); 25 | System.out.println(res); 26 | } 27 | 28 | static long calcMaxFromIndex(int index) { 29 | if (index >= houses.length) { 30 | return 0; 31 | } 32 | 33 | if (sumForIndexes[index] != 0) { 34 | return sumForIndexes[index]; 35 | } 36 | 37 | long right2 = Math.max(calcMaxFromIndex(index + 2), calcMaxFromIndex(index + 3)); 38 | 39 | // compare 2 houses vs 3 houses next 40 | sumForIndexes[index] = (houses[index] > 0 ? houses[index] : 0) + (right2 > 0 ? right2 : 0); 41 | 42 | return sumForIndexes[index]; 43 | } 44 | } -------------------------------------------------------------------------------- /Medium/Rotatetris.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Auto-generated code below aims at helping you parse 8 | * the standard input according to the problem statement. 9 | **/ 10 | class Solution { 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int H = in.nextInt(); 15 | in.nextInt(); 16 | 17 | String[] box = new String[H]; 18 | int holes = 0; 19 | for (int i = 0; i < H; i++) { 20 | box[i] = in.next(); 21 | holes += box[i].length() - box[i].replace(".", "").length(); 22 | } 23 | int H2 = in.nextInt(); 24 | 25 | in.nextInt(); 26 | String[] piece = new String[H2]; 27 | int block = 0; 28 | for (int i = 0; i < H2; i++) { 29 | piece[i] = in.next(); 30 | block += piece[i].length() - piece[i].replace("#", "").length(); 31 | } 32 | 33 | if (block != holes) { 34 | System.out.println("HOLE"); 35 | return; 36 | } 37 | 38 | piece = updatePiece(piece); // remove all the '.' that serves no purpose 39 | 40 | System.out.println(solveForEachRotation(box, piece) ? "FULL" : "HOLE"); 41 | } 42 | 43 | private static String[] updatePiece(String[] piece) { 44 | String[] tmp = piece; 45 | for (int i = 0; i < 8; i++) { 46 | List tmpList = new ArrayList<>(Arrays.asList(tmp)); 47 | if (!tmpList.get(0).contains("#")) { 48 | tmpList.remove(0); 49 | tmp = tmpList.toArray(new String[0]); 50 | } 51 | tmp = rotateClockWise(tmp); 52 | } 53 | return tmp; 54 | } 55 | 56 | private static boolean solveForEachRotation(String[] boxes, String[] piece) { 57 | String[] p = piece; 58 | for (int turn = 0; turn < 4; turn++) { 59 | if (solve(boxes, p)) { 60 | return true; 61 | } 62 | 63 | p = rotateClockWise(p); 64 | } 65 | 66 | return false; 67 | } 68 | 69 | private static boolean solve(String[] boxes, String[] p) { 70 | for (int i = 0; i <= boxes.length - p.length; i++) { 71 | for (int j = 0; j <= boxes[0].length() - p[0].length(); j++) { 72 | 73 | String[] tmpBox = new String[boxes.length]; 74 | System.arraycopy(boxes, 0, tmpBox, 0, boxes.length); 75 | 76 | fill(tmpBox, p, i, j); 77 | 78 | if (check(tmpBox)) { 79 | return true; 80 | } 81 | } 82 | } 83 | return false; 84 | } 85 | 86 | private static void fill(String[] boxes, String[] pieces, int a, int b) { 87 | for (int i = 0; i < pieces.length; i++) { 88 | StringBuilder line = new StringBuilder(boxes[i + a]); 89 | String piece = pieces[i]; 90 | for (int j = 0; j < pieces[0].length(); j++) { 91 | if (piece.charAt(j) == '#') { 92 | if (line.charAt(j + b) == '#') { 93 | line.setCharAt(j + b, '.'); 94 | } else { 95 | line.setCharAt(j + b, piece.charAt(j)); 96 | } 97 | } 98 | } 99 | boxes[i + a] = line.toString(); 100 | } 101 | } 102 | 103 | private static boolean check(String[] boxes) { 104 | for (String box : boxes) { 105 | if (box.contains(".")) { 106 | return false; 107 | } 108 | } 109 | return true; 110 | } 111 | 112 | private static String[] rotateClockWise(String[] array) { 113 | int sizeW = array.length; 114 | int sizeH = array[0].length(); 115 | String[] ret = new String[sizeH]; 116 | 117 | for (int i = 0; i < sizeH; ++i) { 118 | StringBuilder build = new StringBuilder(); 119 | for (int j = 0; j < sizeW; ++j) { 120 | build.append(array[sizeW - j - 1].charAt(i)); 121 | } 122 | ret[i] = build.toString(); 123 | } 124 | 125 | return ret; 126 | } 127 | } -------------------------------------------------------------------------------- /Medium/Scrabble.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | 12 | Map charMap = new HashMap<>() { 13 | { 14 | put('a', 1); 15 | put('b', 3); 16 | put('c', 3); 17 | put('d', 2); 18 | put('e', 1); 19 | put('f', 4); 20 | put('g', 2); 21 | put('h', 4); 22 | put('i', 1); 23 | put('j', 8); 24 | put('k', 5); 25 | put('l', 1); 26 | put('m', 3); 27 | put('n', 1); 28 | put('o', 1); 29 | put('p', 3); 30 | put('q', 10); 31 | put('r', 1); 32 | put('s', 1); 33 | put('t', 1); 34 | put('u', 1); 35 | put('v', 4); 36 | put('w', 4); 37 | put('x', 8); 38 | put('y', 4); 39 | put('z', 10); 40 | } 41 | }; 42 | 43 | 44 | int N = in.nextInt(); 45 | in.nextLine(); 46 | 47 | List list = new ArrayList<>(); 48 | for (int i = 0; i < N; i++) { 49 | list.add(in.nextLine()); 50 | } 51 | 52 | String letters = in.nextLine(); 53 | removeIncorrectWord(list, letters); 54 | 55 | String word = null; 56 | int max = 0; 57 | for (String line : list) { 58 | char[] cs = line.toCharArray(); 59 | int tmp = 0; 60 | for (char c : cs) { 61 | tmp += charMap.get(c); 62 | } 63 | if (tmp > max) { 64 | word = line; 65 | max = tmp; 66 | } 67 | } 68 | 69 | System.out.println(word == null ? "invalid word" : word); 70 | } 71 | 72 | private static void removeIncorrectWord(List list, String letters) { 73 | Iterator iter = list.iterator(); 74 | while (iter.hasNext()) { 75 | String tmp = letters; 76 | 77 | boolean remove = false; 78 | for (char c : iter.next().toCharArray()) { 79 | if (tmp.indexOf(c) >= 0) { 80 | tmp = tmp.replaceFirst(Character.toString(c), ""); 81 | } else { 82 | remove = true; 83 | } 84 | } 85 | 86 | if (remove) { 87 | iter.remove(); 88 | } 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /Medium/ShadowsOfTheKnightEpisode1.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Player { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int W = in.nextInt(); // width of the building. 12 | int H = in.nextInt(); // height of the building. 13 | int N = in.nextInt(); // maximum number of turns before game over. 14 | int X0 = in.nextInt(); 15 | int Y0 = in.nextInt(); 16 | 17 | int minX = 0; 18 | int minY = 0; 19 | int maxX = W - 1; 20 | int maxY = H - 1; 21 | // game loop 22 | while (true) { 23 | String bombDir = in.next(); 24 | if (bombDir.contains("U")) { 25 | maxY = Y0 - 1; 26 | } else if (bombDir.contains("D")) { 27 | minY = Y0 + 1; 28 | } 29 | if (bombDir.contains("L")) { 30 | maxX = X0 - 1; 31 | } else if (bombDir.contains("R")) { 32 | maxX = X0 + 1; 33 | } 34 | 35 | X0 = (minX - maxX) / 2; 36 | Y0 = (minY - maxY) / 2; 37 | 38 | System.out.println(X0 + " " + Y0); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Medium/ShortAccountsMakeLongFriends.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | // first line = initial and 5 others are possible combinations 10 | static int[][] results = new int[6][6]; 11 | static int bestDistance = Integer.MAX_VALUE; 12 | static int solution = 6; // if we find a solution it's max 5 combination 13 | static int finalValue = 0; 14 | 15 | public static void main(String[] args) { 16 | Scanner in = new Scanner(System.in); 17 | finalValue = in.nextInt(); 18 | 19 | for (int i = 0; i < 6; i++) { 20 | int v = in.nextInt(); 21 | results[0][i] = v; 22 | } 23 | 24 | calculate(0); 25 | 26 | System.out.println(bestDistance == 0 ? "POSSIBLE" : "IMPOSSIBLE"); 27 | System.out.println(bestDistance == 0 ? solution : bestDistance); 28 | } 29 | 30 | private static void calculate(int lvl) { 31 | //System.err.println("lvl : " + lvl + " result : " + results[lvl][0]); 32 | 33 | int tmpDistance = Math.abs(finalValue - results[lvl][0]); 34 | if (tmpDistance <= bestDistance) { 35 | bestDistance = tmpDistance; 36 | 37 | if (bestDistance == 0) { 38 | solution = Math.min(solution, lvl); 39 | } 40 | } 41 | 42 | if (lvl == 5) { 43 | return; 44 | } 45 | 46 | for (int i = 0; i < 6 - lvl - 1; i++) { 47 | for (int j = i + 1; j < 6 - lvl; j++) { 48 | int a = results[lvl][i]; 49 | int b = results[lvl][j]; 50 | 51 | int l = 1; 52 | for (int k = 0; k < 6 - lvl; k++) { 53 | if (k != i && k != j) { 54 | results[lvl + 1][l++] = results[lvl][k]; 55 | } 56 | } 57 | 58 | results[lvl + 1][0] = a + b; 59 | calculate(lvl + 1); 60 | 61 | results[lvl + 1][0] = a * b; 62 | calculate(lvl + 1); 63 | 64 | if (a != b) { 65 | results[lvl + 1][0] = Math.abs(a - b); 66 | calculate(lvl + 1); 67 | } 68 | 69 | if (a % b == 0) { 70 | results[lvl + 1][0] = a / b; 71 | calculate(lvl + 1); 72 | } else if (b % a == 0) { 73 | results[lvl + 1][0] = b / a; 74 | calculate(lvl + 1); 75 | } 76 | } 77 | } 78 | } 79 | } -------------------------------------------------------------------------------- /Medium/SkynetRevolutionEpisode1.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Player { 8 | 9 | private static boolean[][] links; 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | int N = in.nextInt(); // the total number of nodes in the level, including the gateways 14 | 15 | links = new boolean[N][N]; 16 | 17 | int L = in.nextInt(); // the number of links 18 | int E = in.nextInt(); // the number of exit gateways 19 | for (int i = 0; i < L; i++) { 20 | int N1 = in.nextInt(); // N1 and N2 defines a link between these nodes 21 | int N2 = in.nextInt(); 22 | links[N1][N2] = true; 23 | links[N2][N1] = true; 24 | } 25 | 26 | int[] gateways = new int[E]; 27 | for (int i = 0; i < E; i++) { 28 | int EI = in.nextInt(); // the index of a gateway node 29 | gateways[i] = EI; 30 | System.err.print(EI + " "); 31 | } 32 | 33 | // game loop 34 | while (true) { 35 | int SI = in.nextInt(); 36 | 37 | String result = ""; 38 | int maxDepth = N + 1; 39 | for (int gateway : gateways) { 40 | NodeAndDepth newNode = findGateway(SI, gateway, false); 41 | if (newNode.node != -1 && newNode.depth < maxDepth) { 42 | maxDepth = newNode.depth; 43 | result = newNode.node + " " + gateway; 44 | } 45 | 46 | newNode = findGateway(SI, gateway, true); 47 | if (newNode.node != -1 && newNode.depth < maxDepth) { 48 | maxDepth = newNode.depth; 49 | result = newNode.node + " " + gateway; 50 | } 51 | } 52 | 53 | System.out.println(result); 54 | } 55 | } 56 | 57 | private static NodeAndDepth findGateway(int root, int gateaway, boolean reverse) { 58 | Set visited = new LinkedHashSet<>(); 59 | Stack stack = new Stack<>(); 60 | stack.push(root); 61 | 62 | int nbJump = 0; 63 | while (!stack.isEmpty()) { 64 | int node = stack.pop(); 65 | if (!visited.contains(node)) { 66 | visited.add(node); 67 | for (int i = 0; i < links.length; i++) { 68 | if ((!reverse && links[node][i]) || (reverse && links[i][node])) { 69 | if (i == gateaway) { 70 | return new NodeAndDepth(node, nbJump); 71 | } 72 | stack.push(i); 73 | } 74 | } 75 | } 76 | nbJump++; 77 | } 78 | return new NodeAndDepth(0, 0); 79 | } 80 | } 81 | 82 | class NodeAndDepth { 83 | int node; 84 | int depth; 85 | 86 | NodeAndDepth(int node, int depth) { 87 | this.node = node; 88 | this.depth = depth; 89 | } 90 | } -------------------------------------------------------------------------------- /Medium/SnakeEncoding.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int N = in.nextInt(); 12 | int X = in.nextInt(); 13 | in.nextLine(); 14 | 15 | char[][] c = new char[N][N]; 16 | for (int i = 0; i < N; i++) { 17 | c[i] = in.nextLine().toCharArray(); 18 | } 19 | 20 | for (int i = 0; i < X; i++) { 21 | int y = N % 2 == 0 ? N - 1 : 0; 22 | int x = N - 1; 23 | int dir = x % 2 == 0 ? 1 : -1; 24 | 25 | char end = c[y][x]; 26 | 27 | while(x != 0 || y != N - 1) { 28 | c[y][x] = c[y + dir][x]; 29 | 30 | y += dir; 31 | 32 | if (y % (N - 1) == 0 && x > 0) { 33 | c[y][x] = c[y][--x]; 34 | dir *= -1; 35 | } 36 | } 37 | 38 | c[y][x] = end; 39 | } 40 | 41 | for (int i = 0; i < N; i++) { 42 | System.out.println(new String(c[i])); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Medium/StallTilt.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | static List drivers; 10 | static int[] bends; 11 | static double g = 9.81; 12 | static double angle = 60d; 13 | 14 | 15 | public static void main(String[] args) { 16 | Scanner in = new Scanner(System.in); 17 | int n = in.nextInt(); 18 | int v = in.nextInt(); 19 | 20 | drivers = new ArrayList<>(n); 21 | bends = new int[v]; 22 | 23 | for (int i = 0; i < n; i++) { 24 | drivers.add(new Driver((char)('a' + i), in.nextInt())); 25 | } 26 | 27 | for (int i = 0; i < v; i++) { 28 | bends[i] = in.nextInt(); 29 | } 30 | 31 | drivers.sort(Comparator.comparingInt(Driver::getSpeed).reversed()); 32 | 33 | int max = calcOptimalSpeed(); 34 | List res = calcResult(); 35 | 36 | System.out.println(max); 37 | System.out.println("y"); 38 | res.forEach(d -> System.out.println(d.c)); 39 | } 40 | 41 | static List calcResult() { 42 | List result = new ArrayList<>(); 43 | for (int i : bends) { 44 | 45 | int countFall = 0; 46 | 47 | Iterator iter = drivers.iterator(); 48 | while (iter.hasNext()) { 49 | Driver d = iter.next(); 50 | 51 | if (Math.toDegrees(Math.atan(d.getSpeed() * d.getSpeed() / (i * g))) > angle) { 52 | result.add(countFall++, d); 53 | iter.remove(); 54 | } 55 | } 56 | } 57 | 58 | result.addAll(0, drivers); 59 | return result; 60 | } 61 | 62 | static int calcOptimalSpeed() { 63 | int min = Integer.MAX_VALUE; 64 | for (int i : bends) { 65 | min = Math.min(min, (int)(Math.sqrt(Math.tan(Math.toRadians(angle)) * i * g))); 66 | } 67 | return min; 68 | } 69 | } 70 | 71 | class Driver { 72 | char c; 73 | int speed; 74 | 75 | public Driver(char c, int speed) { 76 | this.c = c; 77 | this.speed = speed; 78 | } 79 | 80 | int getSpeed() { 81 | return speed; 82 | } 83 | } -------------------------------------------------------------------------------- /Medium/StockExchangeLosses.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int n = in.nextInt(); 12 | 13 | int high = 0; 14 | int res = 0; 15 | 16 | for (int i = 0; i < n; i++) { 17 | int v = in.nextInt(); 18 | 19 | if (v > high) { 20 | high = v; 21 | } else if ((v - high) < res) { 22 | res = v - high; 23 | } 24 | } 25 | 26 | System.out.println(res); 27 | } 28 | } -------------------------------------------------------------------------------- /Medium/SudokuSolver.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | static int[][] board; 10 | static boolean[] numbers = new boolean[9]; 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | board = new int[9][9]; 15 | for (int i = 0; i < 9; i++) { 16 | String[] line = in.nextLine().split(""); 17 | for (int j = 0; j < 9; j++) { 18 | board[i][j] = Integer.parseInt(line[j]); 19 | } 20 | } 21 | 22 | solve(); 23 | 24 | for (int i = 0; i < 9; i++) { 25 | for (int j = 0; j < 9; j++) { 26 | System.out.print(board[i][j]); 27 | } 28 | System.out.println(); 29 | } 30 | } 31 | 32 | private static boolean solve() { 33 | for (int i = 0; i < 9; i++) { 34 | for (int j = 0; j < 9; j++) { 35 | if (board[i][j] == 0) { 36 | for (int k = 1; k < 10; k++) { 37 | board[i][j] = k; 38 | if (isValid(i, j) && solve()) { 39 | return true; 40 | } 41 | board[i][j] = 0; 42 | } 43 | return false; 44 | } 45 | } 46 | } 47 | 48 | return true; 49 | } 50 | 51 | private static boolean isValid(int y, int x) { 52 | return isRowValid(y) && isColValid(x) && isSquareValid(y, x); 53 | } 54 | 55 | private static boolean isRowValid(int y) { 56 | numbers = new boolean[9]; 57 | for (int j = 0; j < 9; j++) { 58 | if (invalidNumbers(y, j)) { 59 | return false; 60 | } 61 | } 62 | 63 | return true; 64 | } 65 | 66 | private static boolean isColValid(int x) { 67 | numbers = new boolean[9]; 68 | for (int i = 0; i < 9; i++) { 69 | if (invalidNumbers(i, x)) { 70 | return false; 71 | } 72 | } 73 | 74 | return true; 75 | } 76 | 77 | private static boolean isSquareValid(int y, int x) { 78 | numbers = new boolean[9]; 79 | 80 | int startX = (x / 3) * 3; 81 | int endX = startX + 3; 82 | 83 | int startY = (y / 3) * 3; 84 | int endY = startY + 3; 85 | 86 | for (int i = startY; i < endY; i++) { 87 | for (int j = startX; j < endX; j++) { 88 | if (invalidNumbers(i, j)) { 89 | return false; 90 | } 91 | } 92 | } 93 | 94 | return true; 95 | } 96 | 97 | private static boolean invalidNumbers(int y, int x) { 98 | if (board[y][x] != 0) { 99 | if (!numbers[board[y][x] - 1]) { 100 | numbers[board[y][x] - 1] = true; 101 | } else { 102 | return true; 103 | } 104 | } 105 | return false; 106 | } 107 | } -------------------------------------------------------------------------------- /Medium/TelephoneNumbers.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int N = in.nextInt(); 12 | Node root = new Node(); 13 | 14 | for (int i = 0; i < N; i++) { 15 | root.add(in.next().chars().mapToObj(c -> (char)c - '0').toArray(Integer[]::new), 0); 16 | } 17 | 18 | System.out.println(root.countNode()); 19 | } 20 | 21 | static class Node { 22 | Map children = new HashMap<>(); 23 | 24 | public void add(Integer[] c, int index) { 25 | children.putIfAbsent(c[index], new Node()); 26 | if (index < c.length - 1) { 27 | children.get(c[index]).add(c, index+1); 28 | } 29 | } 30 | 31 | int countNode() { 32 | int val = children.size(); 33 | for (Node child : children.values()) { 34 | val += child.countNode(); 35 | } 36 | return val; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Medium/TheGift.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | int N = in.nextInt(); 12 | int C = in.nextInt(); 13 | 14 | int total = 0; 15 | PriorityQueue budgets = new PriorityQueue<>(); 16 | for (int i = 0; i < N; i++) { 17 | int B = in.nextInt(); 18 | total += B; 19 | budgets.add(B); 20 | } 21 | 22 | if (total < C) { 23 | System.out.println("IMPOSSIBLE"); 24 | return; 25 | } 26 | 27 | while(budgets.size() > 0) { 28 | int mean = C / budgets.size(); 29 | int current = Math.min(budgets.poll(), mean); 30 | System.out.println(current); 31 | C -= current; 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /Medium/TheGrandFestival1.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | static int R; 10 | static int[] prizes; 11 | static int[][] sumForIndexes; 12 | 13 | public static void main(String[] args) { 14 | Scanner in = new Scanner(System.in); 15 | int N = in.nextInt(); 16 | R = in.nextInt(); 17 | 18 | sumForIndexes = new int[N][R]; 19 | 20 | prizes = new int[N]; 21 | for (int i = 0; i < N; i++) { 22 | prizes[i] = in.nextInt(); 23 | } 24 | 25 | // max start from index 0 or index 1 26 | int res = Math.max(calcMaxFromIndex(0, R), calcMaxFromIndex(1, R)); 27 | System.out.println(res); 28 | } 29 | 30 | static int calcMaxFromIndex(int index, int nbDays) { 31 | nbDays--; 32 | 33 | if (index >= prizes.length) { 34 | return 0; 35 | } 36 | 37 | if (sumForIndexes[index][nbDays] != 0) { 38 | return sumForIndexes[index][nbDays]; 39 | } 40 | 41 | if (nbDays > 0) { 42 | // compare sum of remaining days vs a rest day and a sum of R days 43 | sumForIndexes[index][nbDays] = prizes[index] + Math.max(calcMaxFromIndex(index + 1, nbDays), calcMaxFromIndex(index + 2, R)); 44 | } else { 45 | // compare a sum of R days 1 days in the future vs 2 days in the future 46 | sumForIndexes[index][nbDays] = prizes[index] + Math.max(calcMaxFromIndex(index + 2, R), calcMaxFromIndex(index + 3, R)); 47 | } 48 | 49 | return sumForIndexes[index][nbDays]; 50 | } 51 | } -------------------------------------------------------------------------------- /Medium/TheLastCrusadeEpisode1.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Player { 10 | 11 | static String[][] pieces = { // Down, Left, Right 12 | // Top, Left, Right 13 | {"X", "X", "X"}, //0 14 | {"D", "D", "D"}, //1 15 | {"X", "R", "L"}, //2 16 | {"D", "X", "X"}, //3 17 | {"L", "X", "D"}, //4 18 | {"R", "D", "X"}, //5 19 | {"X", "R", "L"}, //6 20 | {"D", "X", "D"}, //7 21 | {"X", "D", "D"}, //8 22 | {"D", "D", "X"}, //9 23 | {"L", "X", "X"}, //10 24 | {"R", "X", "X"}, //11 25 | {"X", "X", "D"}, //12 26 | {"X", "D", "X"}, //13 27 | }; 28 | 29 | public static void main(String[] args) { 30 | Scanner in = new Scanner(System.in); 31 | int W = in.nextInt(); // number of columns. 32 | int H = in.nextInt(); // number of rows. 33 | in.nextLine(); 34 | 35 | int[][] maze = new int[H][W]; 36 | for (int i = 0; i < H; i++) { 37 | String[] LINE = in.nextLine().split(" "); // represents a line in the grid and contains W integers. Each integer represents one room of a given type. 38 | for (int j = 0; j < LINE.length; j++) { 39 | maze[i][j] = Integer.parseInt(LINE[j]); 40 | } 41 | } 42 | int EX = in.nextInt(); // the coordinate along the X axis of the exit (not useful for this first mission, but must be read). 43 | 44 | List directions = Arrays.asList("TOP", "LEFT", "RIGHT"); 45 | 46 | // game loop 47 | while (true) { 48 | 49 | int XI = in.nextInt(); 50 | int YI = in.nextInt(); 51 | int POS = directions.indexOf(in.next()); 52 | 53 | String direction = pieces[maze[YI][XI]][POS]; 54 | XI += direction.equals("L") ? -1 : (direction.equals("R") ? 1 : 0); 55 | YI += direction.equals("D") ? 1 : 0; 56 | 57 | System.out.println(XI + " " + YI); 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /Medium/TheOptimalUrinalProblem.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | private static Map totals = new HashMap<>(); 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | int n = in.nextInt(); 15 | 16 | if (n == 3 || n == 4) { 17 | System.out.println("2 1"); 18 | return; 19 | } 20 | 21 | int max = 1; 22 | int spot = 1; 23 | 24 | for (int i = 0; i <= n/2; i++) { 25 | // 0000000, i=0 -> x00000X -> 2 'x' 26 | // 0000000, i=1 -> 0x0000X -> 2 'x' 27 | // 0000000, i=2 -> X0x000X -> 3 'x' 28 | int sum = (i <= 1 ? 2 : 3) 29 | + (totals.containsKey(i) ? totals.get(i) : calcSpot(0, i)) 30 | + (totals.containsKey(n - i - 1) ? totals.get(n - i - 1) : calcSpot(i, n - 1)); 31 | 32 | if (max < sum) { 33 | max = sum; 34 | spot = i + 1; 35 | } 36 | } 37 | 38 | System.out.println(max + " " + spot); 39 | } 40 | 41 | private static int calcSpot(int start, int end) { 42 | int distance = end - start; 43 | if (distance <= 3) { 44 | return 0; 45 | } 46 | 47 | if (totals.containsKey(distance)) { 48 | return totals.get(distance); 49 | } 50 | 51 | int mid = (start + end) / 2; 52 | 53 | int nb = 1 + calcSpot(start, mid) + calcSpot(mid, end); 54 | totals.put(distance, nb); 55 | return nb; 56 | } 57 | } -------------------------------------------------------------------------------- /Medium/ThereIsNoSpoonEpisode1.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Don't let the machines win. You are humanity's last hope... 5 | **/ 6 | class Player { 7 | 8 | public static void main(String[] args) { 9 | Scanner in = new Scanner(System.in); 10 | int width = in.nextInt(); // the number of cells on the X axis 11 | int height = in.nextInt(); // the number of cells on the Y axis 12 | if (in.hasNextLine()) { 13 | in.nextLine(); 14 | } 15 | boolean[][] b = new boolean[height][width]; 16 | for (int i = 0; i < height; i++) { 17 | String line = in.nextLine(); // width characters, each either 0 or . 18 | System.err.println(line); 19 | String[] str = line.split(""); 20 | 21 | for (int j=0; j < width; j++) { 22 | b[i][j] = !str[j].equals("."); 23 | } 24 | } 25 | 26 | for (int i = 0; i < height; i++) { 27 | for (int j = 0; j < width; j++) { 28 | if (b[i][j]) { 29 | String right = getCoordinate(b, i, j+1, true); 30 | String down = getCoordinate(b, i+1, j, false); 31 | System.err.println("i: " + i + ", j: " + j + "b[i][j]: " + b[i][j]); 32 | System.out.println(j + " "+ i + " " + right + " " + down); 33 | } 34 | } 35 | } 36 | 37 | // Write an action using System.out.println() 38 | // To debug: System.err.println("Debug messages..."); 39 | 40 | 41 | // Three coordinates: a node, its right neighbor, its bottom neighbor 42 | System.out.println("0 0 1 0 0 1"); 43 | } 44 | 45 | static String getCoordinate(boolean[][] b, int i, int j, boolean horizontal) { 46 | if (horizontal) { 47 | while(j < b[0].length) { 48 | if (b[i][j]) { 49 | return j + " " + i; 50 | } 51 | j++; 52 | } 53 | } else { 54 | while(i < b.length) { 55 | if (b[i][j]) { 56 | return j + " " + i; 57 | } 58 | i++; 59 | } 60 | } 61 | 62 | return "-1 -1"; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Medium/TheseRomansAreCrazy.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | private static int[] decimal = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 10 | private static String[] roman = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 11 | 12 | public static void main(String[] args) { 13 | Scanner in = new Scanner(System.in); 14 | 15 | int result = romanToDecimal(in.next()) + romanToDecimal(in.next()); 16 | 17 | System.out.println(decimalToRoman(result)); 18 | } 19 | 20 | private static int romanToDecimal(String s) { 21 | int res = 0; 22 | for (int i = 0; i < decimal.length; i++) { 23 | while (s.indexOf(roman[i]) == 0) { 24 | res += decimal[i]; 25 | s = s.substring(roman[i].length()); 26 | } 27 | } 28 | return res; 29 | } 30 | 31 | private static String decimalToRoman(int number) { 32 | String str = ""; 33 | for (int i = 0; i < decimal.length; i++) { 34 | while (number >= decimal[i]) { 35 | str += roman[i]; 36 | number -= decimal[i]; 37 | } 38 | } 39 | return str; 40 | } 41 | } -------------------------------------------------------------------------------- /Medium/TritsBalancedTernaryComputing.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayDeque; 2 | import java.util.Collections; 3 | import java.util.Queue; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * Auto-generated code below aims at helping you parse 8 | * the standard input according to the problem statement. 9 | **/ 10 | class Solution { 11 | 12 | static String[][] addition = { 13 | {"T1", "T", "0"}, 14 | {"T", "0", "1"}, 15 | {"0", "1", "1T"} 16 | }; 17 | 18 | static String[][] multiplication = { 19 | {"1", "0", "T"}, 20 | {"0", "0", "0"}, 21 | {"T", "0", "1"} 22 | }; 23 | 24 | public static void main(String[] args) { 25 | Scanner in = new Scanner(System.in); 26 | String lhs = in.nextLine(); 27 | String op = in.nextLine(); 28 | String rhs = in.nextLine(); 29 | 30 | String res = ""; 31 | 32 | switch (op) { 33 | case "+": 34 | res = addition(lhs, rhs); 35 | break; 36 | case "-": 37 | res = substraction(lhs, rhs); 38 | break; 39 | case ">>": 40 | res = shiftDown(lhs, rhs); 41 | break; 42 | case "<<": 43 | res = shiftUp(lhs, rhs); 44 | break; 45 | case "*": 46 | res = multiplication(lhs, rhs); 47 | break; 48 | } 49 | 50 | System.out.println(res); 51 | } 52 | 53 | private static int getIndex(char c) { 54 | return c == 'T' ? 0 : (c == '0' ? 1 : 2); 55 | } 56 | 57 | private static String addition(String l, String r) { 58 | StringBuilder tmp = new StringBuilder(l); 59 | 60 | Queue rets = new ArrayDeque<>(); 61 | for (int i = 0; i < l.length() || i < r.length(); i++) { 62 | char c = '0'; 63 | char d = '0'; 64 | 65 | if (i < l.length()) { 66 | c = l.charAt(l.length() - 1 - i); 67 | } 68 | 69 | if (i < r.length()) { 70 | d = r.charAt(r.length() - 1 - i); 71 | } 72 | 73 | int cIndex = getIndex(c); 74 | int dIndex = getIndex(d); 75 | 76 | String res = addition[cIndex][dIndex]; 77 | 78 | if (l.length() - 1 < i) { 79 | tmp.insert(0, res.charAt(res.length() - 1)); 80 | } else { 81 | tmp.setCharAt(l.length() - 1 - i, res.charAt(res.length() - 1)); 82 | } 83 | 84 | if (res.length() > 1) { 85 | String ret = res.substring(0, res.length() - 1); 86 | ret = fillWithZero(ret, i + 1); 87 | rets.add(ret); 88 | } 89 | } 90 | 91 | String tmps = tmp.toString(); 92 | if (!rets.isEmpty()) { 93 | while (!rets.isEmpty()) { 94 | tmps = addition(tmps, rets.poll()); 95 | 96 | } 97 | if (tmps.charAt(0) == '0') { 98 | tmps = tmps.substring(1); 99 | } 100 | } 101 | 102 | 103 | return tmps; 104 | } 105 | 106 | private static String inverse(String r) { 107 | return r.replaceAll("T", "M").replaceAll("1", "T").replaceAll("M", "1"); 108 | } 109 | 110 | private static String substraction(String l, String r) { 111 | return addition(l, inverse(r)); 112 | } 113 | 114 | 115 | private static String multiplication(String l, String r) { 116 | int index = 0; 117 | 118 | Queue toAdd = new ArrayDeque<>(); 119 | while (index < l.length() && index < r.length()) { 120 | char d = r.charAt(r.length() - 1 - index); 121 | int dIndex = getIndex(d); 122 | 123 | StringBuilder build = new StringBuilder(); 124 | for (int i = l.length() - 1; i >= 0; i--) { 125 | char c = l.charAt(i); 126 | int cIndex = getIndex(c); 127 | 128 | String res = multiplication[cIndex][dIndex]; 129 | 130 | build.insert(0, res); 131 | } 132 | 133 | String tmp = build.toString(); 134 | if (index > 0) { 135 | tmp = fillWithZero(tmp, index); 136 | } 137 | 138 | toAdd.add(tmp); 139 | index++; 140 | } 141 | 142 | String res = toAdd.poll(); 143 | while (!toAdd.isEmpty()) { 144 | String poll = toAdd.poll(); 145 | res = addition(poll, res); 146 | } 147 | 148 | return res; 149 | } 150 | 151 | private static String shiftUp(String l, String r) { 152 | String tmp = r; 153 | StringBuilder res = new StringBuilder(l); 154 | while (!tmp.startsWith("T") && !tmp.equals("0")) { 155 | res.append("0"); 156 | tmp = addition(tmp, "T"); 157 | } 158 | return res.toString(); 159 | } 160 | 161 | private static String shiftDown(String l, String r) { 162 | String tmp = r; 163 | String res = l; 164 | 165 | while (!tmp.startsWith("T") && !tmp.equals("0")) { 166 | res = res.length() == 1 ? "0" : res.substring(0, res.length() - 1); 167 | tmp = addition(tmp, "T"); 168 | } 169 | 170 | return res; 171 | } 172 | 173 | private static String fillWithZero(String str, int nb) { 174 | return str + String.join("", Collections.nCopies(nb, "0")); 175 | } 176 | } -------------------------------------------------------------------------------- /Medium/WinamaxBattle.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Auto-generated code below aims at helping you parse 5 | * the standard input according to the problem statement. 6 | **/ 7 | class Solution { 8 | 9 | static List cardsValue; 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | 14 | cardsValue = Arrays.asList("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"); 15 | 16 | int n = in.nextInt(); // the number of cards for player 1 17 | Queue player1 = new ArrayDeque<>(); 18 | for (int i = 0; i < n; i++) { 19 | player1.add(in.next()); // the n cards of player 1 20 | } 21 | 22 | int m = in.nextInt(); // the number of cards for player 2 23 | Queue player2 = new ArrayDeque<>(); 24 | for (int i = 0; i < m; i++) { 25 | player2.add(in.next()); // the m cards of player 2 26 | } 27 | 28 | List cardsP1 = new ArrayList<>(); 29 | List cardsP2 = new ArrayList<>(); 30 | 31 | int round = 0; 32 | while(!player1.isEmpty() && !player2.isEmpty()) { 33 | String p1 = player1.poll(); 34 | String p2 = player2.poll(); 35 | 36 | cardsP1.add(p1); 37 | cardsP2.add(p2); 38 | 39 | int val = compareCards(p1, p2); 40 | 41 | if (val == 0) { 42 | if (player1.size() < 4 || player2.size() < 4) { 43 | round = -1; 44 | break; 45 | } 46 | 47 | cardsP1.add(player1.poll()); 48 | cardsP1.add(player1.poll()); 49 | cardsP1.add(player1.poll()); 50 | 51 | cardsP2.add(player2.poll()); 52 | cardsP2.add(player2.poll()); 53 | cardsP2.add(player2.poll()); 54 | 55 | continue; 56 | } else { 57 | if (val < 0) { 58 | player1.addAll(cardsP1); 59 | player1.addAll(cardsP2); 60 | } else { 61 | player2.addAll(cardsP1); 62 | player2.addAll(cardsP2); 63 | } 64 | cardsP1.clear(); 65 | cardsP2.clear(); 66 | } 67 | 68 | round++; 69 | } 70 | 71 | if (round == -1) { 72 | System.out.println("PAT"); 73 | } else { 74 | System.out.println((player1.isEmpty() ? 2 : 1) + " " + round); 75 | } 76 | } 77 | 78 | private static int compareCards(String p1, String p2) { 79 | int i1 = cardsValue.indexOf(p1.substring(0, p1.length() - 1)); 80 | int i2 = cardsValue.indexOf(p2.substring(0, p2.length() - 1)); 81 | return i2 - i1; 82 | } 83 | } -------------------------------------------------------------------------------- /VeryHard/MusicScores.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Auto-generated code below aims at helping you parse 7 | * the standard input according to the problem statement. 8 | **/ 9 | class Solution { 10 | 11 | static int width; 12 | static int height; 13 | 14 | static boolean[][] grid; 15 | 16 | static int firstBX = Integer.MAX_VALUE; 17 | static int firstBY; 18 | static int lastBY; 19 | static int nbBlackPixelOnFirstLine; 20 | 21 | static int lineHeight; 22 | static int noteHeight; 23 | 24 | static int minY; 25 | static int maxY; 26 | 27 | static int notesCounter = 6; 28 | 29 | static Note[] notes = new Note[12]; 30 | 31 | public static void main(String[] args) { 32 | Scanner in = new Scanner(System.in); 33 | width = in.nextInt(); 34 | height = in.nextInt(); 35 | 36 | grid = new boolean[height][width]; 37 | 38 | int currentY = 0; 39 | int currentX = 0; 40 | while (in.hasNext()) { 41 | String str = in.next(); 42 | int nbPixels = in.nextInt(); 43 | 44 | if (str.equals("W")) { 45 | currentY += (currentX + nbPixels) / width; 46 | currentX = (currentX + nbPixels) % width; 47 | } else { 48 | if (currentX < firstBX) { 49 | firstBX = currentX; 50 | firstBY = currentY; 51 | nbBlackPixelOnFirstLine = 0; 52 | } 53 | if (currentX == firstBX) { 54 | nbBlackPixelOnFirstLine++; 55 | lastBY = currentY; 56 | } 57 | 58 | // black pixel don't go all the way to the width 59 | for (int j = 0; j < nbPixels; j++) { 60 | grid[currentY][++currentX] = true; 61 | } 62 | } 63 | } 64 | 65 | lineHeight = nbBlackPixelOnFirstLine / 5; 66 | noteHeight = (lastBY + 1 - firstBY - nbBlackPixelOnFirstLine) / 4; 67 | minY = firstBY - noteHeight; 68 | maxY = lastBY + noteHeight; 69 | 70 | // Quick fix for now 71 | int delta = 0; 72 | if (lineHeight == 1) { 73 | delta = 1; 74 | notesCounter = 4; 75 | } 76 | 77 | int full = noteHeight + lineHeight; 78 | int half = full / 2; 79 | 80 | notes[0] = new Note('G', minY, minY + noteHeight); 81 | notes[1] = new Note('F', minY + half, minY + half + noteHeight + delta); 82 | notes[2] = new Note('E', minY + full, minY + full + noteHeight - 1 + delta); 83 | notes[3] = new Note('D', minY + half + full, minY + half + full + noteHeight + delta); 84 | notes[4] = new Note('C', minY + 2 * full, minY + 2 * full + noteHeight - 1 + delta); 85 | notes[5] = new Note('B', minY + half + 2 * full, minY + half + 2 * full + noteHeight + delta); 86 | notes[6] = new Note('A', minY + 3 * full, minY + 3 * full + noteHeight - 1 + delta); 87 | notes[7] = new Note('G', minY + half + 3 * full, minY + half + 3 * full + noteHeight + delta); 88 | notes[8] = new Note('F', minY + 4 * full, minY + 4 * full + noteHeight - 1 + delta); 89 | notes[9] = new Note('E', minY + half + 4 * full, minY + half + 4 * full + noteHeight + delta); 90 | notes[10] = new Note('D', minY + 5 * full, minY + 5 * full + noteHeight - 1 + delta); 91 | notes[11] = new Note('C', minY + half + 5 * full, minY + half + 5 * full + noteHeight + delta); 92 | 93 | System.out.println(String.join(" ", findNote())); 94 | } 95 | 96 | private static List findNote() { 97 | List res = new ArrayList<>(); 98 | 99 | int[] counter = new int[12]; 100 | 101 | for (int i = firstBX; i < width - firstBX; i++) { 102 | for (int j = 0; j < 12; j++) { 103 | if (grid[notes[j].startY][i] && grid[notes[j].endY][i]) { 104 | counter[j]++; 105 | 106 | // counter to map the outline of the notes 107 | if (counter[j] == notesCounter) { 108 | res.add(notes[j].c + "" + (grid[notes[j].getMiddle()][i] ? "Q" : "H")); 109 | i += noteHeight - notesCounter; 110 | counter[j] = 0; 111 | } else { 112 | break; 113 | } 114 | } else { 115 | counter[j] = 0; 116 | } 117 | } 118 | } 119 | 120 | return res; 121 | } 122 | 123 | private static class Note { 124 | char c; 125 | int startY; 126 | int endY; 127 | 128 | Note(char c, int startY, int endY) { 129 | this.c = c; 130 | this.startY = startY; 131 | this.endY = endY; 132 | } 133 | 134 | int getMiddle() { 135 | return (endY + startY) / 2; 136 | } 137 | } 138 | } -------------------------------------------------------------------------------- /link.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gctom57/codingame/fb1702634c99d64797f1a690bdb55dfd1d83091a/link.png --------------------------------------------------------------------------------