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

JavaJava
42
חלקPart 7: Java בעולם האמיתיJava in the real world כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

אלגוריתמים, ראיון עבודה ופרויקט גמרAlgorithms, interviews & final project

סיבוכיות, חיפוש ומיון, שאלות ראיון נפוצות ב-Java, ותכנון פרויקט הגמר.

Complexity, searching and sorting, common Java interview questions, and planning the final project.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

חיפוש בינאריBinary search

תזכורת: מה ביקשוReminder: the task

כתבו find(sorted, target) שמחזירה אינדקס או -1. עבור השנים 1815…2004 הדפיסו 0 5 -1 (הראשון, האחרון, ו-1900 שלא קיים).

Write find(sorted, target) returning an index or -1. For the years 1815…2004 print 0 5 -1 (the first, the last, and 1900 which isn't there).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static int find(int[] sorted, int target) {
        int lo = 0;
        int hi = sorted.length - 1;
        while (lo <= hi) {
            int mid = (lo + hi) / 2;
            if (sorted[mid] == target) {
                return mid;
            } else if (sorted[mid] < target) {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] years = {1815, 1817, 1922, 1949, 1965, 2004};
        System.out.println(find(years, 1815) + " " + find(years, 2004) + " " + find(years, 1900));
    }
}
פלטOutput
0 5 -1

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

פלינדרום עם שני מצביעיםA palindrome with two pointers

תזכורת: מה ביקשוReminder: the task

isPalindrome(s) מתעלמת מאותיות גדולות, רווחים וסימנים, ומשווה מהקצוות פנימה. הדפיסו true false עבור Never odd or even ו-Java.

isPalindrome(s) ignores capitals, spaces and punctuation, and compares from the ends inward. Print true false for Never odd or even and Java.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static boolean isPalindrome(String s) {
        String clean = s.toLowerCase().replaceAll("[^a-z]", "");
        int i = 0;
        int j = clean.length() - 1;
        while (i < j) {
            if (clean.charAt(i) != clean.charAt(j)) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Never odd or even") + " " + isPalindrome("Java"));
    }
}
פלטOutput
true false

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

התו הראשון שלא חוזרThe first non-repeating character

תזכורת: מה ביקשוReminder: the task

firstUnique(s) מחזירה את התו הראשון שמופיע פעם אחת (או -). שני מעברים: ספירה, ואז חיפוש. הדפיסו w - עבור swiss ו-aabb.

firstUnique(s) returns the first character appearing once (or -). Two passes: count, then search. Print w - for swiss and aabb.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.HashMap;
import java.util.Map;

public class Main {
    static char firstUnique(String s) {
        Map<Character, Integer> count = new HashMap<>();
        for (char c : s.toCharArray()) {
            count.merge(c, 1, Integer::sum);
        }
        for (char c : s.toCharArray()) {
            if (count.get(c) == 1) {
                return c;
            }
        }
        return '-';
    }

    public static void main(String[] args) {
        System.out.println(firstUnique("swiss") + " " + firstUnique("aabb"));
    }
}
פלטOutput
w -

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

מיון הכנסהInsertion sort

תזכורת: מה ביקשוReminder: the task

כתבו את מיון ההכנסה מהתזכורת ומיינו {9, 3, 7, 3, 1}: [1, 3, 3, 7, 9].

Write the insertion sort from the refresher and sort {9, 3, 7, 3, 1}: [1, 3, 3, 7, 9].

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.Arrays;

public class Main {
    static void sort(int[] a) {
        for (int i = 1; i < a.length; i++) {
            int x = a[i];
            int j = i - 1;
            while (j >= 0 && a[j] > x) {
                a[j + 1] = a[j];
                j--;
            }
            a[j + 1] = x;
        }
    }

    public static void main(String[] args) {
        int[] a = {9, 3, 7, 3, 1};
        sort(a);
        System.out.println(Arrays.toString(a));
    }
}
פלטOutput
[1, 3, 3, 7, 9]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף, צעד 42: מיזוג שני מדפים ממויניםShelf, step 42: merging two sorted shelves

