├── ContractBinarySearch ├── .idea │ ├── .gitignore │ ├── codeStyles │ │ └── codeStyleConfig.xml │ ├── misc.xml │ ├── modules.xml │ └── vcs.xml ├── ContractBinarySearch.iml ├── out │ └── production │ │ └── ContractBinarySearch │ │ └── META-INF │ │ └── ContractBinarySearch.kotlin_module └── src │ ├── base │ ├── Asserts.java │ ├── MainChecker.java │ ├── MainFilesChecker.java │ ├── Randomized.java │ ├── TestCounter.java │ └── Triple.java │ └── search │ ├── BinarySearch.java │ ├── BinarySearchBaseTest.java │ ├── BinarySearchMissingTest.java │ ├── BinarySearchShift.java │ ├── BinarySearchShiftTest.java │ ├── BinarySearchSpanTest.java │ └── BinarySearchTest.java ├── Exceptions ├── Exceptions.iml └── src │ ├── base │ ├── Asserts.java │ ├── MainChecker.java │ ├── MainFilesChecker.java │ ├── MainStdChecker.java │ ├── Pair.java │ ├── Randomized.java │ └── TestCounter.java │ └── expression │ ├── BaseTest.java │ ├── CommonExpression.java │ ├── Expression.java │ ├── ToMiniString.java │ ├── TripleExpression.java │ ├── exceptions │ ├── AbstractCheckedBinaryOperator.java │ ├── AbstractCheckedUnoOperator.java │ ├── AddOverflowException.java │ ├── CheckedAdd.java │ ├── CheckedDivide.java │ ├── CheckedLog.java │ ├── CheckedLog2.java │ ├── CheckedMultiply.java │ ├── CheckedNegate.java │ ├── CheckedPower.java │ ├── CheckedSubtract.java │ ├── Const.java │ ├── ConstOverflowException.java │ ├── DivByZeroException.java │ ├── DivOverflowException.java │ ├── ExceptionsPowLog2Test.java │ ├── ExceptionsTest.java │ ├── ExpressionException.java │ ├── ExpressionParser.java │ ├── LogarithmBaseException.java │ ├── Main.java │ ├── MultiplyOverflowException.java │ ├── NegateOverflowException.java │ ├── NegatePowException.java │ ├── NegativeLogarithm.java │ ├── OverflowException.java │ ├── Parser.java │ ├── ParserException.java │ ├── Power2.java │ ├── PowerOverflowException.java │ ├── SubtractOverflowException.java │ └── Variable.java │ └── parser │ ├── Either.java │ ├── ExpressionParser.java │ ├── Parser.java │ ├── ParserTest.java │ ├── Token.java │ └── Tokenizer.java ├── Expression ├── .idea │ ├── .gitignore │ ├── codeStyles │ │ └── codeStyleConfig.xml │ ├── inspectionProfiles │ │ └── Project_Default.xml │ ├── misc.xml │ ├── modules.xml │ ├── uiDesigner.xml │ └── vcs.xml ├── Expression.iml ├── out │ └── production │ │ └── Expression │ │ └── META-INF │ │ └── Expression.kotlin_module └── src │ ├── base │ ├── Asserts.java │ ├── MainChecker.java │ ├── MainFilesChecker.java │ ├── MainStdChecker.java │ ├── Pair.java │ ├── Randomized.java │ └── TestCounter.java │ └── expression │ ├── AbstractBinaryOperator.java │ ├── AbstractUnoOperator.java │ ├── Add.java │ ├── BaseTest.java │ ├── CommonExpression.java │ ├── Const.java │ ├── Divide.java │ ├── Expression.java │ ├── ExpressionTest.java │ ├── Log.java │ ├── Log2.java │ ├── Minus.java │ ├── Multiply.java │ ├── Power.java │ ├── Power2.java │ ├── Subtract.java │ ├── ToMiniString.java │ ├── TripleExpression.java │ ├── TripleExpressionTest.java │ ├── Variable.java │ └── parser │ ├── Either.java │ ├── ExpressionParser.java │ ├── Main.java │ ├── Parser.java │ ├── ParserAbsSquareTest.java │ ├── ParserReverseDigitsTest.java │ ├── ParserShiftsTest.java │ ├── ParserTest.java │ ├── Token.java │ └── Tokenizer.java ├── GenericExpression ├── .idea │ ├── .gitignore │ ├── codeStyles │ │ └── codeStyleConfig.xml │ ├── misc.xml │ ├── modules.xml │ ├── uiDesigner.xml │ └── vcs.xml ├── GenericExpression.iml └── src │ ├── base │ ├── Asserts.java │ ├── MainChecker.java │ ├── MainFilesChecker.java │ ├── Randomized.java │ ├── TestCounter.java │ └── Triple.java │ └── expression │ ├── AbstractBinaryOperation.java │ ├── BaseTest.java │ ├── ToMiniString.java │ ├── TripleExpression.java │ ├── evaluator │ └── Evaluator.java │ ├── exceptions │ ├── ExceptionsPowLog2Test.java │ ├── ExceptionsPowLogTest.java │ ├── ExceptionsTest.java │ └── Parser.java │ ├── generic │ ├── GenericCmmTest.java │ ├── GenericCmmUfbTest.java │ ├── GenericCmmUlsTest.java │ ├── GenericLsTest.java │ ├── GenericTabulator.java │ ├── GenericTest.java │ ├── GenericUfbTest.java │ ├── GenericUlsTest.java │ └── Tabulator.java │ └── parser │ ├── Either.java │ └── ParserTest.java ├── InterfaceQueue ├── .idea │ ├── .gitignore │ ├── codeStyles │ │ └── codeStyleConfig.xml │ ├── misc.xml │ ├── modules.xml │ ├── uiDesigner.xml │ └── vcs.xml ├── InterfaceQueue.iml ├── out │ └── production │ │ └── InterfaceQueue │ │ └── META-INF │ │ └── InterfaceQueue.kotlin_module └── src │ ├── base │ ├── Asserts.java │ ├── MainChecker.java │ ├── MainFilesChecker.java │ ├── Randomized.java │ ├── TestCounter.java │ └── Triple.java │ └── queue │ ├── AbstractQueue.java │ ├── ArrayQueue.java │ ├── ArrayQueueDequeTest.java │ ├── ArrayQueueIndexedDequeTest.java │ ├── ArrayQueueTest.java │ ├── ArrayQueueToArrayTest.java │ ├── ArrayQueueToStrTest.java │ ├── LinkedQueue.java │ ├── Main.java │ ├── Queue.java │ ├── QueueFunctionsTest.java │ ├── QueueIfWhileTest.java │ ├── QueueTest.java │ ├── QueueToArrayTest.java │ └── ReflectionTest.java ├── Markup ├── Test.java └── markup │ ├── AbstractList.java │ ├── AbstractMarkupElement.java │ ├── Emphasis.java │ ├── InList.java │ ├── InParagraph.java │ ├── ListItem.java │ ├── Markable.java │ ├── OrderedList.java │ ├── Paragraph.java │ ├── Strikeout.java │ ├── Strong.java │ ├── Text.java │ ├── UnorderedList.java │ ├── base │ ├── Asserts.java │ ├── MainChecker.java │ ├── MainFilesChecker.java │ ├── MainStdChecker.java │ ├── Pair.java │ ├── Randomized.java │ └── TestCounter.java │ └── markup │ ├── AbstractTest.java │ ├── HtmlListTest.java │ ├── HtmlTest.java │ ├── ListTest.java │ └── MarkdownTest.java ├── Md2Html ├── .idea │ ├── .gitignore │ ├── codeStyles │ │ └── codeStyleConfig.xml │ ├── misc.xml │ ├── modules.xml │ ├── uiDesigner.xml │ └── vcs.xml ├── Md2Html.iml ├── kekTest.in ├── out.txt ├── out │ └── production │ │ └── Md2Html │ │ ├── META-INF │ │ └── Md2Html.kotlin_module │ │ ├── Md2HtmlLinkTest.jar │ │ ├── Md2HtmlTest.jar │ │ └── Md2HtmlUnderlineTest.jar └── src │ ├── base │ ├── Asserts.java │ ├── MainChecker.java │ ├── MainFilesChecker.java │ ├── MainStdChecker.java │ ├── Pair.java │ ├── Randomized.java │ └── TestCounter.java │ └── md2html │ ├── BlockParser.java │ ├── HeaderParser.java │ ├── IntList.java │ ├── Md2Html.java │ ├── ParagraphParser.java │ └── TextParser.java ├── NERCHW ├── .idea │ ├── .gitignore │ ├── codeStyles │ │ └── codeStyleConfig.xml │ ├── inspectionProfiles │ │ └── Project_Default.xml │ ├── misc.xml │ ├── modules.xml │ └── vcs.xml ├── NERCHW.iml └── src │ ├── A.java │ ├── B.java │ ├── D.java │ ├── E.java │ ├── H.java │ ├── I.java │ ├── J.java │ ├── K.java │ └── M.java ├── Queue ├── .idea │ ├── .gitignore │ ├── codeStyles │ │ └── codeStyleConfig.xml │ ├── inspectionProfiles │ │ └── Project_Default.xml │ ├── misc.xml │ ├── modules.xml │ ├── uiDesigner.xml │ └── vcs.xml ├── Queue.iml ├── out │ └── production │ │ └── Queue │ │ └── META-INF │ │ └── Queue.kotlin_module └── src │ ├── ArrayQueueTest.java │ ├── base │ ├── Asserts.java │ ├── MainChecker.java │ ├── MainFilesChecker.java │ ├── Randomized.java │ ├── TestCounter.java │ └── Triple.java │ └── queue │ ├── ArrayQueue.java │ ├── ArrayQueueADT.java │ ├── ArrayQueueADTTest.java │ ├── ArrayQueueDequeTest.java │ ├── ArrayQueueIndexedDequeTest.java │ ├── ArrayQueueModule.java │ ├── ArrayQueueModuleTest.java │ ├── ArrayQueueTest.java │ ├── ArrayQueueToArrayTest.java │ ├── ArrayQueueToStrTest.java │ ├── QueueTest.java │ └── ReflectionTest.java ├── README.md ├── Reverse └── ReverseEven.java ├── Scanner ├── MyClasses │ ├── Checker.java │ ├── IntList.java │ └── Scanner.java ├── ReverseSort.java ├── Scanner.java └── WordStatWords.java ├── SumHex └── SumHex.java ├── WordStat └── WordStatWords.java ├── WordStatFirstIndex ├── MyClasses │ ├── Checker.java │ ├── IntList.java │ └── Scanner.java ├── WordStatFirstIndex.java └── WordStatIntList.java └── ticTacToe ├── .idea ├── .gitignore ├── codeStyles │ └── codeStyleConfig.xml ├── misc.xml ├── modules.xml ├── uiDesigner.xml └── vcs.xml ├── src └── MNK │ ├── Board.java │ ├── Cell.java │ ├── Game.java │ ├── HumanPlayer.java │ ├── Main.java │ ├── Move.java │ ├── NMKBoard.java │ ├── Player.java │ ├── Position.java │ ├── ProxyPosition.java │ ├── RandomPlayer.java │ ├── Result.java │ ├── SequentialPlayer.java │ ├── TicTacToe.java │ └── WinnerPlayer.java └── ticTacToe.iml /ContractBinarySearch/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml -------------------------------------------------------------------------------- /ContractBinarySearch/.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /ContractBinarySearch/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /ContractBinarySearch/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /ContractBinarySearch/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /ContractBinarySearch/ContractBinarySearch.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /ContractBinarySearch/out/production/ContractBinarySearch/META-INF/ContractBinarySearch.kotlin_module: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /ContractBinarySearch/src/base/Asserts.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.Locale; 4 | import java.util.Objects; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class Asserts { 10 | static { 11 | Locale.setDefault(Locale.US); 12 | } 13 | 14 | public static void assertEquals(final String message, final Object expected, final Object actual) { 15 | assertTrue(String.format("%s:%n expected `%s`,%n actual `%s`", message, expected, actual), Objects.equals(expected, actual)); 16 | } 17 | 18 | public static void assertTrue(final String message, final boolean value) { 19 | if (!value) { 20 | throw new AssertionError(message); 21 | } 22 | } 23 | 24 | public static void assertEquals(final String message, final int expected, final int actual) { 25 | assertTrue(String.format("%s: Expected %d, found %d", message, expected, actual), actual == expected); 26 | } 27 | 28 | public static void assertEquals(final String message, final double precision, final double expected, final double actual) { 29 | assertTrue( 30 | String.format("%s: Expected %.12f, found %.12f", message, expected, actual), 31 | Math.abs(actual - expected) < precision || 32 | Math.abs(actual - expected) < precision * Math.abs(actual) || 33 | (Double.isNaN(actual) || Double.isInfinite(actual)) && 34 | (Double.isNaN(expected) || Double.isInfinite(expected)) 35 | ); 36 | } 37 | 38 | public static void checkAssert(final Class c) { 39 | if (!c.desiredAssertionStatus()) { 40 | throw error("You should enable assertions by running 'java -ea %s'", c.getName()); 41 | } 42 | } 43 | 44 | public static AssertionError error(final String format, final Object... args) { 45 | return new AssertionError(String.format(format, args)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /ContractBinarySearch/src/base/MainFilesChecker.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.List; 8 | 9 | /** 10 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 11 | */ 12 | public class MainFilesChecker extends MainChecker { 13 | public MainFilesChecker(final String className) { 14 | super(className); 15 | } 16 | 17 | private Path getFile(final String suffix) { 18 | return Paths.get(String.format("test%d.%s", counter.getTest() + 1, suffix)); 19 | } 20 | 21 | protected List runFiles(final List input) { 22 | try { 23 | final Path inf = getFile("in"); 24 | final Path ouf = getFile("out"); 25 | Files.write(inf, input); 26 | run(inf.toString(), ouf.toString()); 27 | final List output = Files.readAllLines(ouf); 28 | Files.delete(inf); 29 | Files.delete(ouf); 30 | return output; 31 | } catch (final IOException e) { 32 | throw new AssertionError(e); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /ContractBinarySearch/src/base/Randomized.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class Randomized { 10 | public static final String ENGLISH = "abcdefghijklmnopqrstuvwxyz"; 11 | 12 | public final Random random = new Random(8045702385702345702L); 13 | 14 | public String randomString(final String chars) { 15 | return randomChar(chars) + (random.nextBoolean() ? "" : randomString(chars)); 16 | } 17 | 18 | public char randomChar(final String chars) { 19 | return chars.charAt(random.nextInt(chars.length())); 20 | } 21 | 22 | public String randomString(final String chars, final int length) { 23 | final StringBuilder string = new StringBuilder(); 24 | for (int i = 0; i < length; i++) { 25 | string.append(randomChar(chars)); 26 | } 27 | return string.toString(); 28 | } 29 | 30 | public String randomString(final String chars, final int minLength, int maxLength) { 31 | return randomString(chars, randomInt(minLength, maxLength + 1)); 32 | } 33 | 34 | public int randomInt(final int min, final int max) { 35 | return random.nextInt(max - min) + min; 36 | } 37 | 38 | @SafeVarargs 39 | public final T randomItem(final T... items) { 40 | return items[random.nextInt(items.length)]; 41 | } 42 | 43 | public final T randomItem(final List items) { 44 | return items.get(random.nextInt(items.size())); 45 | } 46 | 47 | public Random getRandom() { 48 | return random; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /ContractBinarySearch/src/base/Triple.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public class Triple { 7 | private final F first; 8 | private final S second; 9 | private final T third; 10 | 11 | public Triple(final F first, final S second, final T third) { 12 | this.first = first; 13 | this.second = second; 14 | this.third = third; 15 | } 16 | 17 | public F first() { 18 | return first; 19 | } 20 | 21 | public S second() { 22 | return second; 23 | } 24 | 25 | public T third() { 26 | return third; 27 | } 28 | 29 | public static Triple of(final F first, final S second, final T third) { 30 | return new Triple<>(first, second, third); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /ContractBinarySearch/src/search/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package search; 2 | 3 | public class BinarySearch { 4 | 5 | static int iterative(int[] arr, int x) { 6 | int l = 0, r = arr.length; 7 | //inv: [l, r] 8 | while (l < r) { 9 | int m = l + (r - l) / 2; 10 | if (arr[m] > x) { 11 | l = m + 1; 12 | } else { 13 | r = m; 14 | } 15 | } 16 | // Post: l == r and ans in [l, r] => l == r == ans 17 | return l; 18 | } 19 | 20 | static int rec(int[] arr, int x, int l, int r) { 21 | if (l >= r) { 22 | return l; 23 | } 24 | int m = l + (r - l) / 2; 25 | if (arr[m] > x) { 26 | return rec(arr, x, m + 1, r); 27 | } else { 28 | return rec(arr, x, l, m); 29 | } 30 | } 31 | 32 | static int recursive(int[] arr, int x) { 33 | return rec(arr, x, 0, arr.length); 34 | } 35 | 36 | public static void main(String[] args) { 37 | int x = Integer.parseInt(args[0]); 38 | int[] arr = new int[args.length - 1]; 39 | for (int i = 0; i < arr.length; i++) { 40 | arr[i] = Integer.parseInt(args[i + 1]); 41 | } 42 | System.out.println(iterative(arr, x)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /ContractBinarySearch/src/search/BinarySearchBaseTest.java: -------------------------------------------------------------------------------- 1 | package search; 2 | 3 | import base.MainChecker; 4 | 5 | import java.util.Arrays; 6 | import java.util.Collections; 7 | import java.util.stream.Collectors; 8 | import java.util.stream.IntStream; 9 | 10 | /** 11 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 12 | */ 13 | public class BinarySearchBaseTest { 14 | public static void test(final String className, final Solver solver) { 15 | final MainChecker checker = new MainChecker("search." + className); 16 | 17 | test(checker, solver, 0); 18 | test(checker, solver, 0, 0); 19 | for (final int size : new int[]{5, 4, 2, 1, 0, 10, 100}) { 20 | final int[] a = new int[size]; 21 | for (final int max : new int[]{5, 4, 2, 1, 0, 10, 100, Integer.MAX_VALUE / 2}) { 22 | for (int i = 0; i < size; i++) { 23 | a[i] = checker.random.nextInt(max * 2 + 1) - max; 24 | } 25 | Arrays.sort(a); 26 | for (int i = 0; i < size / 2; i++) { 27 | final int t = a[i]; 28 | a[i] = a[size - i - 1]; 29 | a[size - i - 1] = t; 30 | } 31 | for (int i = 0; i < size; i++) { 32 | test(checker, solver, a[i], a); 33 | if (i != 0) { 34 | test(checker, solver, (a[i - 1] + a[i]) / 2, a); 35 | } 36 | } 37 | test(checker, solver, Integer.MIN_VALUE, a); 38 | test(checker, solver, Integer.MAX_VALUE, a); 39 | } 40 | } 41 | checker.printStatus(); 42 | } 43 | 44 | private static void test(final MainChecker checker, final Solver solver, final int x, final int... a) { 45 | checker.checkEquals( 46 | Collections.singletonList(Arrays.stream(solver.solve(x, a)).mapToObj(Long::toString).collect(Collectors.joining(" "))), 47 | checker.run(IntStream.concat(IntStream.of(x), IntStream.of(a)).mapToObj(Integer::toString).toArray(String[]::new)) 48 | ); 49 | } 50 | 51 | interface Solver { 52 | long[] solve(final int x, final int... a); 53 | } 54 | 55 | public static long[] longs(final long... longs) { 56 | return longs; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /ContractBinarySearch/src/search/BinarySearchMissingTest.java: -------------------------------------------------------------------------------- 1 | package search; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public class BinarySearchMissingTest extends BinarySearchBaseTest { 7 | public static void main(final String... args) { 8 | test("BinarySearchMissing", (x, a) -> { 9 | for (int i = 0; i < a.length; i++) { 10 | if (a[i] == x) { 11 | return longs(i); 12 | } 13 | if (x > a[i]) { 14 | return longs(-1 - i); 15 | } 16 | } 17 | return longs(-1 - a.length); 18 | }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /ContractBinarySearch/src/search/BinarySearchShiftTest.java: -------------------------------------------------------------------------------- 1 | package search; 2 | 3 | import base.MainChecker; 4 | 5 | import java.util.List; 6 | import java.util.stream.IntStream; 7 | 8 | /** 9 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 10 | */ 11 | public class BinarySearchShiftTest extends BinarySearchBaseTest { 12 | public static final int[] SIZES = {5, 4, 2, 1, 10, 100}; 13 | public static final int[] VALUES = new int[]{5, 4, 2, 1, 0, 10, 100, Integer.MAX_VALUE / 2}; 14 | 15 | public static void test() { 16 | final MainChecker checker = new MainChecker("search.BinarySearchShift"); 17 | 18 | test(checker, 0); 19 | test(checker, 0, 0); 20 | for (final int size : SIZES) { 21 | for (final int max : VALUES) { 22 | final int[] a = checker.random.ints(size, -max, max + 1).sorted().distinct().toArray(); 23 | for (int k = 0; k < a.length; k++) { 24 | test(checker, k, a); 25 | 26 | final int last = a[a.length - 1]; 27 | System.arraycopy(a, 0, a, 1, a.length - 1); 28 | a[0] = last; 29 | } 30 | } 31 | } 32 | checker.printStatus(); 33 | } 34 | 35 | private static void test(final MainChecker checker, final int k, final int... a) { 36 | checker.checkEquals( 37 | List.of(Integer.toString(k)), 38 | checker.run(IntStream.of(a).mapToObj(Integer::toString).toArray(String[]::new)) 39 | ); 40 | } 41 | 42 | public static void main(final String... args) { 43 | test(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /ContractBinarySearch/src/search/BinarySearchSpanTest.java: -------------------------------------------------------------------------------- 1 | package search; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public class BinarySearchSpanTest extends BinarySearchBaseTest { 7 | public static void main(final String... args) { 8 | test("BinarySearchSpan", (x, a) -> { 9 | for (int i = 0; i < a.length; i++) { 10 | if (a[i] == x) { 11 | int j = i; 12 | while (j < a.length && a[j] == x) { 13 | j++; 14 | } 15 | return longs(i, j - i); 16 | } 17 | if (x > a[i]) { 18 | return longs(i, 0); 19 | } 20 | } 21 | return longs(a.length, 0); 22 | }); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ContractBinarySearch/src/search/BinarySearchTest.java: -------------------------------------------------------------------------------- 1 | package search; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public class BinarySearchTest extends BinarySearchBaseTest { 7 | public static void main(final String... args) { 8 | test("BinarySearch", (x, a) -> { 9 | for (int i = 0; i < a.length; i++) { 10 | if (a[i] <= x) { 11 | return longs(i); 12 | } 13 | } 14 | return longs(a.length); 15 | }); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Exceptions/Exceptions.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Exceptions/src/base/Asserts.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.List; 4 | import java.util.Locale; 5 | import java.util.Objects; 6 | 7 | /** 8 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 9 | */ 10 | public class Asserts { 11 | static { 12 | Locale.setDefault(Locale.US); 13 | } 14 | 15 | public static void assertEquals(final String message, final Object expected, final Object actual) { 16 | assertTrue(String.format("%s:%n expected `%s`,%n actual `%s`", message, expected, actual), Objects.equals(expected, actual)); 17 | } 18 | 19 | public static void assertEquals(final String message, final List expected, final List actual) { 20 | for (int i = 0; i < Math.min(expected.size(), actual.size()); i++) { 21 | assertEquals(message + ":" + (i + 1), expected.get(i), actual.get(i)); 22 | } 23 | assertEquals(message + ": Number of items", expected.size(), actual.size()); 24 | } 25 | 26 | public static void assertTrue(final String message, final boolean value) { 27 | if (!value) { 28 | throw error("%s", message); 29 | } 30 | } 31 | 32 | public static void assertEquals(final String message, final double expected, final double actual, final double precision) { 33 | final double error = Math.abs(expected - actual); 34 | assertTrue( 35 | String.format("%s: expected %f, found %f", message, expected, actual), 36 | error <= precision || (Math.abs(expected) >= 1 && error / Math.abs(expected) < precision) 37 | ); 38 | } 39 | 40 | public static void assertSame(final String message, final Object expected, final Object actual) { 41 | assertTrue(String.format("%s: expected same objects: %s and %s", message, expected, actual), expected == actual); 42 | } 43 | 44 | protected static void checkAssert(final Class c) { 45 | if (!c.desiredAssertionStatus()) { 46 | throw error("You should enable assertions by running 'java -ea %s'", c.getName()); 47 | } 48 | } 49 | 50 | public static AssertionError error(final String format, final Object... args) { 51 | return new AssertionError(String.format(format, args)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Exceptions/src/base/MainFilesChecker.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.List; 8 | 9 | /** 10 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 11 | */ 12 | public class MainFilesChecker extends MainChecker { 13 | public MainFilesChecker(final String className) { 14 | super(className); 15 | } 16 | 17 | private Path getFile(final String suffix) { 18 | return Paths.get(String.format("test%d.%s", counter.getTest() + 1, suffix)); 19 | } 20 | 21 | protected List runFiles(final List input) { 22 | try { 23 | final Path inf = getFile("in"); 24 | final Path ouf = getFile("out"); 25 | Files.write(inf, input); 26 | run(inf.toString(), ouf.toString()); 27 | final List output = Files.readAllLines(ouf); 28 | Files.delete(inf); 29 | Files.delete(ouf); 30 | return output; 31 | } catch (IOException e) { 32 | throw new AssertionError(e); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Exceptions/src/base/MainStdChecker.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.io.*; 4 | import java.util.List; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class MainStdChecker extends MainChecker { 10 | 11 | public MainStdChecker(final String className) { 12 | super(className); 13 | } 14 | 15 | protected List runStd(final List input) { 16 | final ByteArrayOutputStream baos = new ByteArrayOutputStream(); 17 | try (final PrintWriter writer = new PrintWriter(baos)) { 18 | input.forEach(writer::println); 19 | } 20 | 21 | final InputStream oldIn = System.in; 22 | try { 23 | System.setIn(new ByteArrayInputStream(baos.toByteArray())); 24 | return runComment(String.format("<%d input lines>", input.size())); 25 | } finally { 26 | System.setIn(oldIn); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Exceptions/src/base/Pair.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public class Pair { 9 | public final F first; 10 | public final S second; 11 | 12 | public Pair(final F first, final S second) { 13 | this.first = first; 14 | this.second = second; 15 | } 16 | 17 | public static Pair of(final F first, final S second) { 18 | return new Pair<>(first, second); 19 | } 20 | 21 | public static Pair of(final Map.Entry e) { 22 | return of(e.getKey(), e.getValue()); 23 | } 24 | 25 | @Override 26 | public boolean equals(final Object o) { 27 | if (this == o) return true; 28 | if (o == null || getClass() != o.getClass()) return false; 29 | 30 | final Pair pair = (Pair) o; 31 | 32 | return first.equals(pair.first) && second.equals(pair.second); 33 | } 34 | 35 | @Override 36 | public int hashCode() { 37 | int result = first.hashCode(); 38 | result = 31 * result + second.hashCode(); 39 | return result; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return first + ": " + second; 45 | } 46 | 47 | public F getFirst() { 48 | return first; 49 | } 50 | 51 | public S getSecond() { 52 | return second; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Exceptions/src/base/Randomized.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class Randomized { 10 | public static final String ENGLISH = "abcdefghijklmnopqrstuvwxyz"; 11 | public static final String RUSSIAN = "абвгдеежзийклмнопрстуфхцчшщъыьэюя"; 12 | public static final String GREEK = "αβγŋδεζηθικλμνξοπρτυφχψω"; 13 | 14 | public final Random random = new Random(8045702385702345702L); 15 | 16 | public String randomString(final String chars) { 17 | return randomChar(chars) + (random.nextBoolean() ? "" : randomString(chars)); 18 | } 19 | 20 | public char randomChar(final String chars) { 21 | return chars.charAt(random.nextInt(chars.length())); 22 | } 23 | 24 | public String randomString(final String chars, final int length) { 25 | final StringBuilder string = new StringBuilder(); 26 | for (int i = 0; i < length; i++) { 27 | string.append(randomChar(chars)); 28 | } 29 | return string.toString(); 30 | } 31 | 32 | public String randomString(final String chars, final int minLength, int maxLength) { 33 | return randomString(chars, randomInt(minLength, maxLength + 1)); 34 | } 35 | 36 | public int randomInt(final int min, final int max) { 37 | return random.nextInt(max - min) + min; 38 | } 39 | 40 | @SafeVarargs 41 | public final T randomItem(final T... items) { 42 | return items[random.nextInt(items.length)]; 43 | } 44 | 45 | public final T randomItem(final List items) { 46 | return items.get(random.nextInt(items.size())); 47 | } 48 | 49 | public Random getRandom() { 50 | return random; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Exceptions/src/expression/BaseTest.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | import base.Asserts; 4 | import base.TestCounter; 5 | 6 | import java.util.*; 7 | 8 | /** 9 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 10 | */ 11 | public abstract strictfp class BaseTest extends Asserts { 12 | protected final Random random = new Random(7240958270485L); 13 | 14 | protected final TestCounter counter = new TestCounter(); 15 | 16 | protected BaseTest() { 17 | Locale.setDefault(Locale.US); 18 | 19 | checkAssert(getClass()); 20 | } 21 | 22 | protected T random(final List variants) { 23 | return variants.get(random.nextInt(variants.size())); 24 | } 25 | 26 | protected int randomInt(final int n) { 27 | return random.nextInt(n); 28 | } 29 | 30 | public void run() { 31 | System.out.println("=== Testing " + getClass().getSimpleName()); 32 | test(); 33 | counter.printStatus(getClass()); 34 | } 35 | 36 | protected abstract void test(); 37 | 38 | @SafeVarargs 39 | protected static List list(final T... items) { 40 | return new ArrayList<>(Arrays.asList(items)); 41 | } 42 | 43 | protected static void addRange(final List values, final int d, final int c) { 44 | for (int i = -d; i <= d; i++) { 45 | values.add(c + i); 46 | } 47 | } 48 | 49 | public static final class Op { 50 | public final String name; 51 | public final T f; 52 | 53 | private Op(final String name, final T f) { 54 | this.name = name; 55 | this.f = f; 56 | } 57 | } 58 | 59 | public static Op op(final String name, final T f) { 60 | return new Op<>(name, f); 61 | } 62 | 63 | public static int mode(final String[] args, final String... modes) { 64 | if (args.length != 1) { 65 | throw error("Single argument expected. Supported modes: %s", Arrays.asList(modes)); 66 | } 67 | final int index = List.of(modes).indexOf(args[0]); 68 | if (index < 0) { 69 | throw error("Invalid mode '%s'. Supported moves: %s", args[0], Arrays.asList(modes)); 70 | } 71 | return index; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Exceptions/src/expression/CommonExpression.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public interface CommonExpression extends Expression, TripleExpression {} 4 | -------------------------------------------------------------------------------- /Exceptions/src/expression/Expression.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public interface Expression extends ToMiniString { 7 | int evaluate(int x) throws ArithmeticException; 8 | } 9 | -------------------------------------------------------------------------------- /Exceptions/src/expression/ToMiniString.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public interface ToMiniString { 7 | default String toMiniString() { 8 | return toString(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Exceptions/src/expression/TripleExpression.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public interface TripleExpression extends ToMiniString { 7 | int evaluate(int x, int y, int z); 8 | } 9 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/AbstractCheckedBinaryOperator.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | import java.util.Objects; 6 | 7 | public abstract class AbstractCheckedBinaryOperator implements CommonExpression { 8 | protected final CommonExpression left, right; 9 | 10 | public AbstractCheckedBinaryOperator(CommonExpression left, CommonExpression right) { 11 | this.left = left; 12 | this.right = right; 13 | } 14 | 15 | protected abstract String getView(); 16 | protected abstract int getResult(int left, int right); 17 | 18 | @Override 19 | final public String toString() { 20 | StringBuilder res = new StringBuilder(); 21 | res.append("(").append(left).append(" "); 22 | res.append(getView()); 23 | res.append(" ").append(right).append(")"); 24 | return res.toString(); 25 | } 26 | 27 | @Override 28 | final public String toMiniString() { 29 | return toString(); 30 | } 31 | 32 | @Override 33 | final public int evaluate(int x) throws ArithmeticException { 34 | return getResult(left.evaluate(x), right.evaluate(x)); 35 | } 36 | 37 | @Override 38 | final public int evaluate(int x, int y, int z) { 39 | return getResult(left.evaluate(x, y, z), right.evaluate(x, y, z)); 40 | } 41 | 42 | @Override 43 | final public boolean equals(Object obj) { 44 | if (obj != null && getClass() == obj.getClass()) { 45 | return ((AbstractCheckedBinaryOperator)obj).left.equals(left) 46 | && ((AbstractCheckedBinaryOperator)obj).right.equals(right); 47 | } 48 | return false; 49 | } 50 | 51 | @Override 52 | final public int hashCode() { 53 | return Objects.hash(getClass(), left, right); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/AbstractCheckedUnoOperator.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | import java.util.Objects; 6 | 7 | public abstract class AbstractCheckedUnoOperator implements CommonExpression { 8 | protected final CommonExpression x; 9 | 10 | public AbstractCheckedUnoOperator(CommonExpression in) { 11 | this.x = in; 12 | } 13 | 14 | protected abstract String getView(); 15 | protected abstract int getResult(int in); 16 | 17 | @Override 18 | final public String toString() { 19 | return getView() + x.toString(); 20 | } 21 | 22 | @Override 23 | final public int evaluate(int in) { 24 | return getResult(this.x.evaluate(in)); 25 | } 26 | 27 | @Override 28 | final public int evaluate(int x, int y, int z) { 29 | return getResult(this.x.evaluate(x, y, z)); 30 | } 31 | 32 | @Override 33 | final public boolean equals(Object obj) { 34 | if (obj != null && getClass() == obj.getClass()) { 35 | return x.equals(((AbstractCheckedUnoOperator)obj).x); 36 | } 37 | return false; 38 | } 39 | 40 | @Override 41 | final public int hashCode() { 42 | return Objects.hash(getClass(), x); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/AddOverflowException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class AddOverflowException extends OverflowException { 4 | public AddOverflowException(int a, int b) { 5 | super("Add", a + " " + b); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/CheckedAdd.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | public class CheckedAdd extends AbstractCheckedBinaryOperator { 6 | public CheckedAdd(CommonExpression left, CommonExpression right) { 7 | super(left, right); 8 | } 9 | 10 | @Override 11 | protected String getView() { 12 | return "+"; 13 | } 14 | 15 | @Override 16 | protected int getResult(int left, int right) { 17 | if (right > 0 && Integer.MAX_VALUE - right < left) { 18 | throw new AddOverflowException(left, right); 19 | } else if (right < 0 && Integer.MIN_VALUE - right > left) { 20 | throw new AddOverflowException(left, right); 21 | } 22 | return left + right; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/CheckedDivide.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | public class CheckedDivide extends AbstractCheckedBinaryOperator { 6 | public CheckedDivide(CommonExpression left, CommonExpression right) { 7 | super(left, right); 8 | } 9 | 10 | @Override 11 | protected String getView() { 12 | return "/"; 13 | } 14 | 15 | @Override 16 | protected int getResult(int left, int right) { 17 | if (right == 0) { 18 | throw new DivByZeroException(); 19 | } 20 | if (left == Integer.MIN_VALUE && right == -1) { 21 | throw new DivOverflowException(left, right); 22 | } 23 | return left / right; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/CheckedLog.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | public class CheckedLog extends AbstractCheckedBinaryOperator { 6 | public CheckedLog(CommonExpression left, CommonExpression right) { 7 | super(left, right); 8 | } 9 | 10 | @Override 11 | protected String getView() { 12 | return "//"; 13 | } 14 | 15 | @Override 16 | protected int getResult(int left, int right) { 17 | if (left < 0 || left == 1) { 18 | throw new LogarithmBaseException(left, right); 19 | } 20 | if (right <= 0) { 21 | throw new NegativeLogarithm(right); 22 | } 23 | int res = 0; 24 | while (left > 1) { 25 | left /= right; 26 | res++; 27 | } 28 | return res; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/CheckedLog2.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | public class CheckedLog2 extends AbstractCheckedUnoOperator { 6 | public CheckedLog2(CommonExpression in) { 7 | super(in); 8 | } 9 | 10 | @Override 11 | protected String getView() { 12 | return "log2 "; 13 | } 14 | 15 | @Override 16 | protected int getResult(int x) { 17 | if (x <= 0) { 18 | throw new NegativeLogarithm(x); 19 | } 20 | int res = 0; 21 | while (x > 1) { 22 | res++; 23 | x /= 2; 24 | } 25 | return res; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/CheckedMultiply.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | public class CheckedMultiply extends AbstractCheckedBinaryOperator { 6 | public CheckedMultiply(CommonExpression left, CommonExpression right) { 7 | super(left, right); 8 | } 9 | 10 | @Override 11 | protected String getView() { 12 | return "*"; 13 | } 14 | 15 | @Override 16 | protected int getResult(int left, int right) { 17 | checkException(left, right); 18 | return left * right; 19 | } 20 | 21 | public static void checkException(int left, int right) { 22 | if (left != 0 && right != 0) { 23 | if (left == -1 && right == Integer.MIN_VALUE || right == -1 && left == Integer.MIN_VALUE) { 24 | throw new MultiplyOverflowException(left, right); 25 | } else if (left * right == Integer.MIN_VALUE && Integer.MIN_VALUE / right == left) { 26 | // return 27 | } else if (left == Integer.MIN_VALUE || right == Integer.MIN_VALUE) { 28 | throw new MultiplyOverflowException(left, right); 29 | } else if (Integer.MAX_VALUE / abs(left) < abs(right)) { 30 | throw new MultiplyOverflowException(left, right); 31 | } 32 | } 33 | } 34 | 35 | private static int abs(int x) { 36 | return x > 0 ? x : -x; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/CheckedNegate.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | public class CheckedNegate extends AbstractCheckedUnoOperator { 6 | public CheckedNegate(CommonExpression in) { 7 | super(in); 8 | } 9 | 10 | @Override 11 | protected String getView() { 12 | return "-"; 13 | } 14 | 15 | @Override 16 | protected int getResult(int in) { 17 | if (in == Integer.MIN_VALUE) { 18 | throw new NegateOverflowException(in); 19 | } 20 | return -in; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/CheckedPower.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | public class CheckedPower extends AbstractCheckedBinaryOperator { 6 | public CheckedPower(CommonExpression left, CommonExpression right) { 7 | super(left, right); 8 | } 9 | 10 | @Override 11 | protected String getView() { 12 | return "**"; 13 | } 14 | 15 | @Override 16 | protected int getResult(int left, int right) { 17 | if (right < 0) { 18 | throw new NegatePowException(left, right); 19 | } 20 | 21 | try { 22 | int res = 1; 23 | while (right != 0) { 24 | if ((right & 1) == 1) { 25 | right--; 26 | CheckedMultiply.checkException(res, left); 27 | res *= left; 28 | } 29 | CheckedMultiply.checkException(res, res); 30 | res *= res; 31 | left /= 2; 32 | } 33 | return res; 34 | } catch (MultiplyOverflowException e) { 35 | throw new PowerOverflowException(left, right); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/CheckedSubtract.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | public class CheckedSubtract extends AbstractCheckedBinaryOperator { 6 | public CheckedSubtract(CommonExpression left, CommonExpression right) { 7 | super(left, right); 8 | } 9 | 10 | @Override 11 | protected String getView() { 12 | return "-"; 13 | } 14 | 15 | @Override 16 | protected int getResult(int left, int right) { 17 | if (right > 0 && Integer.MIN_VALUE + right > left) { 18 | throw new SubtractOverflowException(left, right); 19 | } else if (right < 0 && Integer.MAX_VALUE + right < left) { 20 | throw new SubtractOverflowException(left, right); 21 | } 22 | return left - right; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/Const.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | public class Const implements CommonExpression { 6 | private final int val; 7 | 8 | public Const(int val) { 9 | this.val = val; 10 | } 11 | 12 | @Override 13 | public String toString() { 14 | return Integer.toString(val); 15 | } 16 | 17 | @Override 18 | public int evaluate(int x) throws ArithmeticException { 19 | return val; 20 | } 21 | 22 | @Override 23 | public int evaluate(int x, int y, int z) { 24 | return val; 25 | } 26 | 27 | @Override 28 | public boolean equals(Object obj) { 29 | if (obj != null && getClass() == obj.getClass()) { 30 | return val == ((Const) obj).val; 31 | } 32 | return false; 33 | } 34 | 35 | @Override 36 | public int hashCode() { 37 | return val; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/ConstOverflowException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class ConstOverflowException extends OverflowException { 4 | public ConstOverflowException(String num) { 5 | super("Constant", num); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/DivByZeroException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class DivByZeroException extends ExpressionException { 4 | public DivByZeroException() { 5 | super("Division by zero"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/DivOverflowException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class DivOverflowException extends OverflowException { 4 | public DivOverflowException(int left, int right) { 5 | super("Divide", left + " " + right); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/ExceptionsPowLog2Test.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public class ExceptionsPowLog2Test extends ExceptionsTest { 9 | private static final Reason NEG_LOG = new Reason("Logarithm of negative value"); 10 | 11 | protected ExceptionsPowLog2Test() { 12 | unary.add(op("log2", ExceptionsPowLog2Test::log2)); 13 | unary.add(op("pow2", ExceptionsPowLog2Test::pow2)); 14 | 15 | tests.addAll(List.of( 16 | op("log2 10", (x, y, z) -> 3), 17 | op("log2 -4", (x, y, z) -> error(NEG_LOG)), 18 | op("log2-5", (x, y, z) -> error(NEG_LOG)), 19 | op("pow2 4", (x, y, z) -> 16), 20 | op("pow2 8", (x, y, z) -> 256), 21 | op("pow2 x * y * z", (x, y, z) -> pow2(x) * y * z), 22 | op("pow2(x * y * z)", (x, y, z) -> pow2(x * y * z)) 23 | )); 24 | parsingTest.addAll(List.of( 25 | parseExample("hello"), 26 | parseExample("log2()"), 27 | parseExample("log2(1, 2)"), 28 | parseExample("lgg 1"), 29 | parseExample("log2 *"), 30 | parseExample("log2x") 31 | )); 32 | } 33 | 34 | private static long pow2(final long a) { 35 | return 0 <= a && a <= 31 ? (long) Math.pow(2, a) : error(OVERFLOW); 36 | } 37 | 38 | private static long log2(final long a) { 39 | return a <= 0 ? error(NEG_LOG) : (long) (Math.log(a) / Math.log(2)); 40 | } 41 | 42 | public static void main(final String[] args) { 43 | new ExceptionsPowLog2Test().run(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/ExpressionException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class ExpressionException extends RuntimeException { 4 | public ExpressionException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/LogarithmBaseException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class LogarithmBaseException extends ExpressionException { 4 | public LogarithmBaseException(int left, int right) { 5 | super(left + " // " + right + " is undefined"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/Main.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | var res = new ExpressionParser().parse(sc.nextLine()); 9 | System.out.println(res); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/MultiplyOverflowException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class MultiplyOverflowException extends OverflowException { 4 | public MultiplyOverflowException(int left, int right) { 5 | super("Multiply", left + " " + right); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/NegateOverflowException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class NegateOverflowException extends OverflowException { 4 | public NegateOverflowException(int a) { 5 | super("Minus", Integer.toString(a)); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/NegatePowException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class NegatePowException extends ExpressionException { 4 | public NegatePowException(int left, int right) { 5 | super(left + "^" + right + " is undefined"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/NegativeLogarithm.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class NegativeLogarithm extends ExpressionException { 4 | public NegativeLogarithm(int right) { 5 | super("Logarithm of negative value:" + right); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/OverflowException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class OverflowException extends ExpressionException { 4 | public OverflowException(String where, String what) { 5 | super(where + " overflowed by " + what); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/Parser.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.TripleExpression; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public interface Parser { 9 | TripleExpression parse(String expression) throws /* Change me */ Exception; 10 | } 11 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/ParserException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class ParserException extends RuntimeException { 4 | public ParserException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/Power2.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | public class Power2 extends AbstractCheckedUnoOperator { 6 | public Power2(CommonExpression in) { 7 | super(in); 8 | } 9 | 10 | @Override 11 | protected String getView() { 12 | return "pow2 "; 13 | } 14 | 15 | @Override 16 | protected int getResult(int x) { 17 | if (x < 0 || x > 31) { 18 | throw new PowerOverflowException(2, x); 19 | } 20 | return (1 << x); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/PowerOverflowException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class PowerOverflowException extends OverflowException { 4 | public PowerOverflowException(int left, int right) { 5 | super("Power", left + " " + right); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/SubtractOverflowException.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | public class SubtractOverflowException extends OverflowException { 4 | public SubtractOverflowException(int a, int b) { 5 | super("Subtract", a + " " + b); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Exceptions/src/expression/exceptions/Variable.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.CommonExpression; 4 | 5 | public class Variable implements CommonExpression { 6 | private final String name; 7 | 8 | public Variable(String name) { 9 | this.name = name; 10 | } 11 | 12 | @Override 13 | public int evaluate(int x) throws ArithmeticException { 14 | return x; 15 | } 16 | 17 | @Override 18 | public String toString() { 19 | return name; 20 | } 21 | 22 | @Override 23 | public int evaluate(int x, int y, int z) { 24 | switch (name) { 25 | case "x": 26 | return x; 27 | case "y": 28 | return y; 29 | case "z": 30 | return z; 31 | } 32 | return -1; //TODO 33 | } 34 | 35 | @Override 36 | public boolean equals(Object obj) { 37 | if (obj != null && getClass() == obj.getClass()) { 38 | return name.equals(((Variable) obj).name); 39 | } 40 | return false; 41 | } 42 | 43 | @Override 44 | public int hashCode() { 45 | return name.hashCode(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Exceptions/src/expression/parser/Either.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | import java.util.function.Function; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public interface Either { 9 | Either flatMapRight(final Function> f); 10 | 11 | boolean isRight(); 12 | 13 | L getLeft(); 14 | R getRight(); 15 | 16 | static Either right(final R value) { 17 | return new Either<>() { 18 | 19 | @Override 20 | public Either flatMapRight(final Function> f) { 21 | return f.apply(value); 22 | } 23 | 24 | @Override 25 | public boolean isRight() { 26 | return true; 27 | } 28 | 29 | @Override 30 | public L getLeft() { 31 | return null; 32 | } 33 | 34 | @Override 35 | public R getRight() { 36 | return value; 37 | } 38 | }; 39 | } 40 | 41 | static Either left(final L value) { 42 | return new Either<>() { 43 | 44 | @Override 45 | public Either flatMapRight(final Function> f) { 46 | return left(value); 47 | } 48 | 49 | @Override 50 | public boolean isRight() { 51 | return false; 52 | } 53 | 54 | @Override 55 | public L getLeft() { 56 | return value; 57 | } 58 | 59 | @Override 60 | public R getRight() { 61 | return null; 62 | } 63 | }; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Exceptions/src/expression/parser/Parser.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | import expression.TripleExpression; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public interface Parser { 9 | TripleExpression parse(String expression); 10 | } 11 | -------------------------------------------------------------------------------- /Exceptions/src/expression/parser/Token.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | public enum Token { 4 | ADD, SUB, MUL, DIV, POW, LOG, LOG2, POW2, VAR, CONST, BRACKET_OPEN, BRACKET_CLOSE, END, UNDEFINED 5 | } 6 | -------------------------------------------------------------------------------- /Expression/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml -------------------------------------------------------------------------------- /Expression/.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /Expression/.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | -------------------------------------------------------------------------------- /Expression/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Expression/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Expression/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Expression/Expression.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Expression/out/production/Expression/META-INF/Expression.kotlin_module: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /Expression/src/base/Asserts.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.List; 4 | import java.util.Locale; 5 | import java.util.Objects; 6 | 7 | /** 8 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 9 | */ 10 | public class Asserts { 11 | static { 12 | Locale.setDefault(Locale.US); 13 | } 14 | 15 | public static void assertEquals(final String message, final Object expected, final Object actual) { 16 | assertTrue(String.format("%s:%n expected `%s`,%n actual `%s`", message, expected, actual), Objects.equals(expected, actual)); 17 | } 18 | 19 | public static void assertEquals(final String message, final List expected, final List actual) { 20 | for (int i = 0; i < Math.min(expected.size(), actual.size()); i++) { 21 | assertEquals(message + ":" + (i + 1), expected.get(i), actual.get(i)); 22 | } 23 | assertEquals(message + ": Number of items", expected.size(), actual.size()); 24 | } 25 | 26 | public static void assertTrue(final String message, final boolean value) { 27 | if (!value) { 28 | throw error("%s", message); 29 | } 30 | } 31 | 32 | public static void assertEquals(final String message, final double expected, final double actual, final double precision) { 33 | final double error = Math.abs(expected - actual); 34 | assertTrue( 35 | String.format("%s: expected %f, found %f", message, expected, actual), 36 | error <= precision || (Math.abs(expected) >= 1 && error / Math.abs(expected) < precision) 37 | ); 38 | } 39 | 40 | public static void assertSame(final String message, final Object expected, final Object actual) { 41 | assertTrue(String.format("%s: expected same objects: %s and %s", message, expected, actual), expected == actual); 42 | } 43 | 44 | protected static void checkAssert(final Class c) { 45 | if (!c.desiredAssertionStatus()) { 46 | throw error("You should enable assertions by running 'java -ea %s'", c.getName()); 47 | } 48 | } 49 | 50 | public static AssertionError error(final String format, final Object... args) { 51 | return new AssertionError(String.format(format, args)); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Expression/src/base/MainFilesChecker.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.List; 8 | 9 | /** 10 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 11 | */ 12 | public class MainFilesChecker extends MainChecker { 13 | public MainFilesChecker(final String className) { 14 | super(className); 15 | } 16 | 17 | private Path getFile(final String suffix) { 18 | return Paths.get(String.format("test%d.%s", counter.getTest() + 1, suffix)); 19 | } 20 | 21 | protected List runFiles(final List input) { 22 | try { 23 | final Path inf = getFile("in"); 24 | final Path ouf = getFile("out"); 25 | Files.write(inf, input); 26 | run(inf.toString(), ouf.toString()); 27 | final List output = Files.readAllLines(ouf); 28 | Files.delete(inf); 29 | Files.delete(ouf); 30 | return output; 31 | } catch (IOException e) { 32 | throw new AssertionError(e); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Expression/src/base/MainStdChecker.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.io.*; 4 | import java.util.List; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class MainStdChecker extends MainChecker { 10 | 11 | public MainStdChecker(final String className) { 12 | super(className); 13 | } 14 | 15 | protected List runStd(final List input) { 16 | final ByteArrayOutputStream baos = new ByteArrayOutputStream(); 17 | try (final PrintWriter writer = new PrintWriter(baos)) { 18 | input.forEach(writer::println); 19 | } 20 | 21 | final InputStream oldIn = System.in; 22 | try { 23 | System.setIn(new ByteArrayInputStream(baos.toByteArray())); 24 | return runComment(String.format("<%d input lines>", input.size())); 25 | } finally { 26 | System.setIn(oldIn); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Expression/src/base/Pair.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public class Pair { 9 | public final F first; 10 | public final S second; 11 | 12 | public Pair(final F first, final S second) { 13 | this.first = first; 14 | this.second = second; 15 | } 16 | 17 | public static Pair of(final F first, final S second) { 18 | return new Pair<>(first, second); 19 | } 20 | 21 | public static Pair of(final Map.Entry e) { 22 | return of(e.getKey(), e.getValue()); 23 | } 24 | 25 | @Override 26 | public boolean equals(final Object o) { 27 | if (this == o) return true; 28 | if (o == null || getClass() != o.getClass()) return false; 29 | 30 | final Pair pair = (Pair) o; 31 | 32 | return first.equals(pair.first) && second.equals(pair.second); 33 | } 34 | 35 | @Override 36 | public int hashCode() { 37 | int result = first.hashCode(); 38 | result = 31 * result + second.hashCode(); 39 | return result; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return first + ": " + second; 45 | } 46 | 47 | public F getFirst() { 48 | return first; 49 | } 50 | 51 | public S getSecond() { 52 | return second; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Expression/src/base/Randomized.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class Randomized { 10 | public static final String ENGLISH = "abcdefghijklmnopqrstuvwxyz"; 11 | public static final String RUSSIAN = "абвгдеежзийклмнопрстуфхцчшщъыьэюя"; 12 | public static final String GREEK = "αβγŋδεζηθικλμνξοπρτυφχψω"; 13 | 14 | public final Random random = new Random(8045702385702345702L); 15 | 16 | public String randomString(final String chars) { 17 | return randomChar(chars) + (random.nextBoolean() ? "" : randomString(chars)); 18 | } 19 | 20 | public char randomChar(final String chars) { 21 | return chars.charAt(random.nextInt(chars.length())); 22 | } 23 | 24 | public String randomString(final String chars, final int length) { 25 | final StringBuilder string = new StringBuilder(); 26 | for (int i = 0; i < length; i++) { 27 | string.append(randomChar(chars)); 28 | } 29 | return string.toString(); 30 | } 31 | 32 | public String randomString(final String chars, final int minLength, int maxLength) { 33 | return randomString(chars, randomInt(minLength, maxLength + 1)); 34 | } 35 | 36 | public int randomInt(final int min, final int max) { 37 | return random.nextInt(max - min) + min; 38 | } 39 | 40 | @SafeVarargs 41 | public final T randomItem(final T... items) { 42 | return items[random.nextInt(items.length)]; 43 | } 44 | 45 | public final T randomItem(final List items) { 46 | return items.get(random.nextInt(items.size())); 47 | } 48 | 49 | public Random getRandom() { 50 | return random; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Expression/src/expression/AbstractBinaryOperator.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | import java.util.Objects; 4 | 5 | public abstract class AbstractBinaryOperator implements CommonExpression { 6 | protected final CommonExpression left, right; 7 | 8 | public AbstractBinaryOperator(CommonExpression left, CommonExpression right) { 9 | this.left = left; 10 | this.right = right; 11 | } 12 | 13 | protected abstract String getView(); 14 | protected abstract int getResult(int left, int right); 15 | 16 | @Override 17 | final public String toString() { 18 | StringBuilder res = new StringBuilder(); 19 | res.append("(").append(left).append(" "); 20 | res.append(getView()); 21 | res.append(" ").append(right).append(")"); 22 | return res.toString(); 23 | } 24 | 25 | @Override 26 | final public String toMiniString() { 27 | return toString(); 28 | } 29 | 30 | @Override 31 | final public int evaluate(int x) throws ArithmeticException { 32 | return getResult(left.evaluate(x), right.evaluate(x)); 33 | } 34 | 35 | @Override 36 | final public int evaluate(int x, int y, int z) { 37 | return getResult(left.evaluate(x, y, z), right.evaluate(x, y, z)); 38 | } 39 | 40 | @Override 41 | final public boolean equals(Object obj) { 42 | if (obj != null && getClass() == obj.getClass()) { 43 | return ((AbstractBinaryOperator)obj).left.equals(left) 44 | && ((AbstractBinaryOperator)obj).right.equals(right); 45 | } 46 | return false; 47 | } 48 | 49 | @Override 50 | final public int hashCode() { 51 | return Objects.hash(getClass(), left, right); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Expression/src/expression/AbstractUnoOperator.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | import java.util.Objects; 4 | 5 | public abstract class AbstractUnoOperator implements CommonExpression { 6 | protected final CommonExpression in; 7 | 8 | public AbstractUnoOperator(CommonExpression in) { 9 | this.in = in; 10 | } 11 | 12 | protected abstract String getView(); 13 | protected abstract int getResult(int in); 14 | 15 | @Override 16 | final public String toString() { 17 | return getView() + in.toString(); 18 | } 19 | 20 | @Override 21 | final public int evaluate(int x) { 22 | return getResult(in.evaluate(x)); 23 | } 24 | 25 | @Override 26 | final public int evaluate(int x, int y, int z) { 27 | return getResult(in.evaluate(x, y, z)); 28 | } 29 | 30 | @Override 31 | final public boolean equals(Object obj) { 32 | if (obj != null && getClass() == obj.getClass()) { 33 | return in.equals(((AbstractUnoOperator)obj).in); 34 | } 35 | return false; 36 | } 37 | 38 | @Override 39 | final public int hashCode() { 40 | return Objects.hash(getClass(), in); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Expression/src/expression/Add.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public class Add extends AbstractBinaryOperator { 4 | public Add(CommonExpression left, CommonExpression right) { 5 | super(left, right); 6 | } 7 | 8 | @Override 9 | protected String getView() { 10 | return "+"; 11 | } 12 | 13 | @Override 14 | protected int getResult(int left, int right) { 15 | 16 | return left + right; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Expression/src/expression/BaseTest.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | import base.Asserts; 4 | import base.TestCounter; 5 | 6 | import java.util.*; 7 | 8 | /** 9 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 10 | */ 11 | public abstract strictfp class BaseTest extends Asserts { 12 | protected final Random random = new Random(7240958270485L); 13 | 14 | protected final TestCounter counter = new TestCounter(); 15 | 16 | protected BaseTest() { 17 | Locale.setDefault(Locale.US); 18 | 19 | checkAssert(getClass()); 20 | } 21 | 22 | protected T random(final List variants) { 23 | return variants.get(random.nextInt(variants.size())); 24 | } 25 | 26 | protected int randomInt(final int n) { 27 | return random.nextInt(n); 28 | } 29 | 30 | public void run() { 31 | System.out.println("=== Testing " + getClass().getSimpleName()); 32 | test(); 33 | counter.printStatus(getClass()); 34 | } 35 | 36 | protected abstract void test(); 37 | 38 | @SafeVarargs 39 | protected static List list(final T... items) { 40 | return new ArrayList<>(Arrays.asList(items)); 41 | } 42 | 43 | protected static void addRange(final List values, final int d, final int c) { 44 | for (int i = -d; i <= d; i++) { 45 | values.add(c + i); 46 | } 47 | } 48 | 49 | public static final class Op { 50 | public final String name; 51 | public final T f; 52 | 53 | private Op(final String name, final T f) { 54 | this.name = name; 55 | this.f = f; 56 | } 57 | } 58 | 59 | public static Op op(final String name, final T f) { 60 | return new Op<>(name, f); 61 | } 62 | 63 | public static int mode(final String[] args, final String... modes) { 64 | if (args.length != 1) { 65 | throw error("Single argument expected. Supported modes: %s", Arrays.asList(modes)); 66 | } 67 | final int index = List.of(modes).indexOf(args[0]); 68 | if (index < 0) { 69 | throw error("Invalid mode '%s'. Supported moves: %s", args[0], Arrays.asList(modes)); 70 | } 71 | return index; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /Expression/src/expression/CommonExpression.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public interface CommonExpression extends Expression, TripleExpression {} 4 | -------------------------------------------------------------------------------- /Expression/src/expression/Const.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public class Const implements CommonExpression { 4 | private final int val; 5 | 6 | public Const(int val) { 7 | this.val = val; 8 | } 9 | 10 | @Override 11 | public String toString() { 12 | return Integer.toString(val); 13 | } 14 | 15 | @Override 16 | public int evaluate(int x) throws ArithmeticException { 17 | return val; 18 | } 19 | 20 | @Override 21 | public int evaluate(int x, int y, int z) { 22 | return val; 23 | } 24 | 25 | @Override 26 | public boolean equals(Object obj) { 27 | if (obj != null && getClass() == obj.getClass()) { 28 | return val == ((Const) obj).val; 29 | } 30 | return false; 31 | } 32 | 33 | @Override 34 | public int hashCode() { 35 | return val; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Expression/src/expression/Divide.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public class Divide extends AbstractBinaryOperator { 4 | public Divide(CommonExpression left, CommonExpression right) { 5 | super(left, right); 6 | } 7 | 8 | @Override 9 | protected String getView() { 10 | return "/"; 11 | } 12 | 13 | @Override 14 | protected int getResult(int left, int right) { 15 | return left / right; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Expression/src/expression/Expression.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public interface Expression extends ToMiniString { 7 | int evaluate(int x) throws ArithmeticException; 8 | } 9 | -------------------------------------------------------------------------------- /Expression/src/expression/Log.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public class Log extends AbstractBinaryOperator { 4 | public Log(CommonExpression left, CommonExpression right) { 5 | super(left, right); 6 | } 7 | 8 | @Override 9 | protected String getView() { 10 | return "//"; 11 | } 12 | 13 | @Override 14 | protected int getResult(int left, int right) { 15 | int res = 0; 16 | while (left > 1) { 17 | left /= right; 18 | res++; 19 | } 20 | return res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Expression/src/expression/Log2.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public class Log2 extends AbstractUnoOperator { 4 | public Log2(CommonExpression in) { 5 | super(in); 6 | } 7 | 8 | @Override 9 | protected String getView() { 10 | return "log2 "; 11 | } 12 | 13 | @Override 14 | protected int getResult(int x) { 15 | int res = 0; 16 | while (x > 1) { 17 | res++; 18 | x /= 2; 19 | } 20 | return res; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Expression/src/expression/Minus.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public class Minus extends AbstractUnoOperator { 4 | public Minus(CommonExpression in) { 5 | super(in); 6 | } 7 | 8 | @Override 9 | protected String getView() { 10 | return "-"; 11 | } 12 | 13 | @Override 14 | protected int getResult(int in) { 15 | return -in; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Expression/src/expression/Multiply.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public class Multiply extends AbstractBinaryOperator { 4 | public Multiply(CommonExpression left, CommonExpression right) { 5 | super(left, right); 6 | } 7 | 8 | @Override 9 | protected String getView() { 10 | return "*"; 11 | } 12 | 13 | @Override 14 | protected int getResult(int left, int right) { 15 | return left * right; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Expression/src/expression/Power.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public class Power extends AbstractBinaryOperator { 4 | public Power(CommonExpression left, CommonExpression right) { 5 | super(left, right); 6 | } 7 | 8 | @Override 9 | protected String getView() { 10 | return "**"; 11 | } 12 | 13 | @Override 14 | protected int getResult(int left, int right) { 15 | int res = 1; 16 | while (right != 0) { 17 | if ((right & 1) == 1) { 18 | right--; 19 | res *= left; 20 | } 21 | res *= res; 22 | left /= 2; 23 | } 24 | return res; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Expression/src/expression/Power2.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public class Power2 extends AbstractUnoOperator { 4 | public Power2(CommonExpression in) { 5 | super(in); 6 | } 7 | 8 | @Override 9 | protected String getView() { 10 | return "pow2 "; 11 | } 12 | 13 | @Override 14 | protected int getResult(int x) { 15 | return (1 << x); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Expression/src/expression/Subtract.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public class Subtract extends AbstractBinaryOperator { 4 | public Subtract(CommonExpression left, CommonExpression right) { 5 | super(left, right); 6 | } 7 | 8 | @Override 9 | protected String getView() { 10 | return "-"; 11 | } 12 | 13 | @Override 14 | protected int getResult(int left, int right) { 15 | return left - right; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Expression/src/expression/ToMiniString.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public interface ToMiniString { 7 | default String toMiniString() { 8 | return toString(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Expression/src/expression/TripleExpression.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public interface TripleExpression extends ToMiniString { 7 | int evaluate(int x, int y, int z); 8 | } 9 | -------------------------------------------------------------------------------- /Expression/src/expression/Variable.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | public class Variable implements CommonExpression { 4 | private final String name; 5 | 6 | public Variable(String name) { 7 | this.name = name; 8 | } 9 | 10 | @Override 11 | public int evaluate(int x) throws ArithmeticException { 12 | return x; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return name; 18 | } 19 | 20 | @Override 21 | public int evaluate(int x, int y, int z) { 22 | switch (name) { 23 | case "x": 24 | return x; 25 | case "y": 26 | return y; 27 | case "z": 28 | return z; 29 | } 30 | return -1; //TODO 31 | } 32 | 33 | @Override 34 | public boolean equals(Object obj) { 35 | if (obj != null && getClass() == obj.getClass()) { 36 | return name.equals(((Variable) obj).name); 37 | } 38 | return false; 39 | } 40 | 41 | @Override 42 | public int hashCode() { 43 | return name.hashCode(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Expression/src/expression/parser/Either.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | import java.util.function.Function; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public interface Either { 9 | Either flatMapRight(final Function> f); 10 | 11 | boolean isRight(); 12 | 13 | L getLeft(); 14 | R getRight(); 15 | 16 | static Either right(final R value) { 17 | return new Either<>() { 18 | 19 | @Override 20 | public Either flatMapRight(final Function> f) { 21 | return f.apply(value); 22 | } 23 | 24 | @Override 25 | public boolean isRight() { 26 | return true; 27 | } 28 | 29 | @Override 30 | public L getLeft() { 31 | return null; 32 | } 33 | 34 | @Override 35 | public R getRight() { 36 | return value; 37 | } 38 | }; 39 | } 40 | 41 | static Either left(final L value) { 42 | return new Either<>() { 43 | 44 | @Override 45 | public Either flatMapRight(final Function> f) { 46 | return left(value); 47 | } 48 | 49 | @Override 50 | public boolean isRight() { 51 | return false; 52 | } 53 | 54 | @Override 55 | public L getLeft() { 56 | return value; 57 | } 58 | 59 | @Override 60 | public R getRight() { 61 | return null; 62 | } 63 | }; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Expression/src/expression/parser/Main.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Scanner in = new Scanner(System.in); 8 | ExpressionParser parser = new ExpressionParser(); 9 | var res = parser.parse(in.nextLine()); 10 | System.out.println("x" + " ".repeat(10) +"f"); 11 | for (int x = 0; x < 11; x++) { 12 | System.out.println(x + " ".repeat(10) + res.evaluate(x)); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Expression/src/expression/parser/Parser.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | import expression.TripleExpression; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public interface Parser { 9 | TripleExpression parse(String expression); 10 | } 11 | -------------------------------------------------------------------------------- /Expression/src/expression/parser/ParserAbsSquareTest.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author Georgiy Korneev 7 | */ 8 | public class ParserAbsSquareTest extends ParserShiftsTest { 9 | protected ParserAbsSquareTest() { 10 | unary.add(op("abs", Math::abs)); 11 | unary.add(op("square", a -> a * a)); 12 | 13 | tests.addAll(List.of( 14 | op("abs -5", (x, y, z) -> 5L), 15 | op("abs (x - y)", (x, y, z) -> Math.abs(x - y)), 16 | op("x - abs -y", (x, y, z) -> x - Math.abs(-y)), 17 | op("abs -x", (x, y, z) -> Math.abs(-x)), 18 | op("abs(x+y)", (x, y, z) -> Math.abs(x + y)), 19 | op("square -5", (x, y, z) -> 25L), 20 | op("square (x - y)", (x, y, z) -> (x - y) * (x - y)), 21 | op("x - square y", (x, y, z) -> x - y * y), 22 | op("square -x", (x, y, z) -> x * x), 23 | op("square(x+y)", (x, y, z) -> (x + y) * (x + y)) 24 | )); 25 | } 26 | 27 | public static void main(final String[] args) { 28 | new ParserAbsSquareTest().run(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Expression/src/expression/parser/ParserReverseDigitsTest.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | import java.util.List; 4 | import java.util.function.LongBinaryOperator; 5 | import java.util.stream.LongStream; 6 | 7 | /** 8 | * @author Georgiy Korneev 9 | */ 10 | public class ParserReverseDigitsTest extends ParserShiftsTest { 11 | protected ParserReverseDigitsTest() { 12 | unary.add(op("reverse", ParserReverseDigitsTest::reverse)); 13 | unary.add(op("digits", ParserReverseDigitsTest::digits)); 14 | 15 | tests.addAll(List.of( 16 | op("reverse 12345", (x, y, z) -> 54321L), 17 | op("reverse -12345", (x, y, z) -> -54321L), 18 | op("reverse (x - y)", (x, y, z) -> reverse(x - y)), 19 | op("x - reverse -y", (x, y, z) -> x - reverse(-y)), 20 | op("reverse -x", (x, y, z) -> reverse(-x)), 21 | op("reverse(x+y)", (x, y, z) -> reverse(x + y)), 22 | op("digits -12345", (x, y, z) -> 15L), 23 | op("digits (x - y)", (x, y, z) -> digits(x - y)), 24 | op("x - digits y", (x, y, z) -> x - digits(y)), 25 | op("digits -x", (x, y, z) -> digits(-x)), 26 | op("digits(x+y)", (x, y, z) -> digits(x + y)) 27 | )); 28 | } 29 | 30 | private static long digits(final long v) { 31 | return Math.abs(reduce(v, Long::sum)); 32 | } 33 | 34 | private static long reverse(final long v) { 35 | return reduce(v, (a, b) -> a * 10 + b); 36 | } 37 | 38 | private static long reduce(final long v, final LongBinaryOperator op) { 39 | return LongStream.iterate(v, n -> n != 0, n -> n / 10).map(n -> n % 10).reduce(0, op); 40 | } 41 | 42 | public static void main(final String[] args) { 43 | new ParserReverseDigitsTest().run(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Expression/src/expression/parser/ParserShiftsTest.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author Georgiy Korneev 7 | */ 8 | public class ParserShiftsTest extends ParserTest { 9 | protected ParserShiftsTest() { 10 | levels.add(0, list( 11 | op("<<", (a, b) -> (int) a << (int) b), 12 | op(">>", (a, b) -> (int) a >> (int) b) 13 | )); 14 | 15 | tests.addAll(List.of( 16 | op("1 << 5 + 3", (x, y, z) -> 256L), 17 | op("x + y << z", (x, y, z) -> (int) (x + y) << (int) z), 18 | op("x * y << z", (x, y, z) -> (int) (x * y) << (int) z), 19 | op("x << y << z", (x, y, z) -> (int) x << (int) y << (int) z), 20 | op("1024 >> 5 + 3", (x, y, z) -> 4L), 21 | op("x + y >> z", (x, y, z) -> x + y >> z), 22 | op("x * y >> z", (x, y, z) -> x * y >> z), 23 | op("x >> y >> z", (x, y, z) -> x >> y >> z) 24 | )); 25 | } 26 | 27 | public static void main(final String[] args) { 28 | new ParserShiftsTest().run(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Expression/src/expression/parser/Token.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | enum Token { 4 | ADD, SUB, MUL, DIV, POW, LOG, LOG2, POW2, VAR, CONST, BRACKET_OPEN, BRACKET_CLOSE, END 5 | } 6 | -------------------------------------------------------------------------------- /Expression/src/expression/parser/Tokenizer.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | public class Tokenizer { 4 | private String source; 5 | private int curPos = 0; 6 | private final String[] search = {"**", "//", "+", "-", "*", "/", "pow2", "log2", "(", ")"}; 7 | private final Token[] token = { 8 | Token.POW, Token.LOG, Token.ADD, Token.SUB, 9 | Token.MUL, Token.DIV, Token.POW2, Token.LOG2, 10 | Token.BRACKET_OPEN, Token.BRACKET_CLOSE 11 | }; 12 | private int N = search.length; 13 | private String lastToken; 14 | 15 | Tokenizer(String source) { 16 | this.source = source; 17 | } 18 | 19 | private void skipBlanks() { 20 | while (curPos < source.length() 21 | && (test(' ') || test('\t') || test('\n') || test('\r'))) { 22 | // skip 23 | } 24 | } 25 | 26 | private boolean test(char c) { 27 | if (source.charAt(curPos) == c) { 28 | curPos++; 29 | return true; 30 | } 31 | return false; 32 | } 33 | 34 | private boolean isDigit(char c) { 35 | return c >= '0' && c <= '9'; 36 | } 37 | 38 | private String getConst() { 39 | StringBuilder res = new StringBuilder(); 40 | while (curPos < source.length() && isDigit(source.charAt(curPos))) { 41 | res.append(source.charAt(curPos++)); 42 | } 43 | return lastToken = res.toString(); 44 | } 45 | 46 | Token nextToken() { 47 | skipBlanks(); 48 | if (curPos >= source.length()) { 49 | return Token.END; 50 | } 51 | if (isDigit(source.charAt(curPos))) { 52 | getConst(); 53 | return Token.CONST; 54 | } 55 | for (int i = 0; i < N; i++) { 56 | if (source.startsWith(search[i], curPos)) { 57 | lastToken = source.substring(curPos, curPos + search[i].length()); 58 | curPos += search[i].length(); 59 | return token[i]; 60 | } 61 | } 62 | if (test('x') || test('y') || test('z')) { 63 | lastToken = Character.toString(source.charAt(curPos - 1)); 64 | return Token.VAR; 65 | } 66 | return Token.END; 67 | } 68 | 69 | String getLastToken() { 70 | return lastToken; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /GenericExpression/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml -------------------------------------------------------------------------------- /GenericExpression/.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /GenericExpression/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /GenericExpression/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /GenericExpression/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /GenericExpression/GenericExpression.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /GenericExpression/src/base/Asserts.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.Arrays; 4 | import java.util.Locale; 5 | import java.util.Objects; 6 | 7 | /** 8 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 9 | */ 10 | public class Asserts { 11 | static { 12 | Locale.setDefault(Locale.US); 13 | } 14 | 15 | public static void assertEquals(final String message, final Object expected, final Object actual) { 16 | final String reason = String.format( 17 | "%s:%n expected `%s`,%n actual `%s`", 18 | message, 19 | toString(expected), 20 | toString(actual) 21 | ); 22 | assertTrue(reason, Objects.deepEquals(expected, actual)); 23 | } 24 | 25 | private static String toString(final Object value) { 26 | final String result = Arrays.deepToString(new Object[]{value}); 27 | return result.substring(1, result.length() - 1); 28 | } 29 | 30 | public static void assertTrue(final String message, final boolean value) { 31 | if (!value) { 32 | throw new AssertionError(message); 33 | } 34 | } 35 | 36 | public static void assertEquals(final String message, final int expected, final int actual) { 37 | assertTrue(String.format("%s: Expected %d, found %d", message, expected, actual), actual == expected); 38 | } 39 | 40 | public static void assertEquals(final String message, final double precision, final double expected, final double actual) { 41 | assertTrue( 42 | String.format("%s: Expected %.12f, found %.12f", message, expected, actual), 43 | Math.abs(actual - expected) < precision 44 | || Math.abs(actual - expected) < precision * Math.abs(actual) 45 | || (Double.isNaN(actual) || Double.isInfinite(actual)) && 46 | (Double.isNaN(expected) || Double.isInfinite(expected)) 47 | || (Double.isNaN(expected) && actual == 0) 48 | ); 49 | } 50 | 51 | public static void checkAssert(final Class c) { 52 | if (!c.desiredAssertionStatus()) { 53 | throw error("You should enable assertions by running 'java -ea %s'", c.getName()); 54 | } 55 | } 56 | 57 | public static AssertionError error(final String format, final Object... args) { 58 | return new AssertionError(String.format(format, args)); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /GenericExpression/src/base/MainFilesChecker.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.List; 8 | 9 | /** 10 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 11 | */ 12 | public class MainFilesChecker extends MainChecker { 13 | public MainFilesChecker(final String className) { 14 | super(className); 15 | } 16 | 17 | private Path getFile(final String suffix) { 18 | return Paths.get(String.format("test%d.%s", counter.getTest() + 1, suffix)); 19 | } 20 | 21 | protected List runFiles(final List input) { 22 | try { 23 | final Path inf = getFile("in"); 24 | final Path ouf = getFile("out"); 25 | Files.write(inf, input); 26 | run(inf.toString(), ouf.toString()); 27 | final List output = Files.readAllLines(ouf); 28 | Files.delete(inf); 29 | Files.delete(ouf); 30 | return output; 31 | } catch (final IOException e) { 32 | throw new AssertionError(e); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /GenericExpression/src/base/Randomized.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class Randomized { 10 | public static final String ENGLISH = "abcdefghijklmnopqrstuvwxyz"; 11 | 12 | public final Random random = new Random(8045702385702345702L); 13 | 14 | public String randomString(final String chars) { 15 | return randomChar(chars) + (random.nextBoolean() ? "" : randomString(chars)); 16 | } 17 | 18 | public char randomChar(final String chars) { 19 | return chars.charAt(random.nextInt(chars.length())); 20 | } 21 | 22 | public String randomString(final String chars, final int length) { 23 | final StringBuilder string = new StringBuilder(); 24 | for (int i = 0; i < length; i++) { 25 | string.append(randomChar(chars)); 26 | } 27 | return string.toString(); 28 | } 29 | 30 | public String randomString(final String chars, final int minLength, int maxLength) { 31 | return randomString(chars, randomInt(minLength, maxLength + 1)); 32 | } 33 | 34 | public int randomInt(final int min, final int max) { 35 | return random.nextInt(max - min) + min; 36 | } 37 | 38 | @SafeVarargs 39 | public final T randomItem(final T... items) { 40 | return items[random.nextInt(items.length)]; 41 | } 42 | 43 | public final T randomItem(final List items) { 44 | return items.get(random.nextInt(items.size())); 45 | } 46 | 47 | public Random getRandom() { 48 | return random; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /GenericExpression/src/base/Triple.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public class Triple { 7 | private final F first; 8 | private final S second; 9 | private final T third; 10 | 11 | public Triple(final F first, final S second, final T third) { 12 | this.first = first; 13 | this.second = second; 14 | this.third = third; 15 | } 16 | 17 | public F first() { 18 | return first; 19 | } 20 | 21 | public S second() { 22 | return second; 23 | } 24 | 25 | public T third() { 26 | return third; 27 | } 28 | 29 | public static Triple of(final F first, final S second, final T third) { 30 | return new Triple<>(first, second, third); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/AbstractBinaryOperation.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | import expression.evaluator.Evaluator; 4 | 5 | public abstract class AbstractBinaryOperation implements TripleExpression { 6 | private TripleExpression first, second; 7 | 8 | AbstractBinaryOperation(TripleExpression first, TripleExpression second) { 9 | this.first = first; 10 | this.second = second; 11 | } 12 | 13 | protected abstract calc(T first, T second, Evaluator evaluator); 14 | } 15 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/BaseTest.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | import base.Asserts; 4 | import base.TestCounter; 5 | 6 | import java.util.*; 7 | 8 | /** 9 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 10 | */ 11 | public abstract strictfp class BaseTest extends Asserts { 12 | protected final Random random = new Random(7240958270485L); 13 | 14 | protected final TestCounter counter = new TestCounter(); 15 | 16 | protected BaseTest() { 17 | Locale.setDefault(Locale.US); 18 | 19 | checkAssert(getClass()); 20 | } 21 | 22 | protected T random(final List variants) { 23 | return variants.get(random.nextInt(variants.size())); 24 | } 25 | 26 | protected int randomInt(final int n) { 27 | return random.nextInt(n); 28 | } 29 | 30 | public void run() { 31 | System.out.println("=== Testing " + getClass().getSimpleName()); 32 | test(); 33 | counter.printStatus(getClass()); 34 | } 35 | 36 | protected abstract void test(); 37 | 38 | @SafeVarargs 39 | protected static List list(final T... items) { 40 | return new ArrayList<>(Arrays.asList(items)); 41 | } 42 | 43 | protected static void addRange(final List values, final int d, final int c) { 44 | for (int i = -d; i <= d; i++) { 45 | values.add(c + i); 46 | } 47 | } 48 | 49 | public static final class Op { 50 | public final String name; 51 | public final T f; 52 | 53 | private Op(final String name, final T f) { 54 | this.name = name; 55 | this.f = f; 56 | } 57 | } 58 | 59 | public static Op op(final String name, final T f) { 60 | return new Op<>(name, f); 61 | } 62 | 63 | public static int mode(final String[] args, final String... modes) { 64 | if (args.length != 1) { 65 | throw error("Single argument expected. Supported modes: %s", Arrays.asList(modes)); 66 | } 67 | final int index = List.of(modes).indexOf(args[0]); 68 | if (index < 0) { 69 | throw error("Invalid mode '%s'. Supported moves: %s", args[0], Arrays.asList(modes)); 70 | } 71 | return index; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/ToMiniString.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public interface ToMiniString { 7 | default String toMiniString() { 8 | return toString(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/TripleExpression.java: -------------------------------------------------------------------------------- 1 | package expression; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public interface TripleExpression extends ToMiniString { 7 | T evaluate(T x, T y, T z); 8 | } 9 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/evaluator/Evaluator.java: -------------------------------------------------------------------------------- 1 | package expression.evaluator; 2 | 3 | public interface Evaluator { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/exceptions/ExceptionsPowLog2Test.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public class ExceptionsPowLog2Test extends ExceptionsTest { 9 | private static final Reason NEG_LOG = new Reason("Logarithm of negative value"); 10 | 11 | protected ExceptionsPowLog2Test() { 12 | unary.add(op("log2", ExceptionsPowLog2Test::log2)); 13 | unary.add(op("pow2", ExceptionsPowLog2Test::pow2)); 14 | 15 | tests.addAll(List.of( 16 | op("log2 10", (x, y, z) -> 3), 17 | op("log2 -4", (x, y, z) -> error(NEG_LOG)), 18 | op("log2-5", (x, y, z) -> error(NEG_LOG)), 19 | op("pow2 4", (x, y, z) -> 16), 20 | op("pow2 8", (x, y, z) -> 256), 21 | op("pow2 x * y * z", (x, y, z) -> pow2(x) * y * z), 22 | op("pow2(x * y * z)", (x, y, z) -> pow2(x * y * z)) 23 | )); 24 | parsingTest.addAll(List.of( 25 | parseExample("hello"), 26 | parseExample("log2()"), 27 | parseExample("log2(1, 2)"), 28 | parseExample("lgg 1"), 29 | parseExample("log2 *"), 30 | parseExample("log2x") 31 | )); 32 | } 33 | 34 | private static long pow2(final long a) { 35 | return 0 <= a && a <= 31 ? (long) Math.pow(2, a) : error(OVERFLOW); 36 | } 37 | 38 | private static long log2(final long a) { 39 | return a <= 0 ? error(NEG_LOG) : (long) (Math.log(a) / Math.log(2)); 40 | } 41 | 42 | public static void main(final String[] args) { 43 | new ExceptionsPowLog2Test().run(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/exceptions/ExceptionsPowLogTest.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public class ExceptionsPowLogTest extends ExceptionsTest { 9 | private static final Reason POWER = new Reason("power"); 10 | private static final Reason LOG = new Reason("log"); 11 | 12 | protected ExceptionsPowLogTest() { 13 | levels.add(list( 14 | op("**", ExceptionsPowLogTest::power), 15 | op("//", ExceptionsPowLogTest::log) 16 | )); 17 | 18 | tests.addAll(List.of( 19 | op("2 ** 3", (x, y, z) -> 8), 20 | op("4 ** 3 ** 2", (x, y, z) -> 4096), 21 | op("2 ** 3 * 3", (x, y, z) -> 24), 22 | op("x ** (y * z)", (x, y, z) -> power(x, y * z)), 23 | op("2 ** x + 1", (x, y, z) -> power(2, x) + 1), 24 | op("-1 ** (3 ** x)", (x, y, z) -> x < 0 ? error(POWER) : -1), 25 | op("8 // 2", (x, y, z) -> 3), 26 | op("x // y", (x, y, z) -> log(x, y)) 27 | )); 28 | } 29 | 30 | private static long log(final long a, final long b) { 31 | try { 32 | final double result = Math.log(a) / Math.log(b); 33 | return a > 0 && b > 0 && result == result ? (long) result : error(LOG); 34 | } catch (final ArithmeticException e) { 35 | return error(LOG); 36 | } 37 | } 38 | 39 | private static long power(final long a, long b) { 40 | if (b < 0 || a == 0 && b == 0) { 41 | return error(POWER); 42 | } 43 | if (Math.abs(a) <= 1 && b > 2) { 44 | b = (b - 1) % 2 + 1; 45 | } 46 | 47 | double result = 1; 48 | for (int i = 0; i < b; i++) { 49 | result *= a; 50 | if (result < Integer.MIN_VALUE || Integer.MAX_VALUE < result) { 51 | return error(OVERFLOW); 52 | } 53 | } 54 | return (long) result; 55 | } 56 | 57 | public static void main(final String[] args) { 58 | new ExceptionsPowLogTest().run(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/exceptions/Parser.java: -------------------------------------------------------------------------------- 1 | package expression.exceptions; 2 | 3 | import expression.TripleExpression; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public interface Parser { 9 | TripleExpression parse(String expression) throws /* Change me */ Exception; 10 | } 11 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/generic/GenericLsTest.java: -------------------------------------------------------------------------------- 1 | package expression.generic; 2 | 3 | /** 4 | * Generic unchecked int, long, short test. 5 | * 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public class GenericLsTest extends GenericTest { 9 | public GenericLsTest() { 10 | ls( 11 | "10", 12 | (x, y, z) -> 10L, 13 | (x, y, z) -> s(10) 14 | ); 15 | ls( 16 | "x", 17 | (x, y, z) -> (long) x, 18 | (x, y, z) -> s(x) 19 | ); 20 | ls( 21 | "y + 2", 22 | (x, y, z) -> y + 2L, 23 | (x, y, z) -> s(y + 2) 24 | ); 25 | ls( 26 | "z / 2", 27 | (x, y, z) -> z / 2L, 28 | (x, y, z) -> s(z / 2) 29 | ); 30 | ls( 31 | "y / z", 32 | (x, y, z) -> y / (long) z, 33 | (x, y, z) -> s(y / z) 34 | ); 35 | ls( 36 | "100 * x * y * 100 + z", 37 | (x, y, z) -> 100L * x * y * 100 + z, 38 | (x, y, z) -> s(100 * x * y * 100 + z) 39 | ); 40 | ls( 41 | "x * y + (z - 1) / 10", 42 | (x, y, z) -> x * (long) y + (z - 1L) / 10, 43 | (x, y, z) -> s(x * y + (z - 1) / 10) 44 | ); 45 | } 46 | 47 | protected static short s(final int x) { 48 | return (short) x; 49 | } 50 | 51 | protected void ls(final String expression, final F fl, final F fs) { 52 | test(expression, "l", fl); 53 | test(expression, "s", (x, y, z) -> fs.apply((short) x, (short) y, (short) z)); 54 | } 55 | 56 | public static void main(final String[] args) { 57 | new GenericLsTest().run(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/generic/GenericTabulator.java: -------------------------------------------------------------------------------- 1 | package expression.generic; 2 | 3 | public class GenericTabulator implements Tabulator { 4 | @Override 5 | public Object[][][] tabulate(String mode, String expression, int x1, int x2, int y1, int y2, int z1, int z2) throws Exception { 6 | return new Object[0][][]; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/generic/GenericUfbTest.java: -------------------------------------------------------------------------------- 1 | package expression.generic; 2 | 3 | /** 4 | * Generic unchecked int, float, byte test. 5 | * 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public class GenericUfbTest extends GenericTest { 9 | public GenericUfbTest() { 10 | ufb( 11 | "10", 12 | (x, y, z) -> 10, 13 | (x, y, z) -> 10.0f, 14 | (x, y, z) -> b(10) 15 | ); 16 | ufb( 17 | "x", 18 | (x, y, z) -> x, 19 | (x, y, z) -> (float) x, 20 | (x, y, z) -> b(x) 21 | ); 22 | ufb( 23 | "y + 2", 24 | (x, y, z) -> y + 2, 25 | (x, y, z) -> y + 2.0f, 26 | (x, y, z) -> b(y + 2) 27 | ); 28 | ufb( 29 | "z / 2", 30 | (x, y, z) -> z / 2, 31 | (x, y, z) -> z / 2.0f, 32 | (x, y, z) -> b(z / 2) 33 | ); 34 | ufb( 35 | "y / z", 36 | (x, y, z) -> y / z, 37 | (x, y, z) -> y / (float) z, 38 | (x, y, z) -> b(y / z) 39 | ); 40 | ufb( 41 | "100 * x * y * 100 + z", 42 | (x, y, z) -> i(100 * x * y * 100 + z), 43 | (x, y, z) -> 100.0f * x * y * 100 + z, 44 | (x, y, z) -> b(100 * x * y * 100 + z) 45 | ); 46 | ufb( 47 | "x * y + (z - 1) / 10", 48 | (x, y, z) -> x * y + (z - 1) / 10, 49 | (x, y, z) -> x * (float) y + (z - 1) / 10.0f, 50 | (x, y, z) -> b(x * y + (z - 1) / 10) 51 | ); 52 | } 53 | 54 | protected static byte b(final int x) { 55 | return (byte) x; 56 | } 57 | 58 | protected void ufb(final String expression, final F fu, final F ff, final F fb) { 59 | test(expression, "u", fu); 60 | test(expression, "f", ff); 61 | test(expression, "b", (x, y, z) -> fb.apply((byte) x, (byte) y, (byte) z)); 62 | } 63 | 64 | public static void main(final String[] args) { 65 | new GenericUfbTest().run(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/generic/GenericUlsTest.java: -------------------------------------------------------------------------------- 1 | package expression.generic; 2 | 3 | /** 4 | * Generic unchecked int, long, short test. 5 | * 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public class GenericUlsTest extends GenericTest { 9 | public GenericUlsTest() { 10 | uls( 11 | "10", 12 | (x, y, z) -> 10, 13 | (x, y, z) -> 10L, 14 | (x, y, z) -> s(10) 15 | ); 16 | uls( 17 | "x", 18 | (x, y, z) -> x, 19 | (x, y, z) -> (long) x, 20 | (x, y, z) -> s(x) 21 | ); 22 | uls( 23 | "y + 2", 24 | (x, y, z) -> y + 2, 25 | (x, y, z) -> y + 2L, 26 | (x, y, z) -> s(y + 2) 27 | ); 28 | uls( 29 | "z / 2", 30 | (x, y, z) -> z / 2, 31 | (x, y, z) -> z / 2L, 32 | (x, y, z) -> s(z / 2) 33 | ); 34 | uls( 35 | "y / z", 36 | (x, y, z) -> y / z, 37 | (x, y, z) -> y / (long) z, 38 | (x, y, z) -> s(y / z) 39 | ); 40 | uls( 41 | "100 * x * y * 100 + z", 42 | (x, y, z) -> i(100 * x * y * 100 + z), 43 | (x, y, z) -> 100L * x * y * 100 + z, 44 | (x, y, z) -> s(100 * x * y * 100 + z) 45 | ); 46 | uls( 47 | "x * y + (z - 1) / 10", 48 | (x, y, z) -> x * y + (z - 1) / 10, 49 | (x, y, z) -> x * (long) y + (z - 1L) / 10, 50 | (x, y, z) -> s(x * y + (z - 1) / 10) 51 | ); 52 | } 53 | 54 | protected static short s(final int x) { 55 | return (short) x; 56 | } 57 | 58 | protected void uls(final String expression, final F fu, final F fl, final F fs) { 59 | test(expression, "u", fu); 60 | test(expression, "l", fl); 61 | test(expression, "s", (x, y, z) -> fs.apply((short) x, (short) y, (short) z)); 62 | } 63 | 64 | public static void main(final String[] args) { 65 | new GenericUlsTest().run(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/generic/Tabulator.java: -------------------------------------------------------------------------------- 1 | package expression.generic; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public interface Tabulator { 7 | Object[][][] tabulate(String mode, String expression, int x1, int x2, int y1, int y2, int z1, int z2) throws Exception; 8 | } 9 | -------------------------------------------------------------------------------- /GenericExpression/src/expression/parser/Either.java: -------------------------------------------------------------------------------- 1 | package expression.parser; 2 | 3 | import java.util.function.Function; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public interface Either { 9 | Either flatMapRight(final Function> f); 10 | 11 | boolean isRight(); 12 | 13 | L getLeft(); 14 | R getRight(); 15 | 16 | static Either right(final R value) { 17 | return new Either<>() { 18 | 19 | @Override 20 | public Either flatMapRight(final Function> f) { 21 | return f.apply(value); 22 | } 23 | 24 | @Override 25 | public boolean isRight() { 26 | return true; 27 | } 28 | 29 | @Override 30 | public L getLeft() { 31 | return null; 32 | } 33 | 34 | @Override 35 | public R getRight() { 36 | return value; 37 | } 38 | }; 39 | } 40 | 41 | static Either left(final L value) { 42 | return new Either<>() { 43 | 44 | @Override 45 | public Either flatMapRight(final Function> f) { 46 | return left(value); 47 | } 48 | 49 | @Override 50 | public boolean isRight() { 51 | return false; 52 | } 53 | 54 | @Override 55 | public L getLeft() { 56 | return value; 57 | } 58 | 59 | @Override 60 | public R getRight() { 61 | return null; 62 | } 63 | }; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /InterfaceQueue/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml -------------------------------------------------------------------------------- /InterfaceQueue/.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /InterfaceQueue/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /InterfaceQueue/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /InterfaceQueue/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /InterfaceQueue/InterfaceQueue.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /InterfaceQueue/out/production/InterfaceQueue/META-INF/InterfaceQueue.kotlin_module: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /InterfaceQueue/src/base/Asserts.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.Locale; 4 | import java.util.Objects; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class Asserts { 10 | static { 11 | Locale.setDefault(Locale.US); 12 | } 13 | 14 | public static void assertEquals(final String message, final Object expected, final Object actual) { 15 | assertTrue(String.format("%s:%n expected `%s`,%n actual `%s`", message, expected, actual), Objects.deepEquals(expected, actual)); 16 | } 17 | 18 | public static void assertTrue(final String message, final boolean value) { 19 | if (!value) { 20 | throw new AssertionError(message); 21 | } 22 | } 23 | 24 | public static void assertEquals(final String message, final int expected, final int actual) { 25 | assertTrue(String.format("%s: Expected %d, found %d", message, expected, actual), actual == expected); 26 | } 27 | 28 | public static void assertEquals(final String message, final double precision, final double expected, final double actual) { 29 | assertTrue( 30 | String.format("%s: Expected %.12f, found %.12f", message, expected, actual), 31 | Math.abs(actual - expected) < precision || 32 | Math.abs(actual - expected) < precision * Math.abs(actual) || 33 | (Double.isNaN(actual) || Double.isInfinite(actual)) && 34 | (Double.isNaN(expected) || Double.isInfinite(expected)) 35 | ); 36 | } 37 | 38 | public static void checkAssert(final Class c) { 39 | if (!c.desiredAssertionStatus()) { 40 | throw error("You should enable assertions by running 'java -ea %s'", c.getName()); 41 | } 42 | } 43 | 44 | public static AssertionError error(final String format, final Object... args) { 45 | return new AssertionError(String.format(format, args)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /InterfaceQueue/src/base/MainFilesChecker.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.List; 8 | 9 | /** 10 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 11 | */ 12 | public class MainFilesChecker extends MainChecker { 13 | public MainFilesChecker(final String className) { 14 | super(className); 15 | } 16 | 17 | private Path getFile(final String suffix) { 18 | return Paths.get(String.format("test%d.%s", counter.getTest() + 1, suffix)); 19 | } 20 | 21 | protected List runFiles(final List input) { 22 | try { 23 | final Path inf = getFile("in"); 24 | final Path ouf = getFile("out"); 25 | Files.write(inf, input); 26 | run(inf.toString(), ouf.toString()); 27 | final List output = Files.readAllLines(ouf); 28 | Files.delete(inf); 29 | Files.delete(ouf); 30 | return output; 31 | } catch (final IOException e) { 32 | throw new AssertionError(e); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /InterfaceQueue/src/base/Randomized.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class Randomized { 10 | public static final String ENGLISH = "abcdefghijklmnopqrstuvwxyz"; 11 | 12 | public final Random random = new Random(8045702385702345702L); 13 | 14 | public String randomString(final String chars) { 15 | return randomChar(chars) + (random.nextBoolean() ? "" : randomString(chars)); 16 | } 17 | 18 | public char randomChar(final String chars) { 19 | return chars.charAt(random.nextInt(chars.length())); 20 | } 21 | 22 | public String randomString(final String chars, final int length) { 23 | final StringBuilder string = new StringBuilder(); 24 | for (int i = 0; i < length; i++) { 25 | string.append(randomChar(chars)); 26 | } 27 | return string.toString(); 28 | } 29 | 30 | public String randomString(final String chars, final int minLength, int maxLength) { 31 | return randomString(chars, randomInt(minLength, maxLength + 1)); 32 | } 33 | 34 | public int randomInt(final int min, final int max) { 35 | return random.nextInt(max - min) + min; 36 | } 37 | 38 | @SafeVarargs 39 | public final T randomItem(final T... items) { 40 | return items[random.nextInt(items.length)]; 41 | } 42 | 43 | public final T randomItem(final List items) { 44 | return items.get(random.nextInt(items.size())); 45 | } 46 | 47 | public Random getRandom() { 48 | return random; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /InterfaceQueue/src/base/Triple.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public class Triple { 7 | private final F first; 8 | private final S second; 9 | private final T third; 10 | 11 | public Triple(final F first, final S second, final T third) { 12 | this.first = first; 13 | this.second = second; 14 | this.third = third; 15 | } 16 | 17 | public F first() { 18 | return first; 19 | } 20 | 21 | public S second() { 22 | return second; 23 | } 24 | 25 | public T third() { 26 | return third; 27 | } 28 | 29 | public static Triple of(final F first, final S second, final T third) { 30 | return new Triple<>(first, second, third); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /InterfaceQueue/src/queue/ArrayQueue.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | public class ArrayQueue extends AbstractQueue { 4 | private Object[] q = new Object[5]; 5 | private int head = 0, tail = 0; 6 | 7 | private int shift(int i, int x) { 8 | return ((i + x) % q.length + q.length) % q.length; 9 | } 10 | 11 | private void ensureCap() { 12 | Object[] nq = new Object[2 * size]; 13 | for (int i = 0; i < size; i++) { 14 | nq[i] = q[shift(i, head)]; 15 | } 16 | head = 0; 17 | tail = size; 18 | q = nq; 19 | } 20 | 21 | @Override 22 | protected void implEnqueue(Object x) { 23 | if (size + 1 >= q.length) { 24 | ensureCap(); 25 | } 26 | q[tail] = x; 27 | tail = shift(tail, 1); 28 | } 29 | 30 | @Override 31 | protected Object implDequeue() { 32 | Object ret = q[head]; 33 | head = shift(head, 1); 34 | return ret; 35 | } 36 | 37 | @Override 38 | protected Object implElement() { 39 | return q[head]; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /InterfaceQueue/src/queue/ArrayQueueDequeTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import java.util.function.Function; 4 | import java.util.stream.Stream; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class ArrayQueueDequeTest extends ArrayQueueTest { 10 | public ArrayQueueDequeTest(final Class type, final Function, T> reference) { 11 | super(type, reference); 12 | } 13 | 14 | public static void main(final String[] args) { 15 | new ArrayQueueDequeTest<>(QueueDeque.class, ReferenceQueueDeque::new).test(); 16 | } 17 | 18 | @Override 19 | protected void add(final T queue, final Object element) { 20 | if (random.nextBoolean()) { 21 | super.add(queue, element); 22 | } else { 23 | queue.push(element); 24 | } 25 | } 26 | 27 | @Override 28 | protected void check(final T queue) { 29 | if (random.nextBoolean()) { 30 | super.check(queue); 31 | } else { 32 | queue.peek(); 33 | } 34 | } 35 | 36 | @Override 37 | protected void remove(final T queue) { 38 | if (random.nextBoolean()) { 39 | super.remove(queue); 40 | } else { 41 | queue.remove(); 42 | } 43 | } 44 | 45 | protected interface QueueDeque extends Queue { 46 | void push(final Object element); 47 | Object peek(); 48 | Object remove(); 49 | } 50 | 51 | protected static class ReferenceQueueDeque extends ReferenceQueue implements QueueDeque { 52 | public ReferenceQueueDeque(final Stream elements) { 53 | super(elements); 54 | } 55 | 56 | @Override 57 | public void push(final Object element) { 58 | deque.addFirst(element); 59 | } 60 | 61 | @Override 62 | public Object peek() { 63 | return deque.getLast(); 64 | } 65 | 66 | @Override 67 | public Object remove() { 68 | return deque.removeLast(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /InterfaceQueue/src/queue/ArrayQueueToArrayTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import java.util.List; 4 | import java.util.stream.Stream; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class ArrayQueueToArrayTest extends ArrayQueueTest { 10 | public ArrayQueueToArrayTest() { 11 | super(ToArrayQueue.class, ReferenceToArrayQueue::new); 12 | } 13 | 14 | public static void main(final String[] args) { 15 | new ArrayQueueToArrayTest().test(); 16 | } 17 | 18 | @Override 19 | protected List linearTest(final ToArrayQueue queue) { 20 | queue.toArray(); 21 | return List.of(); 22 | } 23 | 24 | protected interface ToArrayQueue extends Queue { 25 | Object[] toArray(); 26 | } 27 | 28 | protected static class ReferenceToArrayQueue extends ReferenceQueue implements ToArrayQueue { 29 | public ReferenceToArrayQueue(final Stream elements) { 30 | super(elements); 31 | } 32 | 33 | @Override 34 | public Object[] toArray() { 35 | return deque.toArray(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /InterfaceQueue/src/queue/ArrayQueueToStrTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import java.util.List; 4 | import java.util.stream.Stream; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class ArrayQueueToStrTest extends ArrayQueueTest { 10 | public ArrayQueueToStrTest() { 11 | super(ToStrQueue.class, ReferenceToStrQueue::new); 12 | } 13 | 14 | public static void main(final String[] args) { 15 | new ArrayQueueToStrTest().test(); 16 | } 17 | 18 | @Override 19 | protected List linearTest(final ToStrQueue queue) { 20 | queue.toStr(); 21 | return List.of(); 22 | } 23 | 24 | protected interface ToStrQueue extends Queue { 25 | String toStr(); 26 | } 27 | 28 | protected static class ReferenceToStrQueue extends ReferenceQueue implements ToStrQueue { 29 | public ReferenceToStrQueue(final Stream elements) { 30 | super(elements); 31 | } 32 | 33 | @Override 34 | public String toStr() { 35 | return deque.toString(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /InterfaceQueue/src/queue/LinkedQueue.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | public class LinkedQueue extends AbstractQueue { 4 | private Node head = null, tail = null; 5 | 6 | @Override 7 | protected void implEnqueue(Object x) { 8 | if (isEmpty()) { 9 | head = tail = new Node(x); 10 | return; 11 | } 12 | tail = tail.next = new Node(x); 13 | } 14 | 15 | @Override 16 | protected Object implDequeue() { 17 | Object ret = head.val; 18 | head = head.next; 19 | if (head == null) { 20 | tail = null; 21 | } 22 | return ret; 23 | } 24 | 25 | @Override 26 | protected Object implElement() { 27 | return head.val; 28 | } 29 | 30 | static class Node { 31 | Node next; 32 | Object val; 33 | 34 | public Node(Object nw) { 35 | this.val = nw; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /InterfaceQueue/src/queue/Main.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Queue q = new LinkedQueue(); 8 | Scanner sc = new Scanner(System.in); 9 | while (true) { 10 | if (sc.next().equals("+")) { 11 | System.out.print("prev size: " + q.size()); 12 | q.enqueue(sc.nextInt()); 13 | System.out.println(" new size: " + q.size()); 14 | } else { 15 | System.out.println("prev size: " + q.size() + " element: " + q.dequeue() + " new size: " + q.size()); 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /InterfaceQueue/src/queue/Queue.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import java.util.function.Predicate; 4 | 5 | public interface Queue { 6 | // INV: contains [e1, e2, ..., en] \forall i in 1..n, ei != null 7 | // or empty 8 | // methods: enqueue, dequeue, element, 9 | // size, isEmpty, clear, push, peek, get, set 10 | 11 | // PRE: x != null 12 | void enqueue(Object x); 13 | // POST: e' = [e1, ..., en, x] 14 | 15 | // PRE: not empty 16 | Object dequeue(); 17 | // POST: e' = [e2, ..., en] 18 | // RET = e1 19 | 20 | // PRE: not empty 21 | Object element(); 22 | // POST: e' = e 23 | // RET = en 24 | 25 | //PRE: true 26 | void removeIf(Predicate predicate); 27 | //POST: i = [i_1, i_2, ..., i_k] is subSeq of [1, ..., n] : 28 | // \forall k in 1..n: (k in i <=> predicate.test(e_k)) 29 | // e' = [e_{i_1}, ..., e_{i_k}] 30 | 31 | //PRE: true 32 | void retainIf(Predicate predicate); 33 | //POST: i = [i_1, i_2, ..., i_k] is subSeq of [1, ..., n] : 34 | // \forall k in 1..n: (k in i <=> !predicate.test(e_k)) 35 | // e' = [e_{i_1}, ..., e_{i_k}] 36 | 37 | //PRE: true 38 | void takeWhile(Predicate predicate); 39 | //POST: 40 | // \exists k in [0, ..., n] : 41 | // \forall i in [1, ..., k] predicate.test(e_i) == true 42 | // and 43 | // predicate.test(e_{k+1}) == false or k == n 44 | // [e_1, ..., e_k, e_{k+1}, ..., e_n] -> [e_1, ..., e_k] = e' 45 | 46 | //PRE: true 47 | void dropWhile(Predicate predicate); 48 | //POST: 49 | // /exists k in [0, ..., n] : 50 | // \forall i in [1, ..., k] predicate.test(e_i) == true 51 | // and 52 | // predicate.test(e_{k+1}) == false or k == n 53 | // [e_1, ..., e_k, e_{k+1}, ..., e_n] -> [e_{k + 1}, ..., e_n] = e' 54 | 55 | // PRE: true 56 | int size(); 57 | // POST: e' = e 58 | // RET = n 59 | 60 | // PRE: true 61 | boolean isEmpty(); 62 | // POST: e' = e 63 | // RET = (n == 0) 64 | 65 | // PRE: true 66 | void clear(); 67 | // POST: 68 | // [e1, e2, ..., en] -> empty 69 | } 70 | -------------------------------------------------------------------------------- /InterfaceQueue/src/queue/QueueFunctionsTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import java.util.List; 4 | import java.util.function.Function; 5 | import java.util.function.Predicate; 6 | import java.util.stream.Stream; 7 | 8 | /** 9 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 10 | */ 11 | public class QueueFunctionsTest extends QueueTest { 12 | public QueueFunctionsTest() { 13 | super(QueueFunctions.class, ReferenceQueueFunctions::new); 14 | } 15 | 16 | public static void main(final String[] args) { 17 | new QueueFunctionsTest().test(); 18 | } 19 | 20 | @Override 21 | protected List linearTest(final QueueFunctions queue) { 22 | if (random.nextBoolean()) { 23 | return List.of(queue.filter(Predicate.isEqual(randomElement()))); 24 | } else { 25 | return List.of(queue.map(random.nextBoolean() ? String::valueOf : Object::hashCode)); 26 | } 27 | } 28 | 29 | protected interface QueueFunctions extends Queue { 30 | QueueFunctions filter(final Predicate p); 31 | QueueFunctions map(final Function f); 32 | } 33 | 34 | protected static class ReferenceQueueFunctions extends ReferenceQueue implements QueueFunctions { 35 | public ReferenceQueueFunctions(final Stream elements) { 36 | super(elements); 37 | } 38 | 39 | @Override 40 | public QueueFunctions filter(final Predicate p) { 41 | return new ReferenceQueueFunctions(deque.stream().filter(p)); 42 | } 43 | 44 | @Override 45 | public QueueFunctions map(final Function f) { 46 | return new ReferenceQueueFunctions(deque.stream().map(f)); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /InterfaceQueue/src/queue/QueueTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import java.util.function.Function; 4 | import java.util.stream.Stream; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class QueueTest extends ArrayQueueTest { 10 | public QueueTest(final Class type, final Function, T> reference) { 11 | super(type, reference); 12 | } 13 | 14 | public static void main(final String[] args) { 15 | new QueueTest<>(Queue.class, ReferenceQueue::new).test(); 16 | } 17 | 18 | public void test() { 19 | test("LinkedQueue", 2, Mode.CLASS); 20 | test("ArrayQueue", 2, Mode.CLASS); 21 | } 22 | 23 | private static boolean implementsQueue(final Class type) { 24 | return type != Object.class 25 | && (Stream.of(type.getInterfaces()).map(Class::getName).anyMatch("queue.Queue"::equals) 26 | || implementsQueue(type.getSuperclass())); 27 | } 28 | 29 | @Override 30 | protected void checkImplementation(final Class type) { 31 | assertTrue(type + " should extend AbstractQueue", "queue.AbstractQueue".equals(type.getSuperclass().getName())); 32 | assertTrue(type + " should implement interface Queue", implementsQueue(type)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /InterfaceQueue/src/queue/QueueToArrayTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import queue.ArrayQueueToArrayTest.ReferenceToArrayQueue; 4 | import queue.ArrayQueueToArrayTest.ToArrayQueue; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 10 | */ 11 | public class QueueToArrayTest extends QueueTest { 12 | public QueueToArrayTest() { 13 | super(ToArrayQueue.class, ReferenceToArrayQueue::new); 14 | } 15 | 16 | @Override 17 | protected List linearTest(final ToArrayQueue queue) { 18 | queue.toArray(); 19 | return List.of(); 20 | } 21 | 22 | public static void main(final String[] args) { 23 | new QueueToArrayTest().test(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Markup/Test.java: -------------------------------------------------------------------------------- 1 | import markup.*; 2 | import markup.types.Emphasis; 3 | import markup.types.Strikeout; 4 | import markup.types.Strong; 5 | 6 | import java.util.List; 7 | 8 | public class Test { 9 | public static void main(String[] args) { 10 | Paragraph paragraph = new Paragraph(List.of( 11 | new Strong(List.of( 12 | new Text("1"), 13 | new Strikeout(List.of( 14 | new Text("2"), 15 | new Emphasis(List.of( 16 | new Text("3"), 17 | new Text("4") 18 | )), 19 | new Text("5") 20 | )), 21 | new Text("6") 22 | )) 23 | )); 24 | StringBuilder res = new StringBuilder(); 25 | paragraph.toMarkdown(res); 26 | System.out.println(res.toString()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Markup/markup/AbstractList.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | import java.util.List; 4 | 5 | abstract class AbstractList implements InList { 6 | private List elements; 7 | 8 | AbstractList(List elements) { 9 | this.elements = elements; 10 | } 11 | 12 | public void toHtml(StringBuilder result, String leftBorder, String rightBorder) { 13 | result.append(leftBorder); 14 | for (ListItem cur : elements) { 15 | cur.toHtml(result); 16 | } 17 | result.append(rightBorder); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Markup/markup/AbstractMarkupElement.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | import java.util.List; 4 | 5 | public abstract class AbstractMarkupElement { 6 | private List elements; 7 | 8 | AbstractMarkupElement(List elements) { 9 | this.elements = elements; 10 | } 11 | 12 | protected void toMarkdown(StringBuilder result, String border) { 13 | result.append(border); 14 | for (InParagraph cur : elements) { 15 | cur.toMarkdown(result); 16 | } 17 | result.append(border); 18 | } 19 | 20 | protected void toHtml(StringBuilder result, String leftBorder, String rightBorder) { 21 | result.append(leftBorder); 22 | for (InParagraph cur : elements) { 23 | cur.toHtml(result); 24 | } 25 | result.append(rightBorder); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Markup/markup/Emphasis.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | import java.util.List; 4 | 5 | public class Emphasis extends AbstractMarkupElement implements InParagraph { 6 | public Emphasis(List elements) { 7 | super(elements); 8 | } 9 | 10 | @Override 11 | public void toMarkdown(StringBuilder result) { 12 | toMarkdown(result, "*"); 13 | } 14 | 15 | @Override 16 | public void toHtml(StringBuilder result) { 17 | toHtml(result, "", ""); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Markup/markup/InList.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | public interface InList extends Markable { 4 | } 5 | -------------------------------------------------------------------------------- /Markup/markup/InParagraph.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | public interface InParagraph extends Markable { 4 | void toMarkdown(StringBuilder result); 5 | } 6 | -------------------------------------------------------------------------------- /Markup/markup/ListItem.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | import markup.*; 4 | 5 | import java.util.List; 6 | 7 | public class ListItem { 8 | private List elements; 9 | 10 | public ListItem(List elements) { 11 | this.elements = elements; 12 | } 13 | 14 | public void toMarkdown(StringBuilder result) { //don't use it 15 | throw new NoSuchMethodError("Don't use ListItem.toMarkdown()"); 16 | } 17 | 18 | public void toHtml(StringBuilder result) { 19 | result.append("
  • "); 20 | for (InList element : elements) { 21 | element.toHtml(result); 22 | } 23 | result.append("
  • "); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Markup/markup/Markable.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | public interface Markable { 4 | void toHtml(StringBuilder result); 5 | } 6 | -------------------------------------------------------------------------------- /Markup/markup/OrderedList.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | import java.util.List; 4 | 5 | public class OrderedList extends AbstractList { 6 | public OrderedList(List elements) { 7 | super(elements); 8 | } 9 | 10 | @Override 11 | public void toHtml(StringBuilder result) { 12 | toHtml(result, "
      ", "
    "); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Markup/markup/Paragraph.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | import java.util.List; 4 | 5 | public class Paragraph extends AbstractMarkupElement implements InList { 6 | public Paragraph(List elements) { 7 | super(elements); 8 | } 9 | 10 | public void toMarkdown(StringBuilder result) { 11 | toMarkdown(result, ""); 12 | } 13 | 14 | @Override 15 | public void toHtml(StringBuilder result) { 16 | toHtml(result, "", ""); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Markup/markup/Strikeout.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | import java.util.List; 4 | 5 | public class Strikeout extends AbstractMarkupElement implements InParagraph { 6 | public Strikeout(List elements) { 7 | super(elements); 8 | } 9 | 10 | @Override 11 | public void toMarkdown(StringBuilder result) { 12 | toMarkdown(result, "~"); 13 | } 14 | 15 | @Override 16 | public void toHtml(StringBuilder result) { 17 | toHtml(result, "", ""); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Markup/markup/Strong.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | import java.util.List; 4 | 5 | public class Strong extends AbstractMarkupElement implements InParagraph { 6 | public Strong(List elements) { 7 | super(elements); 8 | } 9 | 10 | @Override 11 | public void toMarkdown(StringBuilder result) { 12 | toMarkdown(result, "__"); 13 | } 14 | 15 | @Override 16 | public void toHtml(StringBuilder result) { 17 | toHtml(result, "", ""); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Markup/markup/Text.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | public class Text implements InParagraph { 4 | private String text; 5 | 6 | public Text(String text) { 7 | this.text = text; 8 | } 9 | 10 | @Override 11 | public void toMarkdown(StringBuilder result) { 12 | result.append(text); 13 | } 14 | 15 | @Override 16 | public void toHtml(StringBuilder result) { 17 | result.append(text); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Markup/markup/UnorderedList.java: -------------------------------------------------------------------------------- 1 | package markup; 2 | 3 | import java.util.List; 4 | 5 | public class UnorderedList extends AbstractList { 6 | public UnorderedList(List elements) { 7 | super(elements); 8 | } 9 | 10 | @Override 11 | public void toHtml(StringBuilder result) { 12 | toHtml(result, "
      ", "
    "); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Markup/markup/base/Asserts.java: -------------------------------------------------------------------------------- 1 | package markup.base; 2 | 3 | import java.util.List; 4 | import java.util.Locale; 5 | import java.util.Objects; 6 | 7 | /** 8 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 9 | */ 10 | public class Asserts { 11 | static { 12 | Locale.setDefault(Locale.US); 13 | } 14 | 15 | public static void assertEquals(final String message, final Object expected, final Object actual) { 16 | assertTrue(String.format("%s:%n expected `%s`,%n actual `%s`", message, expected, actual), Objects.equals(expected, actual)); 17 | } 18 | 19 | public static void assertEquals(final String message, final List expected, final List actual) { 20 | for (int i = 0; i < Math.min(expected.size(), actual.size()); i++) { 21 | assertEquals(message + ":" + (i + 1), expected.get(i), actual.get(i)); 22 | } 23 | assertEquals(message + ": Number of items", expected.size(), actual.size()); 24 | } 25 | 26 | public static void assertTrue(final String message, final boolean value) { 27 | if (!value) { 28 | throw new AssertionError(message); 29 | } 30 | } 31 | 32 | public static void assertEquals(final String message, final double expected, final double actual, final double precision) { 33 | final double error = Math.abs(expected - actual); 34 | assertTrue( 35 | String.format("%s: expected %f, found %f", message, expected, actual), 36 | error <= precision || (Math.abs(expected) >= 1 && error / Math.abs(expected) < precision) 37 | ); 38 | } 39 | 40 | public static void assertSame(final String message, final Object expected, final Object actual) { 41 | assertTrue(String.format("%s: expected same objects: %s and %s", message, expected, actual), expected == actual); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Markup/markup/base/MainFilesChecker.java: -------------------------------------------------------------------------------- 1 | package markup.base; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.List; 8 | 9 | /** 10 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 11 | */ 12 | public class MainFilesChecker extends MainChecker { 13 | public MainFilesChecker(final String className) { 14 | super(className); 15 | } 16 | 17 | private Path getFile(final String suffix) { 18 | return Paths.get(String.format("test%d.%s", counter.getTest() + 1, suffix)); 19 | } 20 | 21 | protected List runFiles(final List input) { 22 | try { 23 | final Path inf = getFile("in"); 24 | final Path ouf = getFile("out"); 25 | Files.write(inf, input); 26 | run(inf.toString(), ouf.toString()); 27 | final List output = Files.readAllLines(ouf); 28 | Files.delete(inf); 29 | Files.delete(ouf); 30 | return output; 31 | } catch (IOException e) { 32 | throw new AssertionError(e); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Markup/markup/base/MainStdChecker.java: -------------------------------------------------------------------------------- 1 | package markup.base; 2 | 3 | import java.io.*; 4 | import java.util.List; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class MainStdChecker extends MainChecker { 10 | 11 | public MainStdChecker(final String className) { 12 | super(className); 13 | } 14 | 15 | protected List runStd(final List input) { 16 | final ByteArrayOutputStream baos = new ByteArrayOutputStream(); 17 | try (final PrintWriter writer = new PrintWriter(baos)) { 18 | input.forEach(writer::println); 19 | } 20 | 21 | final InputStream oldIn = System.in; 22 | try { 23 | System.setIn(new ByteArrayInputStream(baos.toByteArray())); 24 | return runComment(String.format("<%d input lines>", input.size())); 25 | } finally { 26 | System.setIn(oldIn); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Markup/markup/base/Pair.java: -------------------------------------------------------------------------------- 1 | package markup.base; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public class Pair { 9 | public final F first; 10 | public final S second; 11 | 12 | public Pair(final F first, final S second) { 13 | this.first = first; 14 | this.second = second; 15 | } 16 | 17 | public static Pair of(final F first, final S second) { 18 | return new Pair<>(first, second); 19 | } 20 | 21 | public static Pair of(final Map.Entry e) { 22 | return of(e.getKey(), e.getValue()); 23 | } 24 | 25 | @Override 26 | public boolean equals(final Object o) { 27 | if (this == o) return true; 28 | if (o == null || getClass() != o.getClass()) return false; 29 | 30 | final Pair pair = (Pair) o; 31 | 32 | return first.equals(pair.first) && second.equals(pair.second); 33 | } 34 | 35 | @Override 36 | public int hashCode() { 37 | int result = first.hashCode(); 38 | result = 31 * result + second.hashCode(); 39 | return result; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return first + ": " + second; 45 | } 46 | 47 | public F getFirst() { 48 | return first; 49 | } 50 | 51 | public S getSecond() { 52 | return second; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Markup/markup/base/Randomized.java: -------------------------------------------------------------------------------- 1 | package markup.base; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class Randomized { 10 | public static final String ENGLISH = "abcdefghijklmnopqrstuvwxyz"; 11 | public static final String RUSSIAN = "абвгдеежзийклмнопрстуфхцчшщъыьэюя"; 12 | public static final String GREEK = "αβγŋδεζηθικλμνξοπρτυφχψω"; 13 | 14 | public final Random random = new Random(8045702385702345702L); 15 | 16 | public String randomString(final String chars) { 17 | return randomChar(chars) + (random.nextBoolean() ? "" : randomString(chars)); 18 | } 19 | 20 | public char randomChar(final String chars) { 21 | return chars.charAt(random.nextInt(chars.length())); 22 | } 23 | 24 | public String randomString(final String chars, final int length) { 25 | final StringBuilder string = new StringBuilder(); 26 | for (int i = 0; i < length; i++) { 27 | string.append(randomChar(chars)); 28 | } 29 | return string.toString(); 30 | } 31 | 32 | public String randomString(final String chars, final int minLength, int maxLength) { 33 | return randomString(chars, randomInt(minLength, maxLength + 1)); 34 | } 35 | 36 | public int randomInt(final int min, final int max) { 37 | return random.nextInt(max - min) + min; 38 | } 39 | 40 | @SafeVarargs 41 | public final T randomItem(final T... items) { 42 | return items[random.nextInt(items.length)]; 43 | } 44 | 45 | public final T randomItem(final List items) { 46 | return items.get(random.nextInt(items.size())); 47 | } 48 | 49 | public Random getRandom() { 50 | return random; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Markup/markup/markup/AbstractTest.java: -------------------------------------------------------------------------------- 1 | package markup.markup; 2 | 3 | import markup.base.Asserts; 4 | import markup.base.TestCounter; 5 | 6 | import java.util.Map; 7 | import java.util.function.Consumer; 8 | 9 | /** 10 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 11 | */ 12 | public abstract class AbstractTest { 13 | private TestCounter counter = new TestCounter(); 14 | 15 | protected void run() { 16 | test(); 17 | counter.printStatus(getClass()); 18 | } 19 | 20 | protected abstract void test(); 21 | 22 | protected void test(Consumer f, String expected, final Map replacements) { 23 | for (final Map.Entry entry : replacements.entrySet()) { 24 | expected = expected.replace(entry.getKey(), entry.getValue()); 25 | } 26 | 27 | counter.nextTest(); 28 | final StringBuilder sb = new StringBuilder(); 29 | f.accept(sb); 30 | final String actual = sb.toString(); 31 | Asserts.assertEquals("Result", expected, actual); 32 | counter.passed(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Markup/markup/markup/HtmlListTest.java: -------------------------------------------------------------------------------- 1 | package markup.markup; 2 | 3 | import java.util.Map; 4 | 5 | import markup.OrderedList; 6 | import markup.UnorderedList; 7 | import markup.Paragraph; 8 | 9 | /** 10 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 11 | */ 12 | public class HtmlListTest extends ListTest { 13 | private static final Map HTML = Map.of(); 14 | 15 | @Override 16 | protected void test(final Paragraph paragraph, final String expected) { 17 | test(paragraph::toHtml, expected, HTML); 18 | } 19 | 20 | protected void test(UnorderedList list, final String expected) { 21 | test(list::toHtml, expected, HTML); 22 | } 23 | 24 | protected void test(OrderedList list, final String expected) { 25 | test(list::toHtml, expected, HTML); 26 | } 27 | 28 | public static void main(String[] args) { 29 | new HtmlListTest().run(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Markup/markup/markup/HtmlTest.java: -------------------------------------------------------------------------------- 1 | package markup.markup; 2 | 3 | import java.util.Map; 4 | 5 | import markup.Paragraph; 6 | 7 | /** 8 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 9 | */ 10 | public class HtmlTest extends MarkdownTest { 11 | private static final Map HTML = Map.of( 12 | "*<", "", 13 | "*>", "", 14 | "__<", "", 15 | "__>", "", 16 | "~<", "", 17 | "~>", "" 18 | ); 19 | 20 | public static void main(String[] args) { 21 | new HtmlTest().run(); 22 | } 23 | 24 | @Override 25 | protected void test(final Paragraph paragraph, final String expected) { 26 | super.test(paragraph, expected); 27 | test(paragraph::toHtml, expected, HTML); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Markup/markup/markup/MarkdownTest.java: -------------------------------------------------------------------------------- 1 | package markup.markup; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import markup.*; 7 | 8 | /** 9 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 10 | */ 11 | public class MarkdownTest extends AbstractTest { 12 | private static final Map MARKDOWN = Map.of( 13 | "<", "", 14 | ">", "" 15 | ); 16 | 17 | public static void main(String... args) { 18 | new MarkdownTest().run(); 19 | } 20 | 21 | @Override 22 | protected void test() { 23 | test(new Paragraph(List.of(new Text("Hello"))), "Hello"); 24 | test(new Paragraph(List.of(new Emphasis(List.of(new Text("Hello"))))), "*"); 25 | test(new Paragraph(List.of(new Strong(List.of(new Text("Hello"))))), "__"); 26 | test(new Paragraph(List.of(new Strikeout(List.of(new Text("Hello"))))), "~"); 27 | final Paragraph paragraph = new Paragraph(List.of( 28 | new Strong(List.of( 29 | new Text("1"), 30 | new Strikeout(List.of( 31 | new Text("2"), 32 | new Emphasis(List.of( 33 | new Text("3"), 34 | new Text("4") 35 | )), 36 | new Text("5") 37 | )), 38 | new Text("6") 39 | )) 40 | )); 41 | test( 42 | paragraph, 43 | "__<1~<2*<34*>5~>6__>" 44 | ); 45 | test(new Paragraph(List.of( 46 | new Strong(List.of(new Text("sdq"), new Strikeout(List.of(new Emphasis(List.of(new Text("r"))), new Text("vavc"))), new Text("zg"))))), 47 | "__vavc~>zg__>" 48 | ); 49 | } 50 | 51 | protected void test(Paragraph paragraph, final String expected) { 52 | test(paragraph::toMarkdown, expected, MARKDOWN); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Md2Html/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml -------------------------------------------------------------------------------- /Md2Html/.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /Md2Html/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Md2Html/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Md2Html/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Md2Html/Md2Html.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Md2Html/kekTest.in: -------------------------------------------------------------------------------- 1 | Знаете ли вы, что в Markdown, одиночные * и 2 | не означают выделение? 3 | О\[н\] \[\] {} \(\)\(\)\{\]\[ [т_а_к](z_a_z) же могут быть заэкранированы 4 | при помощи обра\\тного слэша: \*. 5 | -------------------------------------------------------------------------------- /Md2Html/out.txt: -------------------------------------------------------------------------------- 1 |

    Знаете ли вы, что в Markdown, одиночные * и 2 | не означают выделение? 3 | О[н] [] {} ()(){][ так же могут быть заэкранированы 4 | при помощи обра\тного слэша: *.

    5 | -------------------------------------------------------------------------------- /Md2Html/out/production/Md2Html/META-INF/Md2Html.kotlin_module: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /Md2Html/out/production/Md2Html/Md2HtmlLinkTest.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprettysimpple/ITMOJava/78fd386b97d37628820a49b96588f1b2d4266462/Md2Html/out/production/Md2Html/Md2HtmlLinkTest.jar -------------------------------------------------------------------------------- /Md2Html/out/production/Md2Html/Md2HtmlTest.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprettysimpple/ITMOJava/78fd386b97d37628820a49b96588f1b2d4266462/Md2Html/out/production/Md2Html/Md2HtmlTest.jar -------------------------------------------------------------------------------- /Md2Html/out/production/Md2Html/Md2HtmlUnderlineTest.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprettysimpple/ITMOJava/78fd386b97d37628820a49b96588f1b2d4266462/Md2Html/out/production/Md2Html/Md2HtmlUnderlineTest.jar -------------------------------------------------------------------------------- /Md2Html/src/base/Asserts.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.List; 4 | import java.util.Locale; 5 | import java.util.Objects; 6 | 7 | /** 8 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 9 | */ 10 | public class Asserts { 11 | static { 12 | Locale.setDefault(Locale.US); 13 | } 14 | 15 | public static void assertEquals(final String message, final Object expected, final Object actual) { 16 | assertTrue(String.format("%s:%n expected `%s`,%n actual `%s`", message, expected, actual), Objects.equals(expected, actual)); 17 | } 18 | 19 | public static void assertEquals(final String message, final List expected, final List actual) { 20 | for (int i = 0; i < Math.min(expected.size(), actual.size()); i++) { 21 | assertEquals(message + ":" + (i + 1), expected.get(i), actual.get(i)); 22 | } 23 | assertEquals(message + ": Number of items", expected.size(), actual.size()); 24 | } 25 | 26 | public static void assertTrue(final String message, final boolean value) { 27 | if (!value) { 28 | throw new AssertionError(message); 29 | } 30 | } 31 | 32 | public static void assertEquals(final String message, final double expected, final double actual, final double precision) { 33 | final double error = Math.abs(expected - actual); 34 | assertTrue( 35 | String.format("%s: expected %f, found %f", message, expected, actual), 36 | error <= precision || (Math.abs(expected) >= 1 && error / Math.abs(expected) < precision) 37 | ); 38 | } 39 | 40 | public static void assertSame(final String message, final Object expected, final Object actual) { 41 | assertTrue(String.format("%s: expected same objects: %s and %s", message, expected, actual), expected == actual); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Md2Html/src/base/MainFilesChecker.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.List; 8 | 9 | /** 10 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 11 | */ 12 | public class MainFilesChecker extends MainChecker { 13 | public MainFilesChecker(final String className) { 14 | super(className); 15 | } 16 | 17 | private Path getFile(final String suffix) { 18 | return Paths.get(String.format("test%d.%s", counter.getTest() + 1, suffix)); 19 | } 20 | 21 | protected List runFiles(final List input) { 22 | try { 23 | final Path inf = getFile("in"); 24 | final Path ouf = getFile("out"); 25 | Files.write(inf, input); 26 | run(inf.toString(), ouf.toString()); 27 | final List output = Files.readAllLines(ouf); 28 | Files.delete(inf); 29 | Files.delete(ouf); 30 | return output; 31 | } catch (IOException e) { 32 | throw new AssertionError(e); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Md2Html/src/base/MainStdChecker.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.io.*; 4 | import java.util.List; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class MainStdChecker extends MainChecker { 10 | 11 | public MainStdChecker(final String className) { 12 | super(className); 13 | } 14 | 15 | protected List runStd(final List input) { 16 | final ByteArrayOutputStream baos = new ByteArrayOutputStream(); 17 | try (final PrintWriter writer = new PrintWriter(baos)) { 18 | input.forEach(writer::println); 19 | } 20 | 21 | final InputStream oldIn = System.in; 22 | try { 23 | System.setIn(new ByteArrayInputStream(baos.toByteArray())); 24 | return runComment(String.format("<%d input lines>", input.size())); 25 | } finally { 26 | System.setIn(oldIn); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Md2Html/src/base/Pair.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 7 | */ 8 | public class Pair { 9 | public final F first; 10 | public final S second; 11 | 12 | public Pair(final F first, final S second) { 13 | this.first = first; 14 | this.second = second; 15 | } 16 | 17 | public static Pair of(final F first, final S second) { 18 | return new Pair<>(first, second); 19 | } 20 | 21 | public static Pair of(final Map.Entry e) { 22 | return of(e.getKey(), e.getValue()); 23 | } 24 | 25 | @Override 26 | public boolean equals(final Object o) { 27 | if (this == o) return true; 28 | if (o == null || getClass() != o.getClass()) return false; 29 | 30 | final Pair pair = (Pair) o; 31 | 32 | return first.equals(pair.first) && second.equals(pair.second); 33 | } 34 | 35 | @Override 36 | public int hashCode() { 37 | int result = first.hashCode(); 38 | result = 31 * result + second.hashCode(); 39 | return result; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return first + ": " + second; 45 | } 46 | 47 | public F getFirst() { 48 | return first; 49 | } 50 | 51 | public S getSecond() { 52 | return second; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Md2Html/src/base/Randomized.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class Randomized { 10 | public static final String ENGLISH = "abcdefghijklmnopqrstuvwxyz"; 11 | public static final String RUSSIAN = "абвгдеежзийклмнопрстуфхцчшщъыьэюя"; 12 | public static final String GREEK = "αβγŋδεζηθικλμνξοπρτυφχψω"; 13 | 14 | public final Random random = new Random(8045702385702345702L); 15 | 16 | public String randomString(final String chars) { 17 | return randomChar(chars) + (random.nextBoolean() ? "" : randomString(chars)); 18 | } 19 | 20 | public char randomChar(final String chars) { 21 | return chars.charAt(random.nextInt(chars.length())); 22 | } 23 | 24 | public String randomString(final String chars, final int length) { 25 | final StringBuilder string = new StringBuilder(); 26 | for (int i = 0; i < length; i++) { 27 | string.append(randomChar(chars)); 28 | } 29 | return string.toString(); 30 | } 31 | 32 | public String randomString(final String chars, final int minLength, int maxLength) { 33 | return randomString(chars, randomInt(minLength, maxLength + 1)); 34 | } 35 | 36 | public int randomInt(final int min, final int max) { 37 | return random.nextInt(max - min) + min; 38 | } 39 | 40 | @SafeVarargs 41 | public final T randomItem(final T... items) { 42 | return items[random.nextInt(items.length)]; 43 | } 44 | 45 | public final T randomItem(final List items) { 46 | return items.get(random.nextInt(items.size())); 47 | } 48 | 49 | public Random getRandom() { 50 | return random; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Md2Html/src/md2html/BlockParser.java: -------------------------------------------------------------------------------- 1 | package md2html; 2 | 3 | class BlockParser { 4 | private StringBuilder source; 5 | 6 | BlockParser(StringBuilder source) { 7 | this.source = source; 8 | } 9 | 10 | private boolean isHeader(StringBuilder text) { 11 | int pos = 0; 12 | while (pos < text.length() && text.charAt(pos) == '#') { 13 | pos++; 14 | } 15 | return pos > 0 && pos < text.length() && text.charAt(pos) == ' '; 16 | } 17 | 18 | public void toHtml(StringBuilder result) { 19 | if (isHeader(source)) { 20 | new HeaderParser(source).toHtml(result); 21 | } else { 22 | new ParagraphParser(source).toHtml(result); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Md2Html/src/md2html/HeaderParser.java: -------------------------------------------------------------------------------- 1 | package md2html; 2 | 3 | class HeaderParser { 4 | private StringBuilder source; 5 | 6 | HeaderParser(StringBuilder source) { 7 | this.source = source; 8 | } 9 | 10 | private int headerLevel(StringBuilder text) { 11 | int pos = 0; 12 | while (pos < text.length() && text.charAt(pos) == '#') { 13 | pos++; 14 | } 15 | return pos; 16 | } 17 | 18 | public void toHtml(StringBuilder result) { 19 | int lvl = headerLevel(source); 20 | result.append(""); 21 | new TextParser( 22 | new StringBuilder( 23 | source.substring(lvl + 1)) 24 | ).toHtml(result); 25 | result.append(""); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Md2Html/src/md2html/IntList.java: -------------------------------------------------------------------------------- 1 | package md2html; 2 | 3 | import java.util.Arrays; 4 | 5 | public class IntList { 6 | private int size = 0; 7 | private int[] arr = new int[5]; 8 | 9 | public void add(int value) { 10 | if (size == arr.length) { 11 | arr = Arrays.copyOf(arr, 3 * arr.length / 2); 12 | } 13 | arr[size++] = value; 14 | } 15 | 16 | public int get(int position) { 17 | return arr[position]; 18 | } 19 | 20 | public void pop() { 21 | size--; 22 | } 23 | 24 | public int getSize() { 25 | return size; 26 | } 27 | } -------------------------------------------------------------------------------- /Md2Html/src/md2html/Md2Html.java: -------------------------------------------------------------------------------- 1 | package md2html; 2 | 3 | import java.io.*; 4 | import java.nio.charset.StandardCharsets; 5 | 6 | public class Md2Html { 7 | 8 | public static void main(String[] args) { 9 | if (args.length != 2) { 10 | System.err.println("Missed filenames\n"); 11 | return; 12 | } 13 | StringBuilder result = new StringBuilder(); 14 | try { 15 | try (BufferedReader reader = new BufferedReader( 16 | new InputStreamReader( 17 | new FileInputStream( 18 | new File(args[0])), 19 | StandardCharsets.UTF_8))) { 20 | String line = ""; 21 | StringBuilder paragraph = new StringBuilder(); 22 | while (line != null && (line = reader.readLine()) != null) { 23 | while (line != null && !line.isEmpty()) { 24 | paragraph.append(line).append('\n'); 25 | line = reader.readLine(); 26 | } 27 | if (paragraph.length() != 0) { 28 | paragraph.setLength(paragraph.length() - 1); 29 | new BlockParser(paragraph).toHtml(result); 30 | result.append('\n'); 31 | paragraph = new StringBuilder(); 32 | } 33 | } 34 | } 35 | } catch (FileNotFoundException e) { 36 | System.err.println("Input4 file not found: " + e.getMessage()); 37 | } catch (IOException e) { 38 | System.err.println("Read error: " + e.getMessage()); 39 | } 40 | try { 41 | try (BufferedWriter writer = new BufferedWriter( 42 | new OutputStreamWriter( 43 | new FileOutputStream( 44 | new File(args[1])), 45 | StandardCharsets.UTF_8))) { 46 | writer.write(result.toString()); 47 | } 48 | } catch (FileNotFoundException e) { 49 | System.err.println("Output file not found: " + e.getMessage()); 50 | } catch (IOException e) { 51 | System.err.println("Write error: " + e.getMessage()); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Md2Html/src/md2html/ParagraphParser.java: -------------------------------------------------------------------------------- 1 | package md2html; 2 | 3 | class ParagraphParser { 4 | private StringBuilder source; 5 | 6 | public ParagraphParser(StringBuilder source) { 7 | this.source = source; 8 | } 9 | 10 | public void toHtml(StringBuilder result) { 11 | result.append("

    "); 12 | new TextParser(source).toHtml(result); 13 | result.append("

    "); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /NERCHW/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml -------------------------------------------------------------------------------- /NERCHW/.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /NERCHW/.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | -------------------------------------------------------------------------------- /NERCHW/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /NERCHW/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /NERCHW/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /NERCHW/NERCHW.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /NERCHW/src/A.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class A { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int a = sc.nextInt(); 7 | int b = sc.nextInt(); 8 | int n = sc.nextInt(); 9 | int ans = 2 * ((n - a - 1) / (b - a)) + 1; 10 | System.out.println(ans); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /NERCHW/src/B.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class B { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int n = sc.nextInt(); 7 | for (int i = -25000; i < n - 25000; i++) { 8 | System.out.println(710 * i); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /NERCHW/src/H.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | import java.lang.Math; 5 | 6 | public class H { 7 | private static int[] pr; 8 | 9 | private static int get(int t) { 10 | int cnt = 0; 11 | for (int i = 0; i < pr.length; i++) { 12 | int l = i, r = pr.length - 1; 13 | int before = (i == 0) ? 0 : pr[i - 1]; 14 | while (l < r) { 15 | int m = r - (r - l) / 2; 16 | if (pr[m] - before > t) { 17 | r = m - 1; 18 | } else { 19 | l = m; 20 | } 21 | } 22 | i = l; 23 | cnt++; 24 | } 25 | return cnt; 26 | } 27 | 28 | public static void main(String[] args) { 29 | Scanner sc = new Scanner(System.in); 30 | pr = new int[sc.nextInt()]; 31 | int mx = 0; 32 | for (int i = 0; i < pr.length; i++) { 33 | pr[i] = sc.nextInt(); 34 | mx = Math.max(mx, pr[i]); 35 | pr[i] += (i == 0 ? 0 : pr[i - 1]); 36 | } 37 | int q = sc.nextInt(); 38 | int[] mem = new int[1000_001]; 39 | Arrays.fill(mem, -1); 40 | while (q --> 0) { 41 | int t = sc.nextInt(); 42 | if (mem[t] != -1) { 43 | System.out.println(mem[t]); 44 | continue; 45 | } 46 | if (t < mx) { 47 | System.out.println("Impossible"); 48 | continue; 49 | } 50 | System.out.println(mem[t] = get(t)); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /NERCHW/src/I.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.lang.Math; 3 | 4 | public class I { 5 | private static final int INF = (int) (1e9 + 7); 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | int xl = INF; 9 | int xr = -INF; 10 | int yl = INF; 11 | int yr = -INF; 12 | int n = sc.nextInt(); 13 | for (int i = 0; i < n; i++) { 14 | int x = sc.nextInt(); 15 | int y = sc.nextInt(); 16 | int h = sc.nextInt(); 17 | xl = Math.min(xl, x - h); 18 | xr = Math.max(xr, x + h); 19 | yl = Math.min(yl, y - h); 20 | yr = Math.max(yr, y + h); 21 | } 22 | int x = (xl + xr) / 2; 23 | int y = (yl + yr) / 2; 24 | int h = (Math.max(xr - xl, yr - yl) + 1) / 2; 25 | System.out.println(x + " " + y + " " + h); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /NERCHW/src/J.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class J { 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int n = Integer.parseInt(sc.nextLine()); 7 | int[][] d = new int[n][n]; 8 | for (int i = 0; i < n; i++) { 9 | String s = sc.nextLine(); 10 | for (int j = 0; j < n; j++) { 11 | d[i][j] = s.charAt(j) - '0'; 12 | } 13 | } 14 | for (int v = 0; v < n; v++) { 15 | for (int i = v + 1; i < n; i++) { 16 | if (d[v][i] == 0) { 17 | continue; 18 | } 19 | for (int j = i + 1; j < n; j++) { 20 | d[v][j] -= d[i][j]; 21 | if (d[v][j] < 0) { 22 | d[v][j] += 10; 23 | } 24 | } 25 | } 26 | } 27 | for (int i = 0; i < n; i++) { 28 | for (int j = 0; j < n; j++) { 29 | System.out.print(d[i][j]); 30 | } 31 | System.out.println(""); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /NERCHW/src/M.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class M { 5 | public static void main(String[] args) { 6 | int[] a; 7 | int n; 8 | Scanner sc = new Scanner(System.in); 9 | int testCount = sc.nextInt(); 10 | while (testCount --> 0) { 11 | a = new int[n = sc.nextInt()]; 12 | for (int i = 0; i < n; i++) { 13 | a[i] = sc.nextInt(); 14 | } 15 | Map mp = new HashMap<>(); 16 | long ans = 0; 17 | for (int i = 0; i < n; i++) { 18 | for (int j = i + 1; j < n; j++) { 19 | int cur = 2 * a[i] - a[j]; 20 | if (mp.containsKey(cur)) { 21 | ans += mp.get(cur); 22 | } 23 | } 24 | if (mp.containsKey(a[i])) { 25 | mp.put(a[i], mp.get(a[i]) + 1); 26 | } else { 27 | mp.put(a[i], 1); 28 | } 29 | } 30 | System.out.println(ans); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Queue/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml -------------------------------------------------------------------------------- /Queue/.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /Queue/.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /Queue/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Queue/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Queue/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Queue/Queue.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Queue/out/production/Queue/META-INF/Queue.kotlin_module: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /Queue/src/ArrayQueueTest.java: -------------------------------------------------------------------------------- 1 | import queue.ArrayQueue; 2 | 3 | public class ArrayQueueTest { 4 | public static void fill(ArrayQueue stack) { 5 | for (int i = 0; i < 10; i++) { 6 | stack.enqueue(i); 7 | } 8 | } 9 | 10 | public static void dump(ArrayQueue stack) { 11 | while (!stack.isEmpty()) { 12 | System.out.println(stack.size() + " " + 13 | stack.element() + " " + stack.dequeue()); 14 | } 15 | } 16 | 17 | public static void main(String[] args) { 18 | ArrayQueue stack = new ArrayQueue(); 19 | fill(stack); 20 | dump(stack); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Queue/src/base/Asserts.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.Locale; 4 | import java.util.Objects; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class Asserts { 10 | static { 11 | Locale.setDefault(Locale.US); 12 | } 13 | 14 | public static void assertEquals(final String message, final Object expected, final Object actual) { 15 | assertTrue(String.format("%s:%n expected `%s`,%n actual `%s`", message, expected, actual), Objects.deepEquals(expected, actual)); 16 | } 17 | 18 | public static void assertTrue(final String message, final boolean value) { 19 | if (!value) { 20 | throw new AssertionError(message); 21 | } 22 | } 23 | 24 | public static void assertEquals(final String message, final int expected, final int actual) { 25 | assertTrue(String.format("%s: Expected %d, found %d", message, expected, actual), actual == expected); 26 | } 27 | 28 | public static void assertEquals(final String message, final double precision, final double expected, final double actual) { 29 | assertTrue( 30 | String.format("%s: Expected %.12f, found %.12f", message, expected, actual), 31 | Math.abs(actual - expected) < precision || 32 | Math.abs(actual - expected) < precision * Math.abs(actual) || 33 | (Double.isNaN(actual) || Double.isInfinite(actual)) && 34 | (Double.isNaN(expected) || Double.isInfinite(expected)) 35 | ); 36 | } 37 | 38 | public static void checkAssert(final Class c) { 39 | if (!c.desiredAssertionStatus()) { 40 | throw error("You should enable assertions by running 'java -ea %s'", c.getName()); 41 | } 42 | } 43 | 44 | public static AssertionError error(final String format, final Object... args) { 45 | return new AssertionError(String.format(format, args)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Queue/src/base/MainFilesChecker.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.util.List; 8 | 9 | /** 10 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 11 | */ 12 | public class MainFilesChecker extends MainChecker { 13 | public MainFilesChecker(final String className) { 14 | super(className); 15 | } 16 | 17 | private Path getFile(final String suffix) { 18 | return Paths.get(String.format("test%d.%s", counter.getTest() + 1, suffix)); 19 | } 20 | 21 | protected List runFiles(final List input) { 22 | try { 23 | final Path inf = getFile("in"); 24 | final Path ouf = getFile("out"); 25 | Files.write(inf, input); 26 | run(inf.toString(), ouf.toString()); 27 | final List output = Files.readAllLines(ouf); 28 | Files.delete(inf); 29 | Files.delete(ouf); 30 | return output; 31 | } catch (final IOException e) { 32 | throw new AssertionError(e); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Queue/src/base/Randomized.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class Randomized { 10 | public static final String ENGLISH = "abcdefghijklmnopqrstuvwxyz"; 11 | 12 | public final Random random = new Random(8045702385702345702L); 13 | 14 | public String randomString(final String chars) { 15 | return randomChar(chars) + (random.nextBoolean() ? "" : randomString(chars)); 16 | } 17 | 18 | public char randomChar(final String chars) { 19 | return chars.charAt(random.nextInt(chars.length())); 20 | } 21 | 22 | public String randomString(final String chars, final int length) { 23 | final StringBuilder string = new StringBuilder(); 24 | for (int i = 0; i < length; i++) { 25 | string.append(randomChar(chars)); 26 | } 27 | return string.toString(); 28 | } 29 | 30 | public String randomString(final String chars, final int minLength, int maxLength) { 31 | return randomString(chars, randomInt(minLength, maxLength + 1)); 32 | } 33 | 34 | public int randomInt(final int min, final int max) { 35 | return random.nextInt(max - min) + min; 36 | } 37 | 38 | @SafeVarargs 39 | public final T randomItem(final T... items) { 40 | return items[random.nextInt(items.length)]; 41 | } 42 | 43 | public final T randomItem(final List items) { 44 | return items.get(random.nextInt(items.size())); 45 | } 46 | 47 | public Random getRandom() { 48 | return random; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Queue/src/base/Triple.java: -------------------------------------------------------------------------------- 1 | package base; 2 | 3 | /** 4 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 5 | */ 6 | public class Triple { 7 | private final F first; 8 | private final S second; 9 | private final T third; 10 | 11 | public Triple(final F first, final S second, final T third) { 12 | this.first = first; 13 | this.second = second; 14 | this.third = third; 15 | } 16 | 17 | public F first() { 18 | return first; 19 | } 20 | 21 | public S second() { 22 | return second; 23 | } 24 | 25 | public T third() { 26 | return third; 27 | } 28 | 29 | public static Triple of(final F first, final S second, final T third) { 30 | return new Triple<>(first, second, third); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Queue/src/queue/ArrayQueueADTTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import queue.ArrayQueueADT; 4 | 5 | public class ArrayQueueADTTest { 6 | public static void fill(ArrayQueueADT stack) { 7 | for (int i = 0; i < 10; i++) { 8 | ArrayQueueADT.enqueue(stack, i); 9 | } 10 | } 11 | 12 | public static void dump(ArrayQueueADT stack) { 13 | while (!ArrayQueueADT.isEmpty(stack)) { 14 | System.out.println(ArrayQueueADT.size(stack) + " " + 15 | ArrayQueueADT.element(stack) + " " + ArrayQueueADT.dequeue(stack)); 16 | } 17 | } 18 | 19 | public static void main(String[] args) { 20 | ArrayQueueADT stack = new ArrayQueueADT(); 21 | fill(stack); 22 | dump(stack); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Queue/src/queue/ArrayQueueDequeTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import java.util.function.Function; 4 | import java.util.stream.Stream; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class ArrayQueueDequeTest extends ArrayQueueTest { 10 | public ArrayQueueDequeTest(final Class type, final Function, T> reference) { 11 | super(type, reference); 12 | } 13 | 14 | public static void main(final String[] args) { 15 | new ArrayQueueDequeTest<>(QueueDeque.class, ReferenceQueueDeque::new).test(); 16 | } 17 | 18 | @Override 19 | protected void add(final T queue, final Object element) { 20 | if (random.nextBoolean()) { 21 | super.add(queue, element); 22 | } else { 23 | queue.push(element); 24 | } 25 | } 26 | 27 | @Override 28 | protected void check(final T queue) { 29 | if (random.nextBoolean()) { 30 | super.check(queue); 31 | } else { 32 | queue.peek(); 33 | } 34 | } 35 | 36 | @Override 37 | protected void remove(final T queue) { 38 | if (random.nextBoolean()) { 39 | super.remove(queue); 40 | } else { 41 | queue.remove(); 42 | } 43 | } 44 | 45 | protected interface QueueDeque extends Queue { 46 | void push(final Object element); 47 | Object peek(); 48 | Object remove(); 49 | } 50 | 51 | protected static class ReferenceQueueDeque extends ReferenceQueue implements QueueDeque { 52 | public ReferenceQueueDeque(final Stream elements) { 53 | super(elements); 54 | } 55 | 56 | @Override 57 | public void push(final Object element) { 58 | deque.addFirst(element); 59 | } 60 | 61 | @Override 62 | public Object peek() { 63 | return deque.getLast(); 64 | } 65 | 66 | @Override 67 | public Object remove() { 68 | return deque.removeLast(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Queue/src/queue/ArrayQueueModuleTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import queue.ArrayQueueModule; 4 | 5 | public class ArrayQueueModuleTest { 6 | public static void fill() { 7 | for (int i = 0; i < 10; i++) { 8 | ArrayQueueModule.enqueue(i); 9 | } 10 | } 11 | 12 | public static void dump() { 13 | while (!ArrayQueueModule.isEmpty()) { 14 | System.out.println(ArrayQueueModule.size() + " " + 15 | ArrayQueueModule.element() + " " + ArrayQueueModule.dequeue()); 16 | } 17 | } 18 | 19 | public static void main(String[] args) { 20 | fill(); 21 | dump(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Queue/src/queue/ArrayQueueToArrayTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import java.util.List; 4 | import java.util.stream.Stream; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class ArrayQueueToArrayTest extends ArrayQueueTest { 10 | public ArrayQueueToArrayTest() { 11 | super(ToArrayQueue.class, ReferenceToArrayQueue::new); 12 | } 13 | 14 | public static void main(final String[] args) { 15 | new ArrayQueueToArrayTest().test(); 16 | } 17 | 18 | @Override 19 | protected List linearTest(final ToArrayQueue queue) { 20 | queue.toArray(); 21 | return List.of(); 22 | } 23 | 24 | protected interface ToArrayQueue extends Queue { 25 | Object[] toArray(); 26 | } 27 | 28 | protected static class ReferenceToArrayQueue extends ReferenceQueue implements ToArrayQueue { 29 | public ReferenceToArrayQueue(final Stream elements) { 30 | super(elements); 31 | } 32 | 33 | @Override 34 | public Object[] toArray() { 35 | return deque.toArray(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Queue/src/queue/ArrayQueueToStrTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import java.util.List; 4 | import java.util.stream.Stream; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class ArrayQueueToStrTest extends ArrayQueueTest { 10 | public ArrayQueueToStrTest() { 11 | super(ToStrQueue.class, ReferenceToStrQueue::new); 12 | } 13 | 14 | public static void main(final String[] args) { 15 | new ArrayQueueToStrTest().test(); 16 | } 17 | 18 | @Override 19 | protected List linearTest(final ToStrQueue queue) { 20 | queue.toStr(); 21 | return List.of(); 22 | } 23 | 24 | protected interface ToStrQueue extends Queue { 25 | String toStr(); 26 | } 27 | 28 | protected static class ReferenceToStrQueue extends ReferenceQueue implements ToStrQueue { 29 | public ReferenceToStrQueue(final Stream elements) { 30 | super(elements); 31 | } 32 | 33 | @Override 34 | public String toStr() { 35 | return deque.toString(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Queue/src/queue/QueueTest.java: -------------------------------------------------------------------------------- 1 | package queue; 2 | 3 | import java.util.function.Function; 4 | import java.util.stream.Stream; 5 | 6 | /** 7 | * @author Georgiy Korneev (kgeorgiy@kgeorgiy.info) 8 | */ 9 | public class QueueTest extends ArrayQueueTest { 10 | public QueueTest(final Class type, final Function, T> reference) { 11 | super(type, reference); 12 | } 13 | 14 | public static void main(final String[] args) { 15 | new QueueTest<>(Queue.class, ReferenceQueue::new).test(); 16 | } 17 | 18 | public void test() { 19 | test("LinkedQueue", 2, Mode.CLASS); 20 | test("ArrayQueue", 2, Mode.CLASS); 21 | } 22 | 23 | private static boolean implementsQueue(final Class type) { 24 | return type != Object.class 25 | && (Stream.of(type.getInterfaces()).map(Class::getName).anyMatch("queue.Queue"::equals) 26 | || implementsQueue(type.getSuperclass())); 27 | } 28 | 29 | @Override 30 | protected void checkImplementation(final Class type) { 31 | assertTrue(type + " should extend AbstractQueue", "queue.AbstractQueue".equals(type.getSuperclass().getName())); 32 | assertTrue(type + " should implement interface Queue", implementsQueue(type)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Reverse/ReverseEven.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class ReverseEven { 5 | 6 | public static void main(String[] args) { 7 | Scanner text = new Scanner(System.in); 8 | int[][] a = new int[10][]; 9 | int n = 0; 10 | while (text.hasNextLine()) { 11 | int[] row = new int[10]; 12 | Scanner line = new Scanner(text.nextLine()); 13 | 14 | int cnt = 0; 15 | while (line.hasNextInt()) { 16 | int val = line.nextInt(); 17 | if (val % 2 == 0) { 18 | if (cnt == a[n].length) { 19 | row = Arrays.copyOf(row, row.length * 2); 20 | } 21 | row[cnt++] = val; 22 | } 23 | } 24 | 25 | if (n == a.length) { 26 | a = Arrays.copyOf(a, a.length * 2); 27 | } 28 | a[n++] = Arrays.copyOf(row, cnt); 29 | } 30 | 31 | 32 | for (int i = n - 1; i >= 0; i--) { 33 | for (int j = a[i].length - 1; j >= 0; j--) { 34 | System.out.print(a[i][j] + " "); 35 | } 36 | System.out.println(""); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Scanner/MyClasses/Checker.java: -------------------------------------------------------------------------------- 1 | package MyClasses; 2 | 3 | public interface Checker { 4 | boolean isWordCharacter(char c); 5 | } 6 | -------------------------------------------------------------------------------- /Scanner/MyClasses/IntList.java: -------------------------------------------------------------------------------- 1 | package MyClasses; 2 | 3 | import java.util.Arrays; 4 | 5 | public class IntList { 6 | private int size; 7 | private int[] arr; 8 | 9 | public IntList() { 10 | initialize(); 11 | } 12 | 13 | public IntList(int value) { 14 | initialize(); 15 | add(value); 16 | } 17 | 18 | private void initialize() { 19 | arr = new int[10]; 20 | size = 0; 21 | } 22 | 23 | public void add(int value) { 24 | if (size == arr.length) { 25 | arr = Arrays.copyOf(arr, 3 * arr.length / 2); 26 | } 27 | arr[size++] = value; 28 | } 29 | 30 | public int get(int position) { 31 | return arr[position]; 32 | } 33 | 34 | public int getSize() { 35 | return size; 36 | } 37 | } -------------------------------------------------------------------------------- /SumHex/SumHex.java: -------------------------------------------------------------------------------- 1 | public class SumHex { 2 | 3 | public static void main(String[] args) { 4 | int resultSum = 0; 5 | for (int i = 0; i < args.length; i++) { 6 | args[i] = args[i]; 7 | for (int left = 0; left < args[i].length(); left++) { 8 | int right = left; 9 | while (right < args[i].length() && !Character.isWhitespace(args[i].charAt(right))) { 10 | right++; 11 | } 12 | if (right > left) { 13 | if (left + 2 < right && args[i].substring(left, left + 2).toLowerCase().equals("0x")) { 14 | resultSum += Integer.parseUnsignedInt(args[i].substring(left + 2, right), 16); 15 | } else { 16 | resultSum += Integer.parseInt(args[i].substring(left, right)); 17 | } 18 | left = right - 1; 19 | } 20 | } 21 | } 22 | System.out.println(resultSum); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /WordStatFirstIndex/MyClasses/Checker.java: -------------------------------------------------------------------------------- 1 | package MyClasses; 2 | 3 | public interface Checker { 4 | boolean isWordCharacter(char c); 5 | } 6 | -------------------------------------------------------------------------------- /WordStatFirstIndex/MyClasses/IntList.java: -------------------------------------------------------------------------------- 1 | package MyClasses; 2 | 3 | import java.util.Arrays; 4 | 5 | public class IntList { 6 | private int size; 7 | private int[] arr; 8 | 9 | public IntList(int value) { 10 | arr = new int[10]; 11 | size = 0; 12 | add(value); 13 | } 14 | 15 | public void add(int value) { 16 | if (size == arr.length) { 17 | arr = Arrays.copyOf(arr, 3 * arr.length / 2); 18 | } 19 | arr[size++] = value; 20 | } 21 | 22 | public int get(int position) throws IndexOutOfBoundsException { 23 | if (position >= size || position < 0) { 24 | throw new IndexOutOfBoundsException("bad position"); 25 | } 26 | return arr[position]; 27 | } 28 | 29 | public int getSize() { 30 | return size; 31 | } 32 | } -------------------------------------------------------------------------------- /WordStatFirstIndex/MyClasses/Scanner.java: -------------------------------------------------------------------------------- 1 | package MyClasses; 2 | 3 | import java.io.*; 4 | 5 | public class Scanner implements AutoCloseable { 6 | private Reader br; 7 | private Checker checker; 8 | private char saved; 9 | private boolean hasSaved; 10 | 11 | public Scanner(Reader r, Checker checker) { 12 | this.checker = checker; 13 | br = r; 14 | hasSaved = false; 15 | saved = 0; 16 | } 17 | 18 | public void close() throws IOException { 19 | br.close(); 20 | } 21 | 22 | private boolean readInput() throws IOException { 23 | if (!hasSaved) { 24 | int res = br.read(); 25 | if (res < 0) { 26 | return false; 27 | } 28 | saved = (char)res; 29 | hasSaved = true; 30 | } 31 | return true; 32 | } 33 | 34 | private boolean hasInput() throws IOException { 35 | return (hasSaved) || readInput(); 36 | } 37 | 38 | private void skipWhitespacesExceptSeparator(Checker checker) throws IOException { 39 | while (hasInput() && !checker.isWordCharacter(saved) && saved != '\n') { 40 | hasSaved = false; 41 | } 42 | } 43 | 44 | public boolean isEndOfLine() throws IOException { 45 | skipWhitespacesExceptSeparator(checker); 46 | return !hasInput() || saved == '\n'; 47 | } 48 | 49 | public String next() throws IOException { 50 | skipWhitespacesExceptSeparator(checker); 51 | StringBuilder result = new StringBuilder(); 52 | while (hasInput() && checker.isWordCharacter(saved)) { 53 | result.append(saved); 54 | hasSaved = false; 55 | } 56 | return result.toString(); 57 | } 58 | 59 | public boolean hasNext() throws IOException { 60 | while (hasInput() && !checker.isWordCharacter(saved)) { 61 | hasSaved = false; 62 | } 63 | return hasInput(); 64 | } 65 | } -------------------------------------------------------------------------------- /WordStatFirstIndex/WordStatIntList.java: -------------------------------------------------------------------------------- 1 | import MyClasses.IntList; 2 | 3 | 4 | public class WordStatIntList { 5 | private int lastLine; 6 | private int count; 7 | private IntList arr; 8 | 9 | public WordStatIntList(int value, int lastLine) { 10 | arr = new IntList(value); 11 | this.lastLine = lastLine; 12 | this.count = 1; 13 | } 14 | 15 | public void add(int position, int lineNum) { 16 | count++; 17 | if (lastLine != lineNum) { 18 | arr.add(position); 19 | lastLine = lineNum; 20 | } 21 | } 22 | 23 | public String toString() { 24 | StringBuilder result = new StringBuilder(); 25 | result.append(count).append(' '); 26 | for (int i = 0; i < arr.getSize(); i++) { 27 | result.append(arr.get(i)); 28 | if (i + 1 != arr.getSize()) { 29 | result.append(' '); 30 | } 31 | } 32 | return result.toString(); 33 | } 34 | } -------------------------------------------------------------------------------- /ticTacToe/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml -------------------------------------------------------------------------------- /ticTacToe/.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /ticTacToe/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /ticTacToe/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /ticTacToe/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/Board.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | public interface Board { 4 | Position getPosition(); 5 | Cell getCell(); 6 | Result makeMove(Move move); 7 | int getN(); 8 | int getM(); 9 | int getK(); 10 | } 11 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/Cell.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | public class Cell { 4 | private char color; 5 | 6 | public Cell() { 7 | new Cell('E'); 8 | } 9 | 10 | public Cell(char color) { 11 | this.color = color; 12 | } 13 | 14 | @Override 15 | public boolean equals(Object obj) { 16 | if (obj instanceof Cell) { 17 | return color == ((Cell) obj).color; 18 | } 19 | return false; 20 | } 21 | 22 | @Override 23 | public int hashCode() { 24 | return color; 25 | } 26 | 27 | @Override 28 | public String toString() { 29 | return Character.toString(color); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/Game.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | import java.util.List; 4 | 5 | public class Game { 6 | private final boolean log; 7 | private final List players; 8 | 9 | public Game(final boolean log, final List players) { 10 | this.log = log; 11 | this.players = players; 12 | } 13 | 14 | public int play(Board board) { 15 | while (true) { 16 | for (int i = 0; i < players.size(); i++) { 17 | final int result = move(board, players.get(i), i); 18 | if (result != -2) { 19 | return result; 20 | } 21 | } 22 | 23 | } 24 | } 25 | 26 | private int move(final Board board, final Player player, final int no) { 27 | final Move move = player.move(board.getPosition(), board.getCell()); 28 | final Result result = board.makeMove(move); 29 | log("Player " + no + " move: " + move); 30 | log("Position:\n" + board); 31 | if (result == Result.WIN) { 32 | log("Player " + no + " won"); 33 | return no; 34 | } else if (result == Result.LOSE) { 35 | log("Player " + no + " lose"); 36 | return (no + 1) % players.size(); 37 | } else if (result == Result.DRAW) { 38 | log("Draw"); 39 | return -1; 40 | } else { 41 | return -2; 42 | } 43 | } 44 | 45 | private void log(final String message) { 46 | if (log) { 47 | System.out.println(message); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/HumanPlayer.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | import java.io.PrintStream; 4 | import java.util.Scanner; 5 | 6 | public class HumanPlayer implements Player { 7 | private final PrintStream out; 8 | private final Scanner in; 9 | 10 | public HumanPlayer(final PrintStream out, final Scanner in) { 11 | this.out = out; 12 | this.in = in; 13 | } 14 | 15 | public HumanPlayer() { 16 | this(System.out, new Scanner(System.in)); 17 | } 18 | 19 | int getNext(Scanner line) { 20 | if (line.hasNextInt()) { 21 | return line.nextInt(); 22 | } else { 23 | return -1; 24 | } 25 | } 26 | 27 | private Move scanMove(Cell turn) { 28 | int row, column; 29 | Scanner line = new Scanner(in.nextLine()); 30 | row = getNext(line); 31 | column = getNext(line); 32 | // I need this "if", if I want to read only two integers. 33 | // Delete it, if you want. 34 | if (line.hasNext()) { 35 | row = -1; 36 | column = -1; 37 | } 38 | return new Move(row, column, turn); 39 | } 40 | 41 | @Override 42 | public Move move(final Position position, final Cell cell) { 43 | while (true) { 44 | out.println("Position"); 45 | out.println(position); 46 | out.println(cell + "'s move"); 47 | out.println("Enter row and column in same line"); 48 | final Move move = scanMove(cell); 49 | if (position.isValid(move)) { 50 | return move; 51 | } 52 | out.println("Move " + move + " is invalid"); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/Main.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | import java.util.List; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | int n = 4, m = 4, k = 4; 8 | List players = List.of(new HumanPlayer(), new SequentialPlayer(), new SequentialPlayer()); 9 | int playerCount = players.size(); 10 | for (int testCount = 0; testCount < 10; testCount++) { 11 | final Game game = new Game(true, players); 12 | int result = game.play(new NMKBoard(n, m, k, playerCount)); 13 | System.out.println("Game number: " + testCount); 14 | if (result >= 0) { 15 | System.out.println("Player: " + (result + 1) + " won"); 16 | } else { 17 | System.out.println("Draw!"); 18 | } 19 | System.out.println("Result: " + (result + 1)); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/Move.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | public final class Move { 4 | private final int row; 5 | private final int column; 6 | private final Cell value; 7 | 8 | public Move(final int row, final int column, final Cell value) { 9 | this.row = row; 10 | this.column = column; 11 | this.value = value; 12 | } 13 | 14 | public int getRow() { 15 | return row; 16 | } 17 | 18 | public int getColumn() { 19 | return column; 20 | } 21 | 22 | public Cell getValue() { 23 | return value; 24 | } 25 | 26 | @Override 27 | public String toString() { 28 | return "row=" + row + ", column=" + column + ", value=" + value; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/Player.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | public interface Player { 4 | Move move(Position position, Cell cell); 5 | } 6 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/Position.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | public interface Position { 4 | boolean isValid(Move move); 5 | Cell getCell(int r, int c); 6 | int getN(); 7 | int getM(); 8 | int getK(); 9 | } 10 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/ProxyPosition.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | public class ProxyPosition implements Position { 4 | private Position position; 5 | 6 | ProxyPosition(Position board) { 7 | this.position = board; 8 | } 9 | 10 | @Override 11 | public boolean isValid(Move move) { 12 | return position.isValid(move); 13 | } 14 | 15 | @Override 16 | public Cell getCell(int r, int c) { 17 | return position.getCell(r, c); 18 | } 19 | 20 | @Override 21 | public int getN() { 22 | return position.getN(); 23 | } 24 | 25 | @Override 26 | public int getM() { 27 | return position.getM(); 28 | } 29 | 30 | @Override 31 | public int getK() { 32 | return position.getK(); 33 | } 34 | 35 | @Override 36 | public String toString() { 37 | return position.toString(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/RandomPlayer.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | import java.util.Random; 4 | 5 | public class RandomPlayer implements Player { 6 | private final Random random; 7 | 8 | public RandomPlayer(final Random random) { 9 | this.random = random; 10 | } 11 | 12 | public RandomPlayer() { 13 | this(new Random()); 14 | } 15 | 16 | @Override 17 | public Move move(final Position position, final Cell cell) { 18 | while (true) { 19 | int r = random.nextInt(position.getN()); 20 | int c = random.nextInt(position.getM()); 21 | final Move move = new Move(r, c, cell); 22 | if (position.isValid(move)) { 23 | return move; 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/Result.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | public enum Result { 4 | WIN, LOSE, DRAW, UNKNOWN 5 | } 6 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/SequentialPlayer.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | public class SequentialPlayer implements Player { 4 | @Override 5 | public Move move(final Position position, final Cell cell) { 6 | for (int r = 0; r < position.getN(); r++) { 7 | for (int c = 0; c < position.getM(); c++) { 8 | final Move move = new Move(r, c, cell); 9 | if (position.isValid(move)) { 10 | return move; 11 | } 12 | } 13 | } 14 | throw new IllegalStateException("No valid moves"); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ticTacToe/src/MNK/TicTacToe.java: -------------------------------------------------------------------------------- 1 | package MNK; 2 | 3 | public class TicTacToe extends NMKBoard { 4 | TicTacToe() { 5 | super(3, 3, 3, 2); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /ticTacToe/ticTacToe.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | --------------------------------------------------------------------------------