נבנה על ידיBuilt by Ariel Yohimovich

JavaJava

המסע: קו הלילהThe quest: the night line

הרכבת האחרונה של הלילה עוברת בשש תחנות. בכל תחנה שלוש משימות ושומר. כותבים בעורך, מריצים ב-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.

  1. תחנה 1: רציף המשתניםStop 1: Variables Platform
  2. תחנה 2: צומת המתודותStop 2: Methods Junction
  3. תחנה 3: מחסן העצמיםStop 3: The Object Depot
  4. תחנה 4: גשר הממשקיםStop 4: Interface Bridge
  5. תחנה 5: מרכז הבקרהStop 5: Control Center
  6. תחנה 6: מגדל ה-ThreadsStop 6: The Threads Tower

תחנה 1: רציף המשתניםStop 1: Variables Platform

הרכבת האחרונה של הלילה עוצרת ברציף שבו כל השלטים התבלבלו. הכרטיסן מבקש עזרה: לחשב, לעגל ולסדר טקסט לפני שהרכבת יוצאת.

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.
רמזHint 1: double price = stops * 2.5;double price = stops * 2.5;
רמזHint 2: עיגול: Math.round(price * 100) / 100.0.Rounding: Math.round(price * 100) / 100.0.
הפתרון שלנוOur solution
Main.java
public class Main {
    static double fare(int stops, boolean student) {
        double price = stops * 2.5;
        if (student) {
            price = price / 2;
        }
        return Math.round(price * 100) / 100.0;
    }

    public static void main(String[] args) {
        System.out.println(fare(4, false) + " " + fare(3, true));
    }
}
פלטOutput
10.0 3.75

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.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.
רמזHint 2: Character.toUpperCase(w.charAt(0)).Character.toUpperCase(w.charAt(0)).
הפתרון שלנוOur solution
Main.java
public class Main {
    static String fix(String sign) {
        StringBuilder sb = new StringBuilder();
        for (String w : sign.trim().split("\\s+")) {
            if (w.isEmpty()) {
                continue;
            }
            if (sb.length() > 0) {
                sb.append(" ");
            }
            sb.append(Character.toUpperCase(w.charAt(0))).append(w.substring(1).toLowerCase());
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(fix("  tEL aVIV  "));
    }
}
פלטOutput
Tel Aviv

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

משימהTask 3

זמן נסיעהTravel time

כתבו static String duration(int minutes) שמחזירה "H:MM": 135 → "2:15", ו-5 → "0:05".

Write static String duration(int minutes) returning "H:MM": 135 → "2:15", and 5 → "0:05".

איך הפלט אמור להיראות?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.
הפתרון שלנוOur solution
Main.java
public class Main {
    static String duration(int minutes) {
        return String.format("%d:%02d", minutes / 60, minutes % 60);
    }

    public static void main(String[] args) {
        System.out.println(duration(135) + " " + duration(5));
    }
}
פלטOutput
2:15 0:05

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

שומר התחנה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.
הפתרון שלנוOur solution
Main.java
public class Main {
    static double fare(int stops, boolean student) {
        double price = stops * 2.5;
        if (student) {
            price = price / 2;
        }
        return Math.round(price * 100) / 100.0;
    }

    static String ticket(String code) {
        String[] parts = code.split("-");
        if (parts.length != 3 || !parts[1].matches("\\d+")) {
            return "Invalid ticket";
        }
        String name = parts[0].substring(0, 1).toUpperCase() + parts[0].substring(1).toLowerCase();
        int stops = Integer.parseInt(parts[1]);
        double price = fare(stops, parts[2].equals("student"));
        return name + ": " + stops + " stops, " + price;
    }

