Array algorithms: max, count, search, average · Algoritmos de array: 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.
Tarefas comuns de array
- Algumas tarefas de array aparecem repetidamente: encontrar a soma, o maior, o menor, ou contar itens.
- Cada uma usa a mesma ideia: comece com um palpite, depois faça o loop e atualize.
- Esses padrões aparecem o tempo todo no exame 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).
Soma e contagem
- Mantenha um total acumulado que comece em 0, e some cada valor.
- Para contar itens que passam em um teste, comece um contador em 0 e adicione 1 quando o teste for verdadeiro.
- Abaixo contamos quantos valores são pares (
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.
Encontrar o máximo
- Comece supondo que o primeiro valor é o maior:
int max = a[0];. - Faça o loop pelo resto. Se um valor for maior que
max, torne-o o novomax. - Isso funciona para números negativos também, porque o palpite vem do próprio array.
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.
Encontrar o mínimo
- O mínimo usa a mesma estrutura — basta inverter o teste para
<. - Comece com
int min = a[0];e mantenha o menor valor que você vir. - Nunca inicie
minem 0; um valor real do array é uma boa primeira suposição.
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".
Buscar um valor
- Para encontrar onde um valor está, faça o loop do índice e compare cada elemento.
- Retorne o índice assim que encontrá-lo.
- Se o loop terminar sem correspondência, retorne
-1para significar "não encontrado".
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.
Média
- Média = soma dividida pela contagem. A contagem é
a.length. - Para obter um decimal, divida por
(double) a.length, para que a matemática não seja divisão inteira. (double)converte o comprimento em decimal antes da divisão.
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.
Erros comuns
- Comece um max ou min do primeiro elemento, depois compare o resto.
- Não leia além de
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.
Agora você tenta
- Cada tarefa completa um método que o Harness chama com vários arrays.
- Reutilize os padrões acima: um total acumulado, um "melhor até agora", ou um contador.
- Pressione Run para compilar, depois Check answer.
Scanning an array for the max · Varrendo um array para encontrar o máximo
One pass keeps a running max, updating it when a bigger value appears. · Uma passagem mantém um máximo corrente, atualizando-o quando um valor maior aparece.
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. · Complete max(int[] a) para que ele retorne o maior valor no array. Você pode assumir que o array tem pelo menos um valor. Deve funcionar com números negativos também.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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. · Complete countEven(int[] a) para que ele retorne quantos valores são pares. Um valor é par quando v % 2 == 0. Um array vazio retorna 0.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete indexOf(int[] a, int target). Return the index of the first · primeiro time · tempo target appears. If it is not in the array, return -1. · Complete indexOf(int[] a, int target). Retorne o índice da primeira vez que target aparece. Se não estiver no array, retorne -1.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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. · Complete average(int[] a). Retorne a média dos valores como um double. Divida por (double) a.length para obter um decimal, não divisão inteira. Você pode assumir que o array não está vazio.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.