Menu
Coddy logo textTech

מתמטיקה - חיתוך של HashSet

חלק מהיחידה לוגיקה וזרימת תוכנית במסלול ה-C# של Coddy. שיעור 63 מתוך 66.

החיתוך של שתי קבוצות מכיל רק את האיברים שמופיעים בשתי הקבוצות.

צרו שתי קבוצות HashSet:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6, 7 };

כדי למצוא את החיתוך, השתמשו בשיטה IntersectWith:

set1.IntersectWith(set2);

לאחר הרצת הקוד הזה, set1 יכיל:

{ 3, 4, 5 }

המתודה IntersectWith משנה את הקבוצה שעליה היא נקראת, ומשאירה בה רק את האיברים שקיימים בשתי הקבוצות.

כדי ליצור קבוצה חדשה עם החיתוך בלי לשנות את הקבוצות המקוריות, אפשר:

HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);
challenge icon

אתגר

בינוני

צרו מתודה בשם FindCommonElements שמקבלת שני ארגומנטים:

  • HashSet של מספרים שלמים (set1)
  • HashSet של מספרים שלמים (set2)

המתודה צריכה להחזיר HashSet חדש שמכיל רק את האיברים שמופיעים בשתי הקבוצות (החיתוך).

נסו בעצמכם

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

class Program {
    public static HashSet<int> FindCommonElements(HashSet<int> set1, HashSet<int> set2) {
        // כתבו את הקוד שלכם כאן
        return null;
    }
    
    static void Main(string[] args) {
        // קראו את השורה הראשונה עבור הקבוצה הראשונה
        string line1 = Console.ReadLine();
        HashSet<int> set1 = new HashSet<int>();
        
        // בדקו אם הקבוצה הראשונה היא בפורמט של מערך JSON
        if (line1 != null && line1.StartsWith("[") && line1.EndsWith("]")) {
            try {
                // חלצו את התוכן שבין הסוגריים המרובעים
                string arrayContent = line1.Substring(1, line1.Length - 2);
                
                // נסו לפענח את התוכן של מערך JSON
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values) {
                    // הסירו מירכאות, אם ישנן
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\"")) {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // המירו למספר שלם והוסיפו לקבוצה
                    if (int.TryParse(cleanValue, out int num)) {
                        set1.Add(num);
                    }
                }
            }
            catch (Exception ex) {
                Console.WriteLine($"Error parsing first set: {ex.Message}");
                return;
            }
        }
        else {
            // עבדו את הקלט המסורתי המופרד ברווחים עבור הקבוצה הראשונה
            string[] input1 = line1.Split();
            foreach (string s in input1) {
                if (int.TryParse(s, out int num)) {
                    set1.Add(num);
                }
            }
        }
        
        // קראו את השורה השנייה עבור הקבוצה השנייה
        string line2 = Console.ReadLine();
        HashSet<int> set2 = new HashSet<int>();
        
        // בדקו אם הקבוצה השנייה היא בפורמט של מערך JSON
        if (line2 != null && line2.StartsWith("[") && line2.EndsWith("]")) {
            try {
                // חלצו את התוכן שבין הסוגריים המרובעים
                string arrayContent = line2.Substring(1, line2.Length - 2);
                
                // נסו לפענח את התוכן של מערך JSON
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values) {
                    // הסירו מירכאות, אם ישנן
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\"")) {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // המירו למספר שלם והוסיפו לקבוצה
                    if (int.TryParse(cleanValue, out int num)) {
                        set2.Add(num);
                    }
                }
            }
            catch (Exception ex) {
                Console.WriteLine($"Error parsing second set: {ex.Message}");
                return;
            }
        }
        else {
            // עבדו את הקלט המסורתי המופרד ברווחים עבור הקבוצה השנייה
            string[] input2 = line2.Split();
            foreach (string s in input2) {
                if (int.TryParse(s, out int num)) {
                    set2.Add(num);
                }
            }
        }
        
        // מצאו איברים משותפים
        HashSet<int> common = FindCommonElements(set1, set2);
        
        // הדפס את התוצאה (ממוינת)
        Console.WriteLine(string.Join(" ", common.OrderBy(x => x)));
    }
}
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה לוגיקה וזרימת תוכנית

תרגלו בעצמכם: קומפיילר C# אונליין