Commit a37f8b4b by Patryk Czarnik

funkcje na tablicach

parent 8bf646d1
package p09_funkcje;
public class FunkcjeNaTablicach {
static int suma(int[] t) {
int suma = 0;
for(int i = 0; i < t.length; i++) {
suma += t[i];
}
return suma;
}
static int suma_v2(int[] t) {
int suma = 0;
for(int x : t) {
suma += x;
}
return suma;
}
// dodaj i przetestuj funkcje:
// - suma_parzystych
static int suma_parzystych(int[] t) {
int suma = 0;
for(int x : t) {
if(x % 2 == 0) {
suma += x;
}
}
return suma;
}
// - ile_parzystych
static int ile_parzystych(int[] t) {
int ile = 0;
for(int x : t) {
if(x % 2 == 0) {
ile += 1;
}
}
return ile;
}
// - srednia_parzystych
// dwie strategie:
// 1) napiszę od nowa funkcję, w której przeglądam tablicę i wszystko liczę
// zalety: większa wydajność (dane przeglądamy tylko raz), niezależność od innych definicji
static double srednia_parzystych_v1(int[] t) {
double suma = 0;
int ile = 0;
for(int x : t) {
if(x % 2 == 0) {
suma += x;
ile++;
}
}
return suma / ile;
}
// 2) korzystamy z już zdefiniowanych funckji
// zalety: unikanie duplikacji kodu, lepsza struktura projektu, podział odpowiedzialności między metody itd - "dobre praktyki"
// DRY
static double srednia_parzystych_v2(int[] t) {
return (double)suma_parzystych(t) / ile_parzystych(t);
}
public static void main(String[] args) {
// Tutaj zapiszemy przykładowe wywołania i wyświetlimy ich wyniki
int[] a = {5, 10, 15, 0};
int[] b = {3, 5, 7, 9, 11, 13};
int[] c = {3, 2, 1, 2, 4, 11, 13};
System.out.println("suma a = " + suma(a));
System.out.println("suma_v2 a = " + suma_v2(a));
System.out.println("suma_p a = " + suma_parzystych(a));
System.out.println("suma_p b = " + suma_parzystych(b));
System.out.println(" ile_p a = " + ile_parzystych(a));
System.out.println(" ile_p b = " + ile_parzystych(b));
System.out.println("średnia_v1 a = " + srednia_parzystych_v1(a));
System.out.println("średnia_v1 b = " + srednia_parzystych_v1(b));
System.out.println("średnia_v1 c = " + srednia_parzystych_v1(c));
System.out.println("średnia_v2 a = " + srednia_parzystych_v2(a));
System.out.println("średnia_v2 b = " + srednia_parzystych_v2(b));
System.out.println("średnia_v2 c = " + srednia_parzystych_v2(c));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment