Plus Minus

Problem

Diberikan array bilangan bulat, hitung rasio elemen yang:

  • positif (> 0)

  • negatif (< 0)

  • nol (== 0)

Cetak setiap rasio dalam 6 desimal (satu per baris). Fungsi tidak mengembalikan nilai.

Input

  • Baris 1: integer n (ukuran array)

  • Baris 2: n bilangan bulat

Output

  • 3 baris: rasio positif, negatif, nol (format 0.######)

Contoh

Input:
6
-4 3 -9 0 4 1

Output:
0.500000
0.333333
0.166667

Intuisi

  1. Hitung jumlah elemen di masing-masing kategori.

  2. Bagi dengan n → rasio.

  3. Format output tepat 6 desimal (gunakan printf / String.format).


Contoh Langkah-demi-Langkah

arr = [-4, 3, -9, 0, 4, 1], n = 6
positif: 3 → 3/6 = 0.500000
negatif: 2 → 2/6 = 0.333333
nol:     1 → 1/6 = 0.166667

Algoritma

pos = 0, neg = 0, zero = 0
untuk setiap x di arr:
    jika x > 0: pos++
    jika x < 0: neg++
    jika x == 0: zero++
cetak (pos/n), (neg/n), (zero/n) → 6 desimal
  • Waktu: O(n)

  • Ruang: O(1)


Implementasi

public static void plusMinus(List<Integer> arr) {
    int n = arr.size();
    int pos = 0, neg = 0, zero = 0;
    
    for (int x : arr) {
        if (x > 0) pos++;
        else if (x < 0) neg++;
        else zero++;
    }
    
    System.out.printf("%.6f%n", (double)pos / n);
    System.out.printf("%.6f%n", (double)neg / n);
    System.out.printf("%.6f%n", (double)zero / n);
}
func plusMinus(arr []int) {
    n := len(arr)
    pos, neg, zero := 0, 0, 0
    
    for _, x := range arr {
        if x > 0 {
            pos++
        } else if x < 0 {
            neg++
        } else {
            zero++
        }
    }
    
    fmt.Printf("%.6f\n", float64(pos)/float64(n))
    fmt.Printf("%.6f\n", float64(neg)/float64(n))
    fmt.Printf("%.6f\n", float64(zero)/float64(n))
}

Ringkasan

Bahasa
Tipe Konversi
Format Output
Kompleksitas

Java

(double)x / n

printf("%.6f%n", ...)

O(n)

Go

float64(x)/float64(n)

fmt.Printf("%.6f\n", ...)

O(n)

Akurasi 6 desimal terjamin. Solusi sederhana, presisi, dan sesuai spesifikasi.

Last updated