    public static void main(String[] args) {
        System.out.println(ticket("noa-4-student"));
        System.out.println(ticket("dan-x-adult"));
    }
}
פלטOutput
Noa: 4 stops, 5.0
Invalid ticket

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

תחנה 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
public class Main {
    static int lateCount(int[] delays) {
        int count = 0;
        for (int d : delays) {
            if (d > 5) {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(lateCount(new int[]{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;

public class Main {
    static String[] timetable(int start, int every, int count) {
        String[] times = new String[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;
    }

    public static void main(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 1: Integer.parseInt זורק NumberFormatException.Integer.parseInt throws NumberFormatException.
רמזHint 2: try/catch סביב ה-parse.try/catch around the parse.
הפתרון שלנוOur solution
Main.java
public class Main {
    static int platform(String text) {
        try {
            int p = Integer.parseInt(text.trim());
            return p >= 1 && p <= 12 ? p : -1;
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    public static void main(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.

שומר התחנה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
public class Main {
    static String 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;
    }

    public static void main(String[] args) {
        System.out.println(report(new int[]{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: מחסן העצמים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().
הפתרון שלנוOur solution
Main.java
public class Main {
    public static void main(String[] args) {
        Train t = new Train("IC-12");
        t.board(30);
        t.board(10);
        System.out.println(t);
    }
}

class Train {
    private final String id;
    private int passengers;

    Train(String id) {
        this.id = id;
    }

    void board(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("negative: " + n);
        }
        passengers += n;
    }

    int getPassengers() {
        return passengers;
    }

    @Override
    public String toString() {
        return id + " (" + passengers + ")";
    }
}
פלטOutput
IC-12 (40)

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.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
public class Main {
    public static void main(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 {
    static int issued = 0;
    final int 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 1: Objects.hash(name, line).Objects.hash(name, line).
רמז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;

public class Main {
    public static void main(String[] args) {
        Set<Station> stops = new HashSet<>();
        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 {
    private final String name;
    private final int line;

    Station(String name, int line) {
        this.name = name;
        this.line = line;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Station s)) {
            return false;
        }
        return line == s.line && name.equals(s.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, line);
    }
}
פלטOutput
2

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

שומר התחנה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
public class Main {
    public static void main(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 {
    private final boolean[] taken;

    Wagon(int seats) {
        taken = new boolean[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]) {
            return false;
        }
        taken[seat - 1] = false;
        return true;
    }

    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: גשר הממשקים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.

משימהTask 1

כרטיס לכל אחדA pass for everyone

ממשק Pass עם double price(int stops), ושלוש מחלקות: Regular (2.5 לתחנה), Student (חצי), Senior (חינם). כתבו static double total(List<Pass> passes, int stops). ל-4 תחנות: 15.0.

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;

public class Main {
    static double total(List<Pass> passes, int stops) {
        double sum = 0;
        for (Pass p : passes) {
            sum += p.price(stops);
        }
        return sum;
    }

    public static void main(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 {
    public double price(int stops) {
        return stops * 2.5;
    }
}

class Student implements Pass {
    public double price(int stops) {
        return stops * 2.5 / 2;
    }
}

class Senior implements Pass {
    public double price(int stops) {
        return 0;
    }
}
פלט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.
רמזHint 1: x.compareTo(best) > 0.x.compareTo(best) > 0.
הפתרון שלנוOur solution
Main.java
import java.util.List;

public class Main {
    static <T extends Comparable<T>> T maxOf(List<T> items) {
        if (items.isEmpty()) {
            throw new IllegalArgumentException("empty list");
        }
        T best = items.get(0);
        for (T x : items) {
            if (x.compareTo(best) > 0) {
                best = x;
            }
        }
        return best;
    }

    public static void main(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
public class Main {
    public static void main(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) {
            throw new IllegalArgumentException("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.

שומר התחנה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) ->.
רמזHint 2: sealed interface Event permits Delay, Cancel, OnTime.sealed interface Event permits Delay, Cancel, OnTime.
הפתרון שלנוOur solution
Main.java
public class Main {
    static String describe(Event e) {
        return switch (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";
        };
    }

    public static void main(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()));
    }
}

sealed interface 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: מרכז הבקרה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.
רמזHint 1: filter, map(String::toUpperCase), sorted(), toList().filter, map(String::toUpperCase), sorted(), toList().
הפתרון שלנוOur solution
Main.java
import java.util.List;

public class Main {
    static List<String> pick(List<String> names, char first) {
        return names.stream()
                .filter(n -> !n.isEmpty() && Character.toLowerCase(n.charAt(0)) == Character.toLowerCase(first))
                .map(String::toUpperCase)
                .sorted()
                .toList();
    }

    public static void main(String[] args) {
        System.out.println(pick(List.of("haifa", "Akko", "hadera", "ashdod", "Herzliya"), 'h'));
    }
}
פלטOutput
[HADERA, HAIFA, HERZLIYA]

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.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.
רמזHint 1: counts.merge(line, 1, Integer::sum).counts.merge(line, 1, Integer::sum).
הפתרון שלנוOur solution
Main.java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    static Map<String, Integer> countLines(List<String> rides) {
        Map<String, Integer> counts = new TreeMap<>();
        for (String line : rides) {
            counts.merge(line, 1, Integer::sum);
        }
        return counts;
    }

    public static void main(String[] args) {
        System.out.println(countLines(List.of("red", "blue", "red", "red", "blue")));
    }
}
פלטOutput
{blue=2, red=3}

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.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.
הפתרון שלנוOur solution
Main.java
import java.util.List;
import java.util.Optional;

public class Main {
    static Optional<String> findStation(List<String> stations, String prefix) {
        String p = prefix.toLowerCase();
        return stations.stream().filter(s -> s.toLowerCase().startsWith(p)).findFirst();
    }

    public static void main(String[] args) {
        List<String> line = List.of("Nahariya", "Akko", "Haifa Center", "Haifa Hof HaCarmel");
        System.out.println(findStation(line, "hai").orElse("none") + " | " + findStation(line, "eilat").orElse("none"));
    }
}
פלטOutput
Haifa Center | none

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

שומר התחנה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.
רמזHint 2: Collectors.groupingBy(Ride::line, TreeMap::new, Collectors.averagingInt(Ride::minutes)).Collectors.groupingBy(Ride::line, TreeMap::new, Collectors.averagingInt(Ride::minutes)).
הפתרון שלנוOur solution
Main.java
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
    record Ride(String name, String line, int minutes) {
    }

    static Ride parse(String row) {
        String[] p = row.split(",");
        if (p.length != 3) {
            return null;
        }
        try {
            return new Ride(p[0].trim(), p[1].trim(), Integer.parseInt(p[2].trim()));
        } catch (NumberFormatException e) {
            return null;
        }
    }

    static Map<String, Double> avgByLine(List<String> rows) {
        return rows.stream()
                .map(Main::parse)
                .filter(r -> r != null)
                .collect(Collectors.groupingBy(Ride::line, TreeMap::new, Collectors.averagingInt(Ride::minutes)));
    }

    public static void main(String[] args) {
        List<String> rows = List.of("noa,red,10", "avi,blue,15", "dana,red,15", "bad row", "lior,blue,x");
        System.out.println(avgByLine(rows));
    }
}
פלטOutput
{blue=15.0, red=12.5}

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

תחנה 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;

public class Main {
    static int countWith(int threads, int each) throws InterruptedException {
        AtomicInteger count = new AtomicInteger();
        Thread[] all = new Thread[threads];
        for (int i = 0; i < threads; i++) {
            all[i] = new Thread(() -> {
                for (int k = 0; k < each; k++) {
                    count.incrementAndGet();
                }
            });
            all[i].start();
        }
        for (Thread t : all) {
            t.join();
        }
        return count.get();
    }

    public static void main(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;

public class Main {
    static long parallelSum(int n, int parts) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(parts);
        try {
            List<Future<Long>> futures = new ArrayList<>();
            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();
        }
    }

    public static void main(String[] args) throws Exception {
        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.
הפתרון שלנוOur solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

public class Main {
    static Map<String, Integer> countAll(List<List<String>> chunks) throws InterruptedException {
        Map<String, Integer> counts = new ConcurrentHashMap<>();
        List<Thread> threads = new ArrayList<>();
        for (List<String> chunk : chunks) {
            Thread t = new Thread(() -> {
                for (String w : chunk) {
                    counts.merge(w, 1, Integer::sum);
                }
            });
            threads.add(t);
            t.start();
        }
        for (Thread t : threads) {
            t.join();
        }
        return new TreeMap<>(counts);
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(countAll(List.of(List.of("red", "blue"), List.of("red", "red"), List.of("green", "blue"))));
    }
}
פלטOutput
{blue=2, green=1, red=3}

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

שומר התחנה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.
רמזHint 1: supplyAsync(() -> travel(d), pool).exceptionally(e -> -1).supplyAsync(() -> travel(d), pool).exceptionally(e -> -1).
רמזHint 2: join() מחכה לתוצאה בלי checked exception.join() waits for the result without a checked exception.
הפתרון שלנוOur solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    static int travel(int km) {
        if (km < 0) {
            throw new IllegalArgumentException("closed");
        }
        return km * 2;
    }

    static String plan(List<Integer> distances) {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        try {
            List<CompletableFuture<Integer>> futures = new ArrayList<>();
            for (int d : distances) {
                futures.add(CompletableFuture.supplyAsync(() -> travel(d), pool).exceptionally(e -> -1));
            }
            int open = 0;
            int closed = 0;
            int best = Integer.MAX_VALUE;
            for (CompletableFuture<Integer> f : futures) {
                int t = f.join();
                if (t < 0) {
                    closed++;
                } else {
                    open++;
                    best = Math.min(best, t);
                }
            }
            return "routes: " + open + " open, " + closed + " closed, fastest " + (open == 0 ? "none" : best + " min");
        } finally {
            pool.shutdown();
        }
    }

    public static void main(String[] args) {
        System.out.println(plan(List.of(12, 4, -1, 9)));
    }
}
פלטOutput
routes: 3 open, 1 closed, fastest 8 min

יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.

נבנה על ידיBuilt by Ariel Yohimovich