Collections לעומקCollections in depth
List, Set, Map ו-Queue, מימושים שונים, סיבוכיות זמן, ומתי לבחור מה.
List, Set, Map and Queue, different implementations, time complexity, and when to choose which.
דפים ייחודייםUnique pages
תזכורת: מה ביקשוReminder: the task
ברשימת ביקורים home, about, home, shop, about, cart. הדפיסו את הדפים בלי כפולים לפי סדר הביקור הראשון ([home, about, shop, cart]), ואז 2 repeats.
A list of visits home, about, home, shop, about, cart. Print the pages without duplicates in order of first visit ([home, about, shop, cart]), then 2 repeats.
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] args) {
List<String> visits = List.of("home", "about", "home", "shop", "about", "cart");
Set<String> unique = new LinkedHashSet<>(visits);
System.out.println(unique);
System.out.println(visits.size() - unique.size() + " repeats");
}
}[home, about, shop, cart] 2 repeats
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שכיחות ממוינתSorted frequencies
תזכורת: מה ביקשוReminder: the task
ספרו את המילים של the cat and the hat and the bat ב-TreeMap (עם merge), הדפיסו את המפה, ואז את המפתח הראשון והאחרון: and the.
Count the words of the cat and the hat and the bat in a TreeMap (with merge), print the map, then the first and last keys: and the.
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
String text = "the cat and the hat and the bat";
TreeMap<String, Integer> freq = new TreeMap<>();
for (String w : text.split(" ")) {
freq.merge(w, 1, Integer::sum);
}
System.out.println(freq);
System.out.println(freq.firstKey() + " " + freq.lastKey());
}
}{and=2, bat=1, cat=1, hat=1, the=3}
and theיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
סוגריים מאוזניםBalanced brackets
תזכורת: מה ביקשוReminder: the task
static boolean balanced(String s) בודקת שכל סוגר נסגר בסוג הנכון ובסדר הנכון, בעזרת מחסנית (ArrayDeque). הדפיסו true false false עבור {[()]}, ([)], ((.
static boolean balanced(String s) checks that every bracket closes with the right kind in the right order, using a stack (ArrayDeque). Print true false false for {[()]}, ([)], ((.
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
static boolean balanced(String s) {
Deque<Character> open = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
open.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (open.isEmpty()) {
return false;
}
char o = open.pop();
if ((c == ')' && o != '(') || (c == ']' && o != '[') || (c == '}' && o != '{')) {
return false;
}
}
}
return open.isEmpty();
}
public static void main(String[] args) {
System.out.println(balanced("{[()]}") + " " + balanced("([)]") + " " + balanced("(("));
}
}true false false
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
משימות לפי עדיפותTasks by priority
תזכורת: מה ביקשוReminder: the task
record Task(String name, int priority) implements Comparable<Task> (1 הכי דחוף). הכניסו ל-PriorityQueue שלוש משימות והוציאו עד שריק: fix server, write report, lunch.
record Task(String name, int priority) implements Comparable<Task> (1 is most urgent). Put three tasks in a PriorityQueue and take them out until empty: fix server, write report, lunch.
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Task> tasks = new PriorityQueue<>();
tasks.add(new Task("write report", 2));
tasks.add(new Task("fix server", 1));
tasks.add(new Task("lunch", 3));
while (!tasks.isEmpty()) {
System.out.println(tasks.poll().name());
}
}
}
record Task(String name, int priority) implements Comparable<Task> {
public int compareTo(Task other) {
return Integer.compare(priority, other.priority);
}
}fix server write report lunch
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צייד באגים: מחיקה תוך כדי מעברBug hunter: removing while looping
תזכורת: מה ביקשוReminder: the task
התוכנית מוחקת מילים קצרות (פחות מ-3 אותיות) וקורסת. תקנו עם Iterator ו-it.remove() כך שיודפס [tree, green].
The program removes short words (under 3 letters) and crashes. Fix it with an Iterator and it.remove() so it prints [tree, green].
סימולציה: הפתרון רץ שורה אחרי שורה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 where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("a", "tree", "is", "green"));
Iterator<String> it = words.iterator();
while (it.hasNext()) {
if (it.next().length() < 3) {
it.remove();
}
}
System.out.println(words);
}
}[tree, green]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 25: אינדקס מהירShelf, step 25: a fast index
תזכורת: מה ביקשוReminder: the task
Index מחזיק שתי מפות: סופר → רשימת כותרים (TreeMap<String, List<String>>), וז'אנר → כותרים ממוינים (TreeMap<String, Set<String>>). add, byAuthor ו-byGenre (רשימה ריקה כשאין). הדפיסו [Emma, Persuasion], [Children of Dune, Dune], [].
Index holds two maps: author → list of titles (TreeMap<String, List<String>>), and genre → sorted titles (TreeMap<String, Set<String>>). add, byAuthor and byGenre (empty when missing). Print [Emma, Persuasion], [Children of Dune, Dune], [].
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
Index idx = new Index();
idx.add(new Book("Emma", "Austen", "novel"));
idx.add(new Book("Dune", "Herbert", "scifi"));
idx.add(new Book("Persuasion", "Austen", "novel"));
idx.add(new Book("Children of Dune", "Herbert", "scifi"));
System.out.println(idx.byAuthor("Austen"));
System.out.println(idx.byGenre("scifi"));
System.out.println(idx.byAuthor("Joyce"));
}
}
record Book(String title, String author, String genre) {
}
class Index {
private final Map<String, List<String>> authors = new TreeMap<>();
private final Map<String, Set<String>> genres = new TreeMap<>();
void add(Book b) {
authors.computeIfAbsent(b.author(), k -> new ArrayList<>()).add(b.title());
genres.computeIfAbsent(b.genre(), k -> new TreeSet<>()).add(b.title());
}
List<String> byAuthor(String author) {
return authors.getOrDefault(author, List.of());
}
Set<String> byGenre(String genre) {
return genres.getOrDefault(genre, Set.of());
}
}[Emma, Persuasion] [Children of Dune, Dune] []
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מטמון LRUAn LRU cache
תזכורת: מה ביקשוReminder: the task
class Lru<K, V> extends LinkedHashMap<K, V> עם קיבולת. בנאי super(16, 0.75f, true) (סדר לפי גישה) ודריסה של removeEldestEntry. עם קיבולת 2: שימו a, b, קראו a, שימו c. הדפיסו את המפתחות: [a, c] (b, שהכי פחות היה בשימוש, נזרק).
class Lru<K, V> extends LinkedHashMap<K, V> with a capacity. Constructor super(16, 0.75f, true) (access order) and an override of removeEldestEntry. With capacity 2: put a, b, get a, put c. Print the keys: [a, c] (b, the least recently used, was dropped).
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Lru<String, Integer> cache = new Lru<>(2);
cache.put("a", 1);
cache.put("b", 2);
cache.get("a");
cache.put("c", 3);
System.out.println(cache.keySet());
}
}
class Lru<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
Lru(int capacity) {
super(16, 0.75f, true);
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}[a, c]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
השנה הקרובהThe nearest year
תזכורת: מה ביקשוReminder: the task
TreeSet של שנים 1815, 1922, 1949, 1965, 2004. הדפיסו את הקרובה מלמטה ומלמעלה ל-1950 (1949 1965), את השנים בין 1900 ל-2000 ([1922, 1949, 1965]), ואז null [2004, 1965, 1949, 1922, 1815] (higher(2004) והסדר ההפוך).
A TreeSet of the years 1815, 1922, 1949, 1965, 2004. Print the nearest below and above 1950 (1949 1965), the years between 1900 and 2000 ([1922, 1949, 1965]), then null [2004, 1965, 1949, 1922, 1815] (higher(2004) and the reversed order).
סימולציה: הפתרון רץ שורה אחרי שורה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
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Integer> years = new TreeSet<>(List.of(1815, 1922, 1949, 1965, 2004));
System.out.println(years.floor(1950) + " " + years.ceiling(1950));
System.out.println(years.subSet(1900, 2000));
System.out.println(years.higher(2004) + " " + years.descendingSet());
}
}1949 1965 [1922, 1949, 1965] null [2004, 1965, 1949, 1922, 1815]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.