Array algorithms: max, count, search, average · Algoritmos de arrays: 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.
Tareas comunes con arreglos
- Algunas tareas con arreglos aparecen una y otra vez: encontrar la suma, el valor más grande, el valor más pequeño o contar elementos.
- Cada una utiliza la misma idea: comenzar con una suposición, luego iterar y actualizarla.
- Estos patrones aparecen constantemente en el examen 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).
Suma y conteo
- Mantén un total acumulado que comience en 0 y suma cada valor.
- Para contar elementos que pasan una condición, inicia un contador en 0 y súmale 1 cuando la condición sea verdadera.
- A continuación se cuenta cuántos valores son 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 el máximo
- Comienza asumiendo que el primer valor es el más grande:
int max = a[0];. - Itera sobre el resto. Si un valor es mayor que
max, conviértelo en el nuevomax. - Esto funciona también para números negativos, porque la suposición inicial proviene del propio arreglo.
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 el mínimo
- El mínimo tiene la misma estructura, solo invierte la condición a
<. - Inicia con
int min = a[0];y guarda el valor más pequeño que encuentres. - Nunca inicies
minen 0; un valor real del arreglo es una primera suposición segura.
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 un valor
- Para encontrar dónde está un valor, itera los índices y compara cada elemento.
- Retorna el índice tan pronto como lo encuentres.
- Si el bucle termina sin encontrar coincidencia, retorna
-1para indicar "no 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.
Promedio
- Promedio = suma dividida por el conteo. El conteo es
a.length. - Para obtener un decimal, divide por
(double) a.lengthpara evitar la división entera. (double)convierte la longitud en un decimal antes de la división.
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.
Errores comunes
- Inicia un máximo o mínimo desde el primer elemento, luego compara el resto.
- No accedas a posiciones beyond
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.
Ahora tú intentas
- Cada tarea completa un método que el Harness llama con varios arreglos.
- Reutiliza los patrones anteriores: un total acumulado, un "mejor hasta ahora" o un contador.
- Presiona Run (Ejecutar) para compilar, luego Check answer (Verificar respuesta).
Scanning an array for the max · Escaneo de un array para el máximo
One pass keeps a running max, updating it when a bigger value appears. · Un solo recorrido mantiene un máximo acumulado, actualizándolo cuando aparece un valor mayor.
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. · Completa max(int[] a) para que devuelva el valor más grande del array. Puedes asumir que el array tiene al menos un valor. Debe funcionar también con números negativos.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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. · Completa countEven(int[] a) para que devuelva cuántos valores son pares. Un valor es par cuando v % 2 == 0. Un array vacío devuelve 0.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete indexOf(int[] a, int target). Return the index of the first · primero time · tiempo target appears. If it is not in the array, return -1. · Completa indexOf(int[] a, int target). Devuelve el índice de la primera vez que aparece target. Si no está en el array, devuelve -1.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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. · Completa average(int[] a). Devuelve el promedio de los valores como double. Divide por (double) a.length para obtener un decimal, no una división entera. Puedes asumir que el array no está vacío.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.