הרכבת האחרונה של הלילה עוברת בשש תחנות. בכל תחנה שלוש משימות ושומר. כותבים בעורך, מריצים ב-IntelliJ ומשווים את הפלט, ובכל משימה יש רמזים ופתרון מוסתר.
The last train of the night passes six stops. Each stop has three tasks and a keeper. Write in the editor, run in IntelliJ and compare the output; each task has hints and a hidden solution.
הרכבת האחרונה של הלילה עוצרת ברציף שבו כל השלטים התבלבלו. הכרטיסן מבקש עזרה: לחשב, לעגל ולסדר טקסט לפני שהרכבת יוצאת.
The last train of the night stops at a platform where every sign got scrambled. The conductor asks for help: calculate, round and tidy some text before the train leaves.
משימהTask 1
מחיר כרטיסTicket price
כתבו static double fare(int stops, boolean student): כל תחנה עולה 2.5 ₪, ותלמיד מקבל 50% הנחה. עגלו לשתי ספרות אחרי הנקודה. main מדפיס 10.0 3.75.
Write static double fare(int stops, boolean student): each stop costs 2.5, and students get 50% off. Round to two decimals. main prints 10.0 3.75.
איך הפלט אמור להיראות?What should the output look like?
10.0 3.75
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
משימהTask 2
שלט מתוקןA fixed sign
השלטים כתובים בבלגן: " tEL aVIV ". כתבו static String fix(String sign) שמחזירה את הטקסט בלי רווחים בקצוות, כל מילה מתחילה באות גדולה והשאר קטנות.
The signs are a mess: " tEL aVIV ". Write static String fix(String sign) returning the text with no spaces at the ends, each word starting with a capital and the rest lowercase.
איך הפלט אמור להיראות?What should the output look like?
Tel Aviv
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:sign.trim().split("\\s+") מפרק למילים.sign.trim().split("\\s+") splits into words.
איך הפלט אמור להיראות?What should the output look like?
2:15 0:05
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:/ ו-% עם int./ and % with ints.
רמזHint 2:%02d מוסיף אפס מוביל.%02d adds a leading zero.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנהStation keeper
שומר הרציף: הכרטיסןPlatform keeper: the Conductor
הכרטיסן בודק כרטיס בפורמט "NAME-STOPS-TYPE", למשל "noa-4-student". כתבו static String ticket(String code) שמחזירה "Noa: 4 stops, 5.0" (שם עם אות ראשונה גדולה, מספר התחנות, והמחיר לפי fare מהמשימה הראשונה; TYPE הוא student או adult). אם הקוד לא תקין (לא שלושה חלקים, או STOPS לא מספר), החזירו "Invalid ticket".
The conductor checks a ticket in the format "NAME-STOPS-TYPE", for example "noa-4-student". Write static String ticket(String code) returning "Noa: 4 stops, 5.0" (the name with a capital first letter, the number of stops, and the price by the first task's fare; TYPE is student or adult). If the code is invalid (not three parts, or STOPS isn't a number), return "Invalid ticket".
איך הפלט אמור להיראות?What should the output look like?
Noa: 4 stops, 5.0
Invalid ticket
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:code.split("-").code.split("-").
רמזHint 2:parts[1].matches("\\d+") בודק שזה מספר, לפני parseInt.parts[1].matches("\\d+") checks it's a number, before parseInt.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
2
תחנה 2: צומת המתודותStop 2: Methods Junction
בצומת עוברות עשרות רכבות, וכל אחת צריכה החלטה. כאן מפרקים עבודה למתודות, עוברים על מערכים, ולא נותנים לקלט גרוע להפיל את המערכת.
Dozens of trains pass the junction, and each needs a decision. Here you split work into methods, walk arrays, and don't let bad input bring the system down.
משימהTask 1
ספירת איחוריםCounting delays
כתבו static int lateCount(int[] delays) שמחזירה כמה רכבות איחרו ביותר מ-5 דקות.
Write static int lateCount(int[] delays) returning how many trains were more than 5 minutes late.
איך הפלט אמור להיראות?What should the output look like?
2
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:for-each ומונה.A for-each and a counter.
הפתרון שלנוOur solution
Main.java
publicclass Main {
staticint lateCount(int[] delays) {
int count =0;
for (int d : delays) {
if (d >5) {
count++;
}
}
return count;
}
publicstaticvoidmain(String[] args) {
System.out.println(lateCount(newint[]{0, 6, 5, 12, 3}));
}
}
פלטOutput
2
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
משימהTask 2
לוח זמניםA timetable
כתבו static String[] timetable(int start, int every, int count) שמחזירה מערך של שעות יציאה "HH:MM", החל מ-start (בדקות מחצות), כל every דקות, count פעמים. אחרי 23:59 חוזרים ל-00:00.
Write static String[] timetable(int start, int every, int count) returning an array of "HH:MM" departure times, starting at start (minutes after midnight), every every minutes, count times. After 23:59 wrap to 00:00.
איך הפלט אמור להיראות?What should the output look like?
[23:30, 23:50, 00:10]
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:t % (24 * 60).t % (24 * 60).
רמזHint 2:String.format("%02d:%02d", h, m).String.format("%02d:%02d", h, m).
הפתרון שלנוOur solution
Main.java
import java.util.Arrays;
publicclass Main {
staticString[] timetable(int start, int every, int count) {
String[] times =newString[count];
for (int i =0; i < count; i++) {
int t = (start + i * every) % (24*60);
times[i] =String.format("%02d:%02d", t /60, t %60);
}
return times;
}
publicstaticvoidmain(String[] args) {
System.out.println(Arrays.toString(timetable(23*60+30, 20, 3)));
}
}
פלטOutput
[23:30, 23:50, 00:10]
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
משימהTask 3
מספר רציףA platform number
המשתמשים מקלידים מספר רציף. כתבו static int platform(String text) שמחזירה את המספר (1 עד 12, רווחים בקצוות מותרים), או -1 אם זה לא מספר או מחוץ לטווח. אסור שהתוכנית תקרוס.
Users type a platform number. Write static int platform(String text) returning the number (1 to 12, spaces at the ends allowed), or -1 if it isn't a number or is out of range. The program must never crash.
איך הפלט אמור להיראות?What should the output look like?
7 -1 -1
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 2:try/catch סביב ה-parse.try/catch around the parse.
הפתרון שלנוOur solution
Main.java
publicclass Main {
staticint platform(String text) {
try {
int p =Integer.parseInt(text.trim());
return p >=1&& p <=12? p :-1;
} catch (NumberFormatException e) {
return-1;
}
}
publicstaticvoidmain(String[] args) {
System.out.println(platform(" 7 ") +" "+ platform("seven") +" "+ platform("13"));
}
}
פלטOutput
7 -1 -1
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנהStation keeper
שומר הצומת: המסדרןJunction keeper: the Dispatcher
המסדרן רוצה דוח: כתבו static String report(int[] delays) שמחזירה שלוש שורות: trains: N, on time: K (עיכוב 0 או פחות) ו-worst: W (העיכוב הגדול ביותר, או 0 אם אין רכבות). עם לולאה, בלי Math.max ובלי streams.
The dispatcher wants a report: write static String report(int[] delays) returning three lines: trains: N, on time: K (a delay of 0 or less) and worst: W (the largest delay, or 0 if there are no trains). With a loop, without Math.max and without streams.
איך הפלט אמור להיראות?What should the output look like?
trains: 5
on time: 2
worst: 12
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:התחילו עם int worst = 0 ועדכנו בלולאה.Start with int worst = 0 and update it in the loop.
רמזHint 2:שורות מחברים עם "\n".Join lines with "\n".
הפתרון שלנוOur solution
Main.java
publicclass Main {
staticString report(int[] delays) {
int onTime =0;
int worst =0;
for (int d : delays) {
if (d <=0) {
onTime++;
}
if (d > worst) {
worst = d;
}
}
return"trains: "+ delays.length+"\n"+"on time: "+ onTime +"\n"+"worst: "+ worst;
}
publicstaticvoidmain(String[] args) {
System.out.println(report(newint[]{0, 7, -1, 12, 3}));
}
}
פלטOutput
trains: 5
on time: 2
worst: 12
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
3
תחנה 3: מחסן העצמיםStop 3: The Object Depot
במחסן חונים הקרונות. כל קרון הוא עצם עם מצב משלו, ואסור שמישהו מבחוץ ישנה לו את המושבים בלי לשאול. כאן בונים מחלקות שמגינות על עצמן.
The wagons park at the depot. Each wagon is an object with its own state, and nobody outside may change its seats without asking. Here you build classes that protect themselves.
משימהTask 1
רכבת מוגנתA protected train
כתבו מחלקה Train עם שדות private של מזהה ומספר נוסעים, בנאי שמקבל מזהה, board(int n) שזורקת IllegalArgumentException על מספר שלילי, getPassengers(), ו-toString() שמחזיר IC-12 (40).
Write a Train class with private fields for an id and a passenger count, a constructor taking the id, board(int n) that throws IllegalArgumentException on a negative number, getPassengers(), and toString() returning IC-12 (40).
איך הפלט אמור להיראות?What should the output look like?
IC-12 (40)
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:private final String id;private final String id;
רמזHint 2:@Override public String toString().@Override public String toString().
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
משימהTask 2
מונה כרטיסיםA ticket counter
כל Ticket חדש מקבל מספר רץ. כתבו מחלקה עם שדה static int issued ושדה final int number, כך ששלושה כרטיסים מדפיסים 1 2 3 issued=3.
Each new Ticket gets a running number. Write a class with a static int issued field and a final int number field, so three tickets print 1 2 3 issued=3.
איך הפלט אמור להיראות?What should the output look like?
1 2 3 issued=3
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:השדה הסטטי שייך למחלקה, לא לעצם: יש רק אחד.The static field belongs to the class, not the object: there is only one.
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
Ticket a =new Ticket();
Ticket b =new Ticket();
Ticket c =new Ticket();
System.out.println(a.number +" "+ b.number +" "+ c.number +" issued="+ Ticket.issued);
}
}
class Ticket {
staticint issued =0;
finalint number;
Ticket() {
issued++;
number = issued;
}
}
פלטOutput
1 2 3 issued=3
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
משימהTask 3
תחנות בלי כפילויותStations without duplicates
Station עם שם ומספר קו. שתי תחנות עם אותו שם ואותו קו הן אותה תחנה. כתבו equals ו-hashCode כך ש-HashSet של Haifa, Akko, Haifa יהיה בגודל 2.
A Station with a name and a line number. Two stations with the same name and line are the same station. Write equals and hashCode so a HashSet of Haifa, Akko, Haifa has size 2.
איך הפלט אמור להיראות?What should the output look like?
2
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 2:o instanceof Station s בודק וממיר בבת אחת.o instanceof Station s checks and casts at once.
הפתרון שלנוOur solution
Main.java
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
publicclass Main {
publicstaticvoidmain(String[] args) {
Set<Station> stops =newHashSet<>();
stops.add(new Station("Haifa", 1));
stops.add(new Station("Akko", 1));
stops.add(new Station("Haifa", 1));
System.out.println(stops.size());
}
}
class Station {
privatefinalString name;
privatefinalint line;
Station(String name, int line) {
this.name = name;
this.line = line;
}
@Overridepublicbooleanequals(Object o) {
if (this== o) {
returntrue;
}
if (!(o instanceof Station s)) {
returnfalse;
}
return line == s.line && name.equals(s.name);
}
@Overridepublicint hashCode() {
return Objects.hash(name, line);
}
}
פלטOutput
2
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנהStation keeper
שומר המחסן: מנהל הקרונותDepot keeper: the Wagon Master
כתבו מחלקה Wagon עם מספר מושבים. book() תופס את המושב הפנוי הנמוך ביותר ומחזיר את מספרו (מ-1), או -1 אם הקרון מלא. cancel(int seat) משחרר מושב ומחזיר true, או false אם המספר לא קיים או שהמושב כבר פנוי. free() מחזיר כמה מושבים פנויים. המערך private. main מדפיס 1 2 true 1 3 -1 0.
Write a Wagon class with a number of seats. book() takes the lowest free seat and returns its number (from 1), or -1 if the wagon is full. cancel(int seat) frees a seat and returns true, or false if the number doesn't exist or the seat is already free. free() returns how many seats are free. The array is private. main prints 1 2 true 1 3 -1 0.
איך הפלט אמור להיראות?What should the output look like?
1 2 true 1 3 -1 0
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:מערך boolean[] שמסמן מושבים תפוסים.A boolean[] marking taken seats.
רמזHint 2:מושב N הוא האינדקס N-1.Seat N is index N-1.
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
Wagon w =new Wagon(3);
System.out.println(w.book() +" "+ w.book() +" "+ w.cancel(1) +" "+ w.book() +" "+ w.book() +" "+ w.book() +" "+ w.free());
}
}
class Wagon {
privatefinalboolean[] taken;
Wagon(int seats) {
taken =newboolean[seats];
}
int book() {
for (int i =0; i < taken.length; i++) {
if (!taken[i]) {
taken[i] =true;
return i +1;
}
}
return-1;
}
boolean cancel(int seat) {
if (seat <1|| seat > taken.length||!taken[seat -1]) {
returnfalse;
}
taken[seat -1] =false;
returntrue;
}
int free() {
int n =0;
for (boolean t : taken) {
if (!t) {
n++;
}
}
return n;
}
}
פלטOutput
1 2 true 1 3 -1 0
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
4
תחנה 4: גשר הממשקיםStop 4: Interface Bridge
על הגשר עוברים כל סוגי הנוסעים, וכל אחד משלם אחרת. במקום if ארוך לכל סוג, נותנים לכל סוג להחליט בעצמו: ממשקים, Generics, records ו-switch שיודע מה בפנים.
Every kind of passenger crosses the bridge, and each pays differently. Instead of a long if for every kind, let each kind decide for itself: interfaces, generics, records and a switch that knows what's inside.
An interface Pass with double price(int stops), and three classes: Regular (2.5 per stop), Student (half), Senior (free). Write static double total(List<Pass> passes, int stops). For 4 stops: 15.0.
איך הפלט אמור להיראות?What should the output look like?
15.0
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:המתודה ב-class שמממש ממשק חייבת להיות public.A method in a class implementing an interface must be public.
הפתרון שלנוOur solution
Main.java
import java.util.List;
publicclass Main {
staticdouble total(List<Pass> passes, int stops) {
double sum =0;
for (Pass p : passes) {
sum += p.price(stops);
}
return sum;
}
publicstaticvoidmain(String[] args) {
List<Pass> passes =List.of(new Regular(), new Student(), new Senior());
System.out.println(total(passes, 4));
}
}
interface Pass {
double price(int stops);
}
class Regular implements Pass {
publicdouble price(int stops) {
return stops *2.5;
}
}
class Student implements Pass {
publicdouble price(int stops) {
return stops *2.5/2;
}
}
class Senior implements Pass {
publicdouble price(int stops) {
return0;
}
}
פלטOutput
15.0
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
משימהTask 2
הגדול ביותר, מכל טיפוסThe largest, of any type
כתבו מתודה גנרית static <T extends Comparable<T>> T maxOf(List<T> items) שמחזירה את האיבר הגדול ביותר, וזורקת IllegalArgumentException על רשימה ריקה. main מדפיס 9 train.
Write a generic method static <T extends Comparable<T>> T maxOf(List<T> items) returning the largest item, and throwing IllegalArgumentException on an empty list. main prints 9 train.
איך הפלט אמור להיראות?What should the output look like?
9 train
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
import java.util.List;
publicclass Main {
static<T extendsComparable<T>> T maxOf(List<T> items) {
if (items.isEmpty()) {
thrownewIllegalArgumentException("empty list");
}
T best = items.get(0);
for (T x : items) {
if (x.compareTo(best) >0) {
best = x;
}
}
return best;
}
publicstaticvoidmain(String[] args) {
System.out.println(maxOf(List.of(3, 9, 2)) +" "+ maxOf(List.of("bus", "train", "car")));
}
}
פלטOutput
9 train
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
משימהTask 3
נסיעה שבודקת את עצמהA trip that checks itself
record Trip(String from, String to, int minutes) עם בנאי קומפקטי שזורק IllegalArgumentException("minutes must be positive") כשהדקות 0 או פחות, ומתודה isLong() (מעל 60). main מדפיס את הנסיעה ואת הדחייה.
record Trip(String from, String to, int minutes) with a compact constructor that throws IllegalArgumentException("minutes must be positive") when the minutes are 0 or less, and an isLong() method (over 60). main prints the trip and the rejection.
איך הפלט אמור להיראות?What should the output look like?
Trip[from=Haifa, to=Eilat, minutes=300] long=true
rejected: minutes must be positive
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:בנאי קומפקטי: Trip { ... } בלי רשימת פרמטרים.A compact constructor: Trip { ... } with no parameter list.
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
Trip t =new Trip("Haifa", "Eilat", 300);
System.out.println(t +" long="+ t.isLong());
try {
new Trip("Akko", "Akko", 0);
} catch (IllegalArgumentException e) {
System.out.println("rejected: "+ e.getMessage());
}
}
}
record Trip(String from, String to, int minutes) {
Trip {
if (minutes <=0) {
thrownewIllegalArgumentException("minutes must be positive");
}
}
boolean isLong() {
return minutes >60;
}
}
פלטOutput
Trip[from=Haifa, to=Eilat, minutes=300] long=true
rejected: minutes must be positive
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנהStation keeper
שומר הגשר: לוח ההודעותBridge keeper: the Announcement Board
sealed interface Event עם שלושה records: Delay(int minutes), Cancel(String reason) ו-OnTime(). כתבו static String describe(Event e) עם switch ותבניות record: עיכוב מעל 30 → very late: 45 min, עיכוב אחר → late: 5 min, ביטול → cancelled: storm, בזמן → on time. בלי default: הקומפיילר יודע שכיסיתם הכול.
A sealed interface Event with three records: Delay(int minutes), Cancel(String reason) and OnTime(). Write static String describe(Event e) with a switch and record patterns: a delay over 30 → very late: 45 min, any other delay → late: 5 min, a cancellation → cancelled: storm, on time → on time. No default: the compiler knows you covered everything.
איך הפלט אמור להיראות?What should the output look like?
very late: 45 min
late: 5 min
cancelled: storm
on time
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:case Delay(int min) when min > 30 -> לפני case Delay(int min) ->.case Delay(int min) when min > 30 -> before case Delay(int min) ->.
publicclass Main {
staticString describe(Event e) {
returnswitch (e) {
case Delay(int min) when min >30->"very late: "+ min +" min";
case Delay(int min) ->"late: "+ min +" min";
case Cancel(String reason) ->"cancelled: "+ reason;
case OnTime() ->"on time";
};
}
publicstaticvoidmain(String[] args) {
System.out.println(describe(new Delay(45)));
System.out.println(describe(new Delay(5)));
System.out.println(describe(new Cancel("storm")));
System.out.println(describe(new OnTime()));
}
}
sealedinterface Event permits Delay, Cancel, OnTime {
}
record Delay(int minutes) implements Event {
}
record Cancel(String reason) implements Event {
}
record OnTime() implements Event {
}
פלטOutput
very late: 45 min
late: 5 min
cancelled: storm
on time
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
5
תחנה 5: מרכז הבקרהStop 5: Control Center
במרכז הבקרה זורמים נתונים מכל הקווים. צריך לסנן, לספור ולמצוא, ולא ליפול על שורה שבורה. כאן עובדים עם Streams, Map ו-Optional.
Data streams into the control center from every line. You need to filter, count and find, without falling over a broken row. Here you work with streams, maps and Optional.
משימהTask 1
סינון תחנותFiltering stations
כתבו static List<String> pick(List<String> names, char first) עם stream: השמות שמתחילים באות (בלי תלות באותיות גדולות), באותיות גדולות וממוינים. main מדפיס [HADERA, HAIFA, HERZLIYA].
Write static List<String> pick(List<String> names, char first) with a stream: the names starting with the letter (ignoring case), in capitals and sorted. main prints [HADERA, HAIFA, HERZLIYA].
איך הפלט אמור להיראות?What should the output look like?
[HADERA, HAIFA, HERZLIYA]
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
משימהTask 2
נסיעות לפי קוRides per line
כתבו static Map<String, Integer> countLines(List<String> rides) שסופרת כמה נסיעות היו בכל קו, ב-TreeMap (ממוין לפי שם). main מדפיס {blue=2, red=3}.
Write static Map<String, Integer> countLines(List<String> rides) counting the rides on each line, in a TreeMap (sorted by name). main prints {blue=2, red=3}.
איך הפלט אמור להיראות?What should the output look like?
{blue=2, red=3}
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
משימהTask 3
חיפוש בלי nullA search without null
כתבו static Optional<String> findStation(List<String> stations, String prefix) שמחזירה את התחנה הראשונה שמתחילה ב-prefix (בלי תלות באותיות גדולות), או Optional.empty(). main מדפיס Haifa Center | none.
Write static Optional<String> findStation(List<String> stations, String prefix) returning the first station starting with prefix (ignoring case), or Optional.empty(). main prints Haifa Center | none.
איך הפלט אמור להיראות?What should the output look like?
Haifa Center | none
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:stream().filter(...).findFirst() כבר מחזיר Optional.stream().filter(...).findFirst() already returns an Optional.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנהStation keeper
שומרת הבקרה: האנליסטיתControl keeper: the Analyst
כל שורה בקובץ: name,line,minutes. כתבו static Map<String, Double> avgByLine(List<String> rows) שמחזירה את ממוצע הדקות בכל קו, ממוין לפי שם הקו. שורה שאין בה שלושה חלקים, או שהדקות בה לא מספר, מדלגים עליה. main מדפיס {blue=15.0, red=12.5}.
Each row in the file: name,line,minutes. Write static Map<String, Double> avgByLine(List<String> rows) returning the average minutes on each line, sorted by line name. A row without three parts, or whose minutes aren't a number, is skipped. main prints {blue=15.0, red=12.5}.
איך הפלט אמור להיראות?What should the output look like?
{blue=15.0, red=12.5}
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:record Ride ומתודה parse שמחזירה null על שורה שבורה.A Ride record and a parse method that returns null for a broken row.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
6
תחנה 6: מגדל ה-ThreadsStop 6: The Threads Tower
התחנה האחרונה היא מגדל שבו כמה רכבות פועלות באותו רגע. כל מי שנוגע במשהו משותף חייב לתאם, אחרת מספרים נעלמים. כאן ה-threads אמיתיים.
The last stop is a tower where several trains run at the same moment. Anyone touching something shared must coordinate, or numbers vanish. Here the threads are real.
משימהTask 1
מונה שלא מאבדA counter that never loses
כתבו static int countWith(int threads, int each) שמפעילה threads threads, כל אחד מוסיף 1 each פעמים למונה משותף, מחכה לכולם ומחזירה את התוצאה. היא חייבת להיות בדיוק threads × each בכל הרצה.
Write static int countWith(int threads, int each) that starts threads threads, each adding 1 to a shared counter each times, waits for all of them and returns the result. It must be exactly threads × each on every run.
איך הפלט אמור להיראות?What should the output look like?
4000
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:AtomicInteger ו-incrementAndGet().AtomicInteger and incrementAndGet().
רמזHint 2:join() לכל thread לפני get().join() every thread before get().
הפתרון שלנוOur solution
Main.java
import java.util.concurrent.atomic.AtomicInteger;
publicclass Main {
staticint countWith(int threads, int each) throws InterruptedException {
AtomicInteger count =newAtomicInteger();
Thread[] all =newThread[threads];
for (int i =0; i < threads; i++) {
all[i] =newThread(() -> {
for (int k =0; k < each; k++) {
count.incrementAndGet();
}
});
all[i].start();
}
for (Thread t : all) {
t.join();
}
return count.get();
}
publicstaticvoidmain(String[] args) throws InterruptedException {
System.out.println(countWith(4, 1000));
}
}
פלטOutput
4000
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
משימהTask 2
סכום בבריכהA sum in a pool
כתבו static long parallelSum(int n, int parts) שמחשבת 1 + 2 + … + n: מחלקים ל-parts חלקים, כל חלק הוא משימה ב-ExecutorService עם parts threads, ומחברים את התוצאות מה-Future. לא לשכוח shutdown.
Write static long parallelSum(int n, int parts) computing 1 + 2 + … + n: split into parts pieces, each piece is a task in an ExecutorService with parts threads, and add up the Future results. Don't forget shutdown.
איך הפלט אמור להיראות?What should the output look like?
500500
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:גודל חלק: (n + parts - 1) / parts, והחלק האחרון נגמר ב-n.Piece size: (n + parts - 1) / parts, and the last piece ends at n.
רמזHint 2:משתנים שה-lambda משתמשת בהם צריכים להיות effectively final.Variables the lambda uses must be effectively final.
הפתרון שלנוOur solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
publicclass Main {
staticlong parallelSum(int n, int parts) throwsException {
ExecutorService pool =Executors.newFixedThreadPool(parts);
try {
List<Future<Long>> futures =newArrayList<>();
int size = (n + parts -1) / parts;
for (int p =0; p < parts; p++) {
int from = p * size +1;
int to =Math.min(n, (p +1) * size);
futures.add(pool.submit(() -> {
long s =0;
for (int i = from; i <= to; i++) {
s += i;
}
return s;
}));
}
long total =0;
for (Future<Long> f : futures) {
total += f.get();
}
return total;
} finally {
pool.shutdown();
}
}
publicstaticvoidmain(String[] args) throwsException {
System.out.println(parallelSum(1000, 4));
}
}
פלטOutput
500500
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
משימהTask 3
ספירה משותפתShared counting
כתבו static Map<String, Integer> countAll(List<List<String>> chunks): כל רשימה נספרת ב-thread משלה לתוך ConcurrentHashMap אחת (merge), ובסוף מחזירים TreeMap ממוין. main מדפיס {blue=2, green=1, red=3}.
Write static Map<String, Integer> countAll(List<List<String>> chunks): each list is counted on its own thread into one ConcurrentHashMap (merge), and at the end return a sorted TreeMap. main prints {blue=2, green=1, red=3}.
איך הפלט אמור להיראות?What should the output look like?
{blue=2, green=1, red=3}
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:merge של ConcurrentHashMap אטומית לכל מפתח.ConcurrentHashMap's merge is atomic per key.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
השומר מחכה למי שסיים את שלוש המשימות של התחנה. אפשר לנסות כבר עכשיו, אבל קשה יותר.The keeper waits for whoever finished the stop's three tasks. You can try now, but it's harder.
שומר התחנהStation keeper
שומר המגדל: המתזמןTower keeper: the Scheduler
כל מסלול מחושב במקביל: travel(km) מחזירה km × 2 דקות, וזורקת IllegalArgumentException על מרחק שלילי (מסלול סגור). כתבו static String plan(List<Integer> distances) עם CompletableFuture.supplyAsync על בריכה של 3 threads: מסלול שנכשל נספר כסגור (exceptionally). החזירו routes: 3 open, 1 closed, fastest 8 min, או fastest none כשאין מסלול פתוח.
Each route is computed in parallel: travel(km) returns km × 2 minutes, and throws IllegalArgumentException on a negative distance (a closed route). Write static String plan(List<Integer> distances) with CompletableFuture.supplyAsync on a pool of 3 threads: a route that fails counts as closed (exceptionally). Return routes: 3 open, 1 closed, fastest 8 min, or fastest none when no route is open.
איך הפלט אמור להיראות?What should the output look like?
routes: 3 open, 1 closed, fastest 8 min
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.