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.
일반적인 배열 문제
- beberapa数组任务反复出现:求和、找最大值、找最小值或计数。
- 모두 같은 원리를 사용합니다: 추측을 시작하고, 루프하면서 업데이트합니다.
- 이러한 패턴은 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. · 출력을 보려면 '실행'을 클릭하세요.