Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 50 additions & 8 deletions src/main/java/algorithms/sprint0/Zip.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static algorithms.sprint0.Utils.printList;
import static algorithms.sprint0.Utils.readList;

public class Zip {

private static final int MAX_LIST_SIZE = 100_000;
private static final int MAX_INPUT_LINE_LENGTH = 1_200_001;

static List<Integer> zip(List<Integer> a, List<Integer> b, int n) {
if (n < 0) {
throw new IllegalArgumentException("n >= 0 required");
Expand All @@ -34,14 +37,53 @@ static List<Integer> zip(List<Integer> a, List<Integer> b, int n) {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8))) {
String sizeLine = reader.readLine();
if (sizeLine == null) {
throw new EOFException("Missing list size");
try {
process(reader, writer);
} catch (IllegalArgumentException | EOFException exception) {
System.err.println("Invalid input: " + exception.getMessage());
}
int n = parseInt(sizeLine.trim());
List<Integer> a = readList(reader);
List<Integer> b = readList(reader);
printList(zip(a, b, n), writer);
}
}

static void process(BufferedReader reader, BufferedWriter writer) throws IOException {
String sizeLine = readBoundedLine(reader);
if (sizeLine == null) {
throw new EOFException("Missing list size");
}
int n = parseInt(sizeLine.trim());
if (n < 0 || n > MAX_LIST_SIZE) {
throw new IllegalArgumentException("List size must be between 0 and " + MAX_LIST_SIZE);
}
List<Integer> a = parseList(readBoundedLine(reader));
List<Integer> b = parseList(readBoundedLine(reader));
if (a.size() < n || b.size() < n) {
throw new IllegalArgumentException("Each list must contain at least n integers");
}
printList(zip(a, b, n), writer);
}

private static String readBoundedLine(BufferedReader reader) throws IOException {
StringBuilder line = new StringBuilder();
int character;
while ((character = reader.read()) != -1 && character != '\n' && character != '\r') {
if (line.length() == MAX_INPUT_LINE_LENGTH) {
throw new IllegalArgumentException("Input line is too long");
}
line.append((char) character);
}
if (character == '\r') {
reader.mark(1);
if (reader.read() != '\n') {
reader.reset();
}
}
return character == -1 && line.length() == 0 ? null : line.toString();
}

private static List<Integer> parseList(String line) throws IOException {
if (line == null) {
throw new EOFException("Missing integer list");
}
return Utils.readList(new BufferedReader(new StringReader(line)));
}
}
23 changes: 17 additions & 6 deletions src/main/java/algorithms/sprint1/SleightOfHand.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,21 @@ int nextInt() throws IOException {
return val * sign;
}

String next() throws IOException {
String next(int maxLength) throws IOException {
int c;
do {
c = read();
if (c == -1) throw new EOFException("Unexpected EOF");
} while (c <= ' ');

byte[] tmp = new byte[32];
byte[] tmp = new byte[Math.min(32, maxLength)];
int n = 0;
while (c > ' ') {
if (n == maxLength) {
throw new IOException("Token length exceeds " + maxLength);
}
if (n == tmp.length) {
byte[] t2 = new byte[tmp.length * 2];
byte[] t2 = new byte[Math.min(maxLength, tmp.length * 2)];
System.arraycopy(tmp, 0, t2, 0, tmp.length);
tmp = t2;
}
Expand Down Expand Up @@ -128,14 +131,17 @@ private static void run() throws Exception {
int[] count = new int[10];

for (int r = 0; r < 4; r++) {
StringBuilder row = new StringBuilder(in.next());
StringBuilder row = new StringBuilder(in.next(4));
// На всякий случай, если токенайзер разделит строку (обычно не будет)
while (row.length() < 4) {
row.append(in.next());
row.append(in.next(4 - row.length()));
}
for (int c = 0; c < 4; c++) {
char ch = row.charAt(c);
if (ch != '.') {
if (ch < '0' || ch > '9') {
throw new IOException("Invalid grid cell: " + ch);
}
count[ch - '0']++;
}
}
Expand Down Expand Up @@ -219,7 +225,12 @@ static int solve(int k, int[][] a) {

for (int[] row : a) {
for (int v : row) {
if (v != 0) count[v]++;
if (v != 0) {
if (v < 0 || v > 9) {
throw new IllegalArgumentException("Grid values must be between 0 and 9");
}
count[v]++;
}
}
}

Expand Down
29 changes: 27 additions & 2 deletions src/main/java/algorithms/sprint2/Deque.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
public class Deque {

// -------------------- RING BUFFER DEQUE --------------------
private static final int MAX_CAPACITY = 100_000;

static final class RingDeque {
private final int[] a;
private final int cap;
Expand All @@ -63,8 +65,8 @@ static final class RingDeque {
private int size = 0;

RingDeque(int cap) {
this.cap = cap;
this.a = new int[cap];
this.cap = validateCapacity(cap);
this.a = new int[this.cap];
}

private int next(int i) {
Expand Down Expand Up @@ -112,9 +114,19 @@ int popBack() {
}
}

private static int validateCapacity(int cap) {
if (cap < 0 || cap > MAX_CAPACITY) {
throw new IllegalArgumentException("Deque capacity is out of range");
}
return cap;
}

private static void process(FastIn in, FastOut out) throws Exception {
int n = in.nextInt();
int m = in.nextInt();
if (n < 0 || n > MAX_CAPACITY) {
throw new IllegalArgumentException("Command count is out of range");
}

RingDeque dq = new RingDeque(m);

Expand Down Expand Up @@ -235,6 +247,10 @@ private static void test() throws Exception {
)
);

// Некорректная емкость отклоняется, а не меняет заявленную семантику дека.
assertRejected("2\n-1\npush_back 1\npop_front\n");
assertRejected("1\n1000000000\npop_front\n");

// Wrap-around: head/tail должны корректно "перепрыгивать" границу массива
assertEq(
"1\n4\n2\n3\n",
Expand All @@ -261,6 +277,15 @@ static void assertEq(String exp, String act) {
}
}

private static void assertRejected(String input) throws Exception {
try {
solveIO(input);
throw new AssertionError("Expected invalid deque capacity to be rejected");
} catch (IllegalArgumentException expected) {
// Expected validation failure.
}
}

public static void main(String[] args) throws Exception {
if (System.getProperty("os.name").startsWith("Windows")) {
test();
Expand Down
40 changes: 29 additions & 11 deletions src/main/java/algorithms/sprint4/FindSystem.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,18 @@
import java.util.HashSet;
import java.util.Map;
import java.util.StringTokenizer;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

// https://contest.yandex.ru/contest/24414/run-report/160043341/

class FindSystem {

private static final int MAX_DOCUMENTS = 10_000;
private static final int MAX_QUERIES = 10_000;
private static final int MAX_LINE_LENGTH = 10_000;

/*
* Принцип работы алгоритма:
* 1) Строим обратный индекс:
Expand Down Expand Up @@ -141,23 +148,25 @@ private static boolean isBetter(int docId1, int score1, int docId2, int score2)
private static void solve() throws Exception {
FastReader reader = new FastReader(System.in);

int n = reader.nextInt();
int n = reader.nextInt(MAX_DOCUMENTS);
String[] docs = new String[n];
for (int i = 0; i < n; i++) {
docs[i] = reader.nextLine();
docs[i] = reader.nextLine(MAX_LINE_LENGTH);
}

HashMap<String, ArrayList<int[]>> index = buildIndex(docs);

int m = reader.nextInt();
StringBuilder out = new StringBuilder();
int m = reader.nextInt(MAX_QUERIES);
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(System.out, StandardCharsets.UTF_8));

for (int i = 0; i < m; i++) {
String query = reader.nextLine();
out.append(processQuery(query, index)).append('\n');
String query = reader.nextLine(MAX_LINE_LENGTH);
out.write(processQuery(query, index));
out.newLine();
}

System.out.print(out);
out.flush();
}

private static void test() {
Expand Down Expand Up @@ -229,7 +238,7 @@ private int read() throws IOException {
return buffer[ptr++];
}

int nextInt() throws IOException {
int nextInt(int max) throws IOException {
int c;
do {
c = read();
Expand All @@ -238,15 +247,21 @@ int nextInt() throws IOException {
}
} while (c <= ' ');

int value = 0;
long value = 0;
while (c > ' ') {
if (c < '0' || c > '9') {
throw new IOException("Expected a non-negative integer");
}
value = value * 10 + c - '0';
if (value > max) {
throw new IOException("Input value exceeds limit");
}
c = read();
}
return value;
return (int) value;
}

String nextLine() throws IOException {
String nextLine(int maxLength) throws IOException {
int c = read();

while (c == '\n' || c == '\r') {
Expand All @@ -255,6 +270,9 @@ String nextLine() throws IOException {

StringBuilder sb = new StringBuilder();
while (c != -1 && c != '\n' && c != '\r') {
if (sb.length() == maxLength) {
throw new IOException("Input line exceeds limit");
}
sb.append((char) c);
c = read();
}
Expand Down
Loading