תזכורת: מה ביקשוReminder: the task

שני מדפים ממוינים לפי שנה. mergeByYear(a, b) ממזגת לרשימה ממוינת אחת ב-O(n) (בלי למיין מחדש). הדפיסו Emma Ulysses Solaris Dune Beloved.

Two shelves sorted by year. mergeByYear(a, b) merges them into one sorted list in O(n) (no re-sorting). Print Emma Ulysses Solaris Dune Beloved.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;

public class Main {
    record Book(String title, int year) {
    }

    static List<Book> mergeByYear(List<Book> a, List<Book> b) {
        List<Book> out = new ArrayList<>();
        int i = 0;
        int j = 0;
        while (i < a.size() && j < b.size()) {
            if (a.get(i).year() <= b.get(j).year()) {
                out.add(a.get(i++));
            } else {
                out.add(b.get(j++));
            }
        }
        while (i < a.size()) {
            out.add(a.get(i++));
        }
        while (j < b.size()) {
            out.add(b.get(j++));
        }
        return out;
    }

    public static void main(String[] args) {
        List<Book> home = List.of(new Book("Emma", 1815), new Book("Dune", 1965));
        List<Book> club = List.of(new Book("Ulysses", 1922), new Book("Solaris", 1961), new Book("Beloved", 1987));
        for (Book b : mergeByYear(home, club)) {
            System.out.print(b.title() + " ");
        }
        System.out.println();
    }
}
פלטOutput
Emma Ulysses Solaris Dune Beloved 

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

פיבונאצ'י בלולאהFibonacci in a loop

תזכורת: מה ביקשוReminder: the task

fib(n) בלולאה עם שני משתנים, O(n). הגרסה הרקורסיבית הפשוטה היא O(2ⁿ) ואיטית מאוד ב-30. הדפיסו 55 832040.

fib(n) in a loop with two variables, O(n). The plain recursive version is O(2ⁿ) and very slow at 30. Print 55 832040.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static int fib(int n) {
        int a = 0;
        int b = 1;
        for (int i = 0; i < n; i++) {
            int t = a + b;
            a = b;
            b = t;
        }
        return a;
    }

    public static void main(String[] args) {
        System.out.println(fib(10) + " " + fib(30));
    }
}
פלטOutput
55 832040

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

BFS: כמה צעדים בין ספריםBFS: how many steps between books

תזכורת: מה ביקשוReminder: the task

מפה של "ספרים דומים". steps(links, from, to) מוצאת במספר הצעדים הקטן ביותר עם BFS (תור ומפת מרחקים), או -1. הדפיסו 2 -1 (Dune → Solaris → Roadside Picnic).

A map of "similar books". steps(links, from, to) finds the fewest steps with BFS (a queue and a distance map), or -1. Print 2 -1 (Dune → Solaris → Roadside Picnic).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Map;

public class Main {
    static int steps(Map<String, List<String>> links, String from, String to) {
        Deque<String> queue = new ArrayDeque<>(List.of(from));
        Map<String, Integer> dist = new java.util.HashMap<>(Map.of(from, 0));
        while (!queue.isEmpty()) {
            String cur = queue.poll();
            if (cur.equals(to)) {
                return dist.get(cur);
            }
            for (String next : links.getOrDefault(cur, List.of())) {
                if (!dist.containsKey(next)) {
                    dist.put(next, dist.get(cur) + 1);
                    queue.add(next);
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Map<String, List<String>> similar = Map.of(
                "Dune", List.of("Solaris", "Foundation"),
                "Solaris", List.of("Roadside Picnic"),
                "Foundation", List.of("Hyperion"),
                "Hyperion", List.of("Roadside Picnic"));
        System.out.println(steps(similar, "Dune", "Roadside Picnic") + " " + steps(similar, "Dune", "Emma"));
    }
}
פלטOutput
2 -1

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

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