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) を完成させ、配列の最大値を返すようにしなさい。配列には少なくとも1つの値があるものと仮定してください。負の数でも動作する必要があります。
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. · 実行ボタンをクリックして出力を確認してください。