APCS Oct 2023 - m370 Q1 [Java]
Problem statement:
Food is placed at n positions, and a mouse starts at position x. The first line contains the space-separated integers x and n: the initial mouse position and the number of food items. The second line contains n space-separated food positions, none of which coincide with the mouse. All test cases guarantee 3 ≤ n ≤ 20 with n odd; the mouse and food positions are between -100 and 100.
import java.util.Scanner;
public class rat {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
String userinput = scanner.nextLine();
String[] words = userinput.split(" ");
int x = Integer.parseInt(words[0]);
int n = Integer.parseInt(words[1]);
String userinput2 = scanner.nextLine();
String[] points = userinput2.split(" ");
int fct = 0;
int bct = 0;
int[] font = new int[n];
int[] back = new int[n];
if (n >= 3 && n <= 20) {
if (n % 2 != 0) {
for (int i = 0; i < n; i++) {
int px = Integer.parseInt(points[i]);
if (px <= 100 && px >= -100) {
if (px > x) {
font[fct] = px;
fct = fct + 1;
} else if (px < x) {
back[bct] = px;
bct = bct + 1;
}
} else {
break;
}
}
int num = x;
if (bct > fct) {
for (int i = 0; i < bct; i++) {
if (back[i] < num) {
num = back[i];
}
}
System.out.println(bct + " " + num);
} else if (bct < fct) {
for (int i = 0; i < fct; i++) {
if (num < font[i]) {
num = font[i];
}
}
System.out.println(fct + " " + num);
}
}
}
scanner.close();
} catch (Exception e) {
System.out.print(e);
}
}
}
This is a problem from the 2023 APCS exam. I used a straightforward approach, adding the conditions one by one: determine which side of the mouse each food item is on and count the items, then compare the counts on both sides and find the farthest food position on the relevant side.
Key concepts:
java.util.Scanneris similar to Python’s input. UseString userinput = scanner.nextLine();.- Declare new variables with a type such as
intorString. split(" ");splits a string.int x = Integer.parseInt(words[0]);converts a String to an Int.
[name=BlackInk7777] This is my first Java program. I used Python during the APCS exam because writing it in Java took a bit too long. While writing the Java version, I also noticed a mistake in my exam code: I had forgotten a condition. QQ.
- [✔️] You may use the code directly if needed.
- [✔️] Please credit the source when sharing.

This article was translated from Traditional Chinese by AI. Meaning or wording may differ; please refer to the Traditional Chinese original as the authoritative version.