Array algorithms: max, count, search, average · אלגוריתמי מערכים: מקסימום, ספירה, חיפוש, ממוצע
Common array jobs
- Some array tasks come up again and again: find the sum, the biggest, the smallest, or count items.
- Each one uses the same idea: start with a guess, then loop and update it.
- These patterns appear all the time on the AP CSA exam.
משימות נפוצות עם מערכים
- משימות מסוימות על מערכים מופיעות שוב ושוב: למצוא את ה-סכום, את ה-גדול ביותר, את ה-קטן ביותר או לספור פריטים.
- כל אחת מהן משתמשת באותה רעיון: להתחיל בניחוש, ולאחר מכן לעבור על המערכת ולעדכן אותו.
- דפוסי אלו מופיעים כל הזמן במבחן AP CSA.
Sum and count
- Keep a running total that starts at 0, and add each value.
- To count items that pass a test, start a counter at 0 and add 1 when the test is true.
- Below we count how many values are even (
v % 2 == 0).
סכום וספירה
- שמרו על סכום מצטבר שמתחיל ב-0, והוסיפו כל ערך.
- כדי לספור פריטים שעומדים במבחן, התחילו סופר ב-0 והוסיפו 1 כאשר הבדיקה היא נכונה.
- למטה אנו סופרים כמה ערכים הם זוגיים (
v % 2 == 0).
public class Main {
public static void main(String[] args) {
int[] a = {3, 4, 7, 10};
int evens = 0;
for (int v : a) {
if (v % 2 == 0) {
evens = evens + 1;
}
}
System.out.println(evens); // 2
}
}
Find the maximum
- Start by guessing the first value is the biggest:
int max = a[0];. - Loop through the rest. If a value is bigger than
max, make it the newmax. - This works for negative numbers too, because the guess comes from the array itself.
מציאת המקסימום
- התחילו בהנחה שהערך הראשון הוא הגדול ביותר:
int max = a[0];. - עבור על שאר האלמנטים. אם ערך גדול יותר מ-
max, הפוך אותו לmaxחדש. - זה עובד גם עבור מספרים שליליים, כי הניחוש מגיע מהמערכת עצמה.
public class Main {
public static void main(String[] args) {
int[] a = {3, 9, 2, 7};
int max = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] > max) {
max = a[i];
}
}
System.out.println(max); // 9
}
}
Find the minimum
- The minimum uses the same shape — just flip the test to
<. - Start with
int min = a[0];and keep the smallest value you see. - Never start
minat 0; a real value from the array is a safe first guess.
מציאת המינימום
- המינימום משתמש באותה צורה – רק הפכו את הבדיקה ל-
<. - התחילו עם
int min = a[0];ושמרו על הערך הקטן ביותר שראיתם. - לעולם אל תתחילו עם
minבערך 0; ערך אמיתי מהמערכת הוא ניחוש ראשון בטוח.
public class Main {
public static void main(String[] args) {
int[] a = {3, 9, 2, 7};
int min = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < min) {
min = a[i];
}
}
System.out.println(min); // 2
}
}
Search for a value
- To find where a value is, loop the index and compare each element.
- Return the index as soon as you find it.
- If the loop finishes with no match, return
-1to mean "not found".
חיפוש ערך
- למצוא איפה ערך נמצא, חלוק את האינדקס והשווה כל אלמנט.
- החזר את האינדקס ברגע שמצאת אותו.
- אם החיפוש מסתיים ללא התאמה, החזר
-1כדי לציין "לא נמצא".
public class Main {
public static void main(String[] args) {
int[] a = {5, 8, 13, 21};
int target = 13;
int found = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == target) {
found = i;
break; // stop at the first match
}
}
System.out.println(found); // 2
}
}
Average
- Average = sum divided by count. The count is
a.length. - To get a decimal, divide by
(double) a.length, so the math is not integer division. (double)turns the length into a decimal before the division.
ממוצע
- ממוצע = סכום חלקי למספר. מספר זה הוא
a.length. - כדי לקבל תוצאה בעלת נקודה עשרית, חלק ב-
(double) a.length, כך שהחישוב לא יהיה חילוק שלם. (double)ממיר את האורך לערך עם נקודה עשרית לפני החילוק.
public class Main {
public static void main(String[] args) {
int[] a = {2, 3, 10};
int total = 0;
for (int v : a) {
total = total + v;
}
double avg = total / (double) a.length;
System.out.println(avg); // 5.0
}
}
Common mistakes
- Start a max or min from the first element, then compare the rest.
- Do not read past
a.length - 1.
טעויות נפוצות
- התחל מקסימום או מינימום מהאלמנט הראשון, ואז השווה לשאר.
- אל תעבור מעבר ל-
a.length - 1.
Now you try
- Each task completes a method the Harness calls with several arrays.
- Reuse the patterns above: a running total, a "best so far", or a counter.
- Press Run to compile, then Check answer.
כעת תנסו בעצמכם
- כל משימה משלימה שיטה שה-Harness קורא לה עם כמה מערכים.
- השתמש בחוזרים בדגמים הנ
- לחץ על Run להתקפלה, ולאחר מכן לחץ על Check answer.
Scanning an array for the max · סריקת מערך למציאת המקסימום
One pass keeps a running max, updating it when a bigger value appears. · מעבר אחד שומר על מקסימום נצחי, ומעדכן אותו כאשר מופיע ערך גדול יותר.
Complete max(int[] a) so it returns the largest value in the array. You may assume the array has at least one value. It must work with negative numbers too. · השלם max(int[] a) כך שיחזיר את הערך הגדול ביותר במערך. ניתן להניח שהמערך מכיל לפחות ערך אחד. הוא חייב לעבוד גם עם מספרים שליליים.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete countEven(int[] a) so it returns how many values are even. A value is even when v % 2 == 0. An empty array returns 0. · השלם countEven(int[] a) כך שיחזיר כמה ערכים הם זוגיים. ערך הוא זוגי כאשר v % 2 == 0. מערך ריק מחזיר 0.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete indexOf(int[] a, int target). Return the index of the first time target appears. If it is not in the array, return -1. · השלם indexOf(int[] a, int target). החזר את האינדקס של הפעם הראשונה שבה target מופיע. אם הוא לא נמצא במערך, החזר -1.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Complete average(int[] a). Return the average of the values as a double. Divide by (double) a.length so you get a decimal, not integer division. You may assume the array is not empty. · השלם average(int[] a). החזר את הממוצע של הערכים כמספר עשרוני double. חלק ב(double) a.length כדי לקבל ערך עשרוני ולא חלוקה שלמה. ניתן להניח שהמערך אינו ריק.